blob: 386921c49e8d56fb784c30ffd8b9316656458c03 [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"
Argyrios Kyrtzidis53ba9562011-12-15 05:53:37 +000049#include <cstdlib>
50
51#if LLVM_ON_WIN32
52#include <windows.h>
53#include <io.h>
54#include <fcntl.h>
55#endif
56#if LLVM_ON_UNIX
57#include <unistd.h>
58#endif
Ted Kremenekfc062212009-10-19 21:44:57 +000059
Steve Naroff50398192009-08-28 15:28:48 +000060using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000061using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000062using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000063using namespace clang::cxtu;
Steve Naroff50398192009-08-28 15:28:48 +000064
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000065CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000066 if (!TU)
67 return 0;
68 CXTranslationUnit D = new CXTranslationUnitImpl();
69 D->TUData = TU;
70 D->StringPool = createCXStringPool();
Ted Kremenek15322172011-11-10 08:43:12 +000071 D->Diagnostics = 0;
Ted Kremeneka60ed472010-11-16 08:15:36 +000072 return D;
73}
74
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000075cxtu::CXTUOwner::~CXTUOwner() {
76 if (TU)
77 clang_disposeTranslationUnit(TU);
78}
79
Ted Kremenekf0e23e82010-02-17 00:41:40 +000080/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000081/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000082static RangeComparisonResult RangeCompare(SourceManager &SM,
83 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000084 SourceRange R2) {
85 assert(R1.isValid() && "First range is invalid?");
86 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000088 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000089 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000090 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000091 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000092 return RangeAfter;
93 return RangeOverlap;
94}
95
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000096/// \brief Determine if a source location falls within, before, or after a
97/// a given source range.
98static RangeComparisonResult LocationCompare(SourceManager &SM,
99 SourceLocation L, SourceRange R) {
100 assert(R.isValid() && "First range is invalid?");
101 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000102 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000103 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000104 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
105 return RangeBefore;
106 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
107 return RangeAfter;
108 return RangeOverlap;
109}
110
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111/// \brief Translate a Clang source range into a CIndex source range.
112///
113/// Clang internally represents ranges where the end location points to the
114/// start of the token at the end. However, for external clients it is more
115/// useful to have a CXSourceRange be a proper half-open interval. This routine
116/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000117CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000119 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000120 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000121 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000122 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000123 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000124 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000125 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000126 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000127 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000128 }
129
130 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
131 R.getBegin().getRawEncoding(),
132 EndLoc.getRawEncoding() };
133 return Result;
134}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000135
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000136//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000138//===----------------------------------------------------------------------===//
139
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000140static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000141static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
142
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000143
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000144RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000145 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000146}
147
Douglas Gregorb1373d02010-01-20 20:59:29 +0000148/// \brief Visit the given cursor and, if requested by the visitor,
149/// its children.
150///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151/// \param Cursor the cursor to visit.
152///
153/// \param CheckRegionOfInterest if true, then the caller already checked that
154/// this cursor is within the region of interest.
155///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156/// \returns true if the visitation should be aborted, false if it
157/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000158bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000159 if (clang_isInvalid(Cursor.kind))
160 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000161
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162 if (clang_isDeclaration(Cursor.kind)) {
163 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000164 if (!D) {
165 assert(0 && "Invalid declaration cursor");
166 return true; // abort.
167 }
168
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000169 // Ignore implicit declarations, unless it's an objc method because
170 // currently we should report implicit methods for properties when indexing.
171 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 return false;
173 }
174
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 // If we have a range of interest, and this cursor doesn't intersect with it,
176 // we're done.
177 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000178 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000179 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 return false;
181 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
Douglas Gregorb1373d02010-01-20 20:59:29 +0000183 switch (Visitor(Cursor, Parent, ClientData)) {
184 case CXChildVisit_Break:
185 return true;
186
187 case CXChildVisit_Continue:
188 return false;
189
190 case CXChildVisit_Recurse:
191 return VisitChildren(Cursor);
192 }
193
Douglas Gregorfd643772010-01-25 16:45:46 +0000194 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000195}
196
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000197static bool visitPreprocessedEntitiesInRange(SourceRange R,
198 PreprocessingRecord &PPRec,
199 CursorVisitor &Visitor) {
200 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
201 FileID FID;
202
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000203 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000204 // If the begin/end of the range lie in the same FileID, do the optimization
205 // where we skip preprocessed entities that do not come from the same FileID.
206 FID = SM.getFileID(R.getBegin());
207 if (FID != SM.getFileID(R.getEnd()))
208 FID = FileID();
209 }
210
211 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
212 Entities = PPRec.getPreprocessedEntitiesInRange(R);
213 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
214 PPRec, FID);
215}
216
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000217void CursorVisitor::visitFileRegion() {
218 if (RegionOfInterest.isInvalid())
219 return;
220
221 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
222 SourceManager &SM = Unit->getSourceManager();
223
224 std::pair<FileID, unsigned>
225 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
226 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
227
228 if (End.first != Begin.first) {
229 // If the end does not reside in the same file, try to recover by
230 // picking the end of the file of begin location.
231 End.first = Begin.first;
232 End.second = SM.getFileIDSize(Begin.first);
233 }
234
235 assert(Begin.first == End.first);
236 if (Begin.second > End.second)
237 return;
238
239 FileID File = Begin.first;
240 unsigned Offset = Begin.second;
241 unsigned Length = End.second - Begin.second;
242
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000243 if (!VisitDeclsOnly && !VisitPreprocessorLast)
244 if (visitPreprocessedEntitiesInRegion())
245 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000246
247 visitDeclsFromFileRegion(File, Offset, Length);
248
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000249 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000250 visitPreprocessedEntitiesInRegion();
251}
252
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000253static bool isInLexicalContext(Decl *D, DeclContext *DC) {
254 if (!DC)
255 return false;
256
257 for (DeclContext *DeclDC = D->getLexicalDeclContext();
258 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
259 if (DeclDC == DC)
260 return true;
261 }
262 return false;
263}
264
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000265void CursorVisitor::visitDeclsFromFileRegion(FileID File,
266 unsigned Offset, unsigned Length) {
267 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
268 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000269 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000270
271 SmallVector<Decl *, 16> Decls;
272 Unit->findFileRegionDecls(File, Offset, Length, Decls);
273
274 // If we didn't find any file level decls for the file, try looking at the
275 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000276 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000277 bool Invalid = false;
278 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
279 if (Invalid)
280 return;
281
282 SourceLocation Outer;
283 if (SLEntry.isFile())
284 Outer = SLEntry.getFile().getIncludeLoc();
285 else
286 Outer = SLEntry.getExpansion().getExpansionLocStart();
287 if (Outer.isInvalid())
288 return;
289
290 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
291 Length = 0;
292 Unit->findFileRegionDecls(File, Offset, Length, Decls);
293 }
294
295 assert(!Decls.empty());
296
297 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000298 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000299 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
300 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
301 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000302 if (D->getSourceRange().isInvalid())
303 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000304
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000305 if (isInLexicalContext(D, CurDC))
306 continue;
307
308 CurDC = dyn_cast<DeclContext>(D);
309
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000310 // We handle forward decls via ObjCClassDecl.
311 if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
312 if (InterD->isForwardDecl())
313 continue;
314 // An interface that started as a forward decl may have changed location
315 // because its @interface was parsed.
316 if (InterD->isInitiallyForwardDecl() &&
317 !SM.isInFileID(SM.getFileLoc(InterD->getLocation()), File))
318 continue;
319 }
320
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000321 if (TagDecl *TD = dyn_cast<TagDecl>(D))
322 if (!TD->isFreeStanding())
323 continue;
324
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000325 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
326 if (CompRes == RangeBefore)
327 continue;
328 if (CompRes == RangeAfter)
329 break;
330
331 assert(CompRes == RangeOverlap);
332 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000333
334 if (isa<ObjCContainerDecl>(D)) {
335 FileDI_current = &DIt;
336 FileDE_current = DE;
337 } else {
338 FileDI_current = 0;
339 }
340
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000341 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000342 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000343 }
344
345 if (VisitedAtLeastOnce)
346 return;
347
348 // No Decls overlapped with the range. Move up the lexical context until there
349 // is a context that contains the range or we reach the translation unit
350 // level.
351 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
352 : (*(DIt-1))->getLexicalDeclContext();
353
354 while (DC && !DC->isTranslationUnit()) {
355 Decl *D = cast<Decl>(DC);
356 SourceRange CurDeclRange = D->getSourceRange();
357 if (CurDeclRange.isInvalid())
358 break;
359
360 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000361 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000362 break;
363 }
364
365 DC = D->getLexicalDeclContext();
366 }
367}
368
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000369bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000370 if (!AU->getPreprocessor().getPreprocessingRecord())
371 return false;
372
Douglas Gregor788f5a12010-03-20 00:41:21 +0000373 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000374 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000375 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000376
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000377 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000378 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000379 SourceLocation B = MappedRange.getBegin();
380 SourceLocation E = MappedRange.getEnd();
381
382 if (AU->isInPreambleFileID(B)) {
383 if (SM.isLoadedSourceLocation(E))
384 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
385 PPRec, *this);
386
387 // Beginning of range lies in the preamble but it also extends beyond
388 // it into the main file. Split the range into 2 parts, one covering
389 // the preamble and another covering the main file. This allows subsequent
390 // calls to visitPreprocessedEntitiesInRange to accept a source range that
391 // lies in the same FileID, allowing it to skip preprocessed entities that
392 // do not come from the same FileID.
393 bool breaked =
394 visitPreprocessedEntitiesInRange(
395 SourceRange(B, AU->getEndOfPreambleFileID()),
396 PPRec, *this);
397 if (breaked) return true;
398 return visitPreprocessedEntitiesInRange(
399 SourceRange(AU->getStartOfMainFileID(), E),
400 PPRec, *this);
401 }
402
403 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000404 }
405
Douglas Gregor788f5a12010-03-20 00:41:21 +0000406 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000407 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
408
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000409 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000410 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
411 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000412
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000413 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000414}
415
416template<typename InputIterator>
417bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000418 InputIterator Last,
419 PreprocessingRecord &PPRec,
420 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000421 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000422 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
423 continue;
424
425 PreprocessedEntity *PPE = *First;
426 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000427 if (Visit(MakeMacroExpansionCursor(ME, TU)))
428 return true;
429
430 continue;
431 }
432
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000433 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000434 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
435 return true;
436
437 continue;
438 }
439
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000440 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000441 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
442 return true;
443
444 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000445 }
446 }
447
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000448 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000449}
450
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000452///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453/// \returns true if the visitation should be aborted, false if it
454/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000456 if (clang_isReference(Cursor.kind) &&
457 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000458 // By definition, references have no children.
459 return false;
460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000461
462 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000464 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 if (clang_isDeclaration(Cursor.kind)) {
467 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000468 if (!D)
469 return false;
470
Ted Kremenek539311e2010-02-18 18:47:01 +0000471 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000473
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000474 if (clang_isStatement(Cursor.kind)) {
475 if (Stmt *S = getCursorStmt(Cursor))
476 return Visit(S);
477
478 return false;
479 }
480
481 if (clang_isExpression(Cursor.kind)) {
482 if (Expr *E = getCursorExpr(Cursor))
483 return Visit(E);
484
485 return false;
486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000487
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000489 CXTranslationUnit tu = getCursorTU(Cursor);
490 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000491
492 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
493 for (unsigned I = 0; I != 2; ++I) {
494 if (VisitOrder[I]) {
495 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
496 RegionOfInterest.isInvalid()) {
497 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
498 TLEnd = CXXUnit->top_level_end();
499 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000500 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000501 return true;
502 }
503 } else if (VisitDeclContext(
504 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000505 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000506 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000507 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000508
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000509 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000510 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
511 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000513
Douglas Gregor7b691f332010-01-20 21:13:59 +0000514 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000516
Douglas Gregorc314aa42011-03-02 19:17:03 +0000517 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
518 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
519 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
520 return Visit(BaseTSInfo->getTypeLoc());
521 }
522 }
523 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000524
525 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
526 IBOutletCollectionAttr *A =
527 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
528 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
529 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
530 A->getInterfaceLoc(), TU));
531 }
532
Douglas Gregorb1373d02010-01-20 20:59:29 +0000533 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000534 return false;
535}
536
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000537bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000538 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
539 if (Visit(TSInfo->getTypeLoc()))
540 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000541
Ted Kremenek664cffd2010-07-22 11:30:19 +0000542 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000543 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000544
545 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000546}
547
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000548llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
549 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000550 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000551 if (Range.isInvalid())
552 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000553
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000554 switch (CompareRegionOfInterest(Range)) {
555 case RangeBefore:
556 // This declaration comes before the region of interest; skip it.
557 return llvm::Optional<bool>();
558
559 case RangeAfter:
560 // This declaration comes after the region of interest; we're done.
561 return false;
562
563 case RangeOverlap:
564 // This declaration overlaps the region of interest; visit it.
565 break;
566 }
567 }
568 return true;
569}
570
571bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
572 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
573
574 // FIXME: Eventually remove. This part of a hack to support proper
575 // iteration over all Decls contained lexically within an ObjC container.
576 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
577 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
578
579 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000580 Decl *D = *I;
581 if (D->getLexicalDeclContext() != DC)
582 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000583 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000584 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
585 if (!V.hasValue())
586 continue;
587 if (!V.getValue())
588 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000589 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000590 return true;
591 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000592 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000593}
594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
596 llvm_unreachable("Translation units are visited directly by Visit()");
597 return false;
598}
599
Richard Smith162e1c12011-04-15 14:24:37 +0000600bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
601 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
602 return Visit(TSInfo->getTypeLoc());
603
604 return false;
605}
606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
608 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
609 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000610
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000611 return false;
612}
613
614bool CursorVisitor::VisitTagDecl(TagDecl *D) {
615 return VisitDeclContext(D);
616}
617
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000618bool CursorVisitor::VisitClassTemplateSpecializationDecl(
619 ClassTemplateSpecializationDecl *D) {
620 bool ShouldVisitBody = false;
621 switch (D->getSpecializationKind()) {
622 case TSK_Undeclared:
623 case TSK_ImplicitInstantiation:
624 // Nothing to visit
625 return false;
626
627 case TSK_ExplicitInstantiationDeclaration:
628 case TSK_ExplicitInstantiationDefinition:
629 break;
630
631 case TSK_ExplicitSpecialization:
632 ShouldVisitBody = true;
633 break;
634 }
635
636 // Visit the template arguments used in the specialization.
637 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
638 TypeLoc TL = SpecType->getTypeLoc();
639 if (TemplateSpecializationTypeLoc *TSTLoc
640 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
641 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
642 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
643 return true;
644 }
645 }
646
647 if (ShouldVisitBody && VisitCXXRecordDecl(D))
648 return true;
649
650 return false;
651}
652
Douglas Gregor74dbe642010-08-31 19:31:58 +0000653bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
654 ClassTemplatePartialSpecializationDecl *D) {
655 // FIXME: Visit the "outer" template parameter lists on the TagDecl
656 // before visiting these template parameters.
657 if (VisitTemplateParameters(D->getTemplateParameters()))
658 return true;
659
660 // Visit the partial specialization arguments.
661 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
662 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
663 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
664 return true;
665
666 return VisitCXXRecordDecl(D);
667}
668
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000669bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000670 // Visit the default argument.
671 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
672 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
673 if (Visit(DefArg->getTypeLoc()))
674 return true;
675
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000676 return false;
677}
678
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000679bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
680 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000681 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000682 return false;
683}
684
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000685bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
686 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
687 if (Visit(TSInfo->getTypeLoc()))
688 return true;
689
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000690 // Visit the nested-name-specifier, if present.
691 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
692 if (VisitNestedNameSpecifierLoc(QualifierLoc))
693 return true;
694
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000695 return false;
696}
697
Douglas Gregora67e03f2010-09-09 21:42:20 +0000698/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000699static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
700 CXXCtorInitializer const * const *X
701 = static_cast<CXXCtorInitializer const * const *>(Xp);
702 CXXCtorInitializer const * const *Y
703 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000704
705 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
706 return -1;
707 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
708 return 1;
709 else
710 return 0;
711}
712
Douglas Gregorb1373d02010-01-20 20:59:29 +0000713bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000714 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
715 // Visit the function declaration's syntactic components in the order
716 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000717 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000718 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
719
720 // If we have a function declared directly (without the use of a typedef),
721 // visit just the return type. Otherwise, just visit the function's type
722 // now.
723 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
724 (!FTL && Visit(TL)))
725 return true;
726
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000727 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000728 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
729 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000730 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000731
732 // Visit the declaration name.
733 if (VisitDeclarationNameInfo(ND->getNameInfo()))
734 return true;
735
736 // FIXME: Visit explicitly-specified template arguments!
737
738 // Visit the function parameters, if we have a function type.
739 if (FTL && VisitFunctionTypeLoc(*FTL, true))
740 return true;
741
742 // FIXME: Attributes?
743 }
744
Sean Hunt10620eb2011-05-06 20:44:56 +0000745 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000746 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
747 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000748 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000749 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
750 IEnd = Constructor->init_end();
751 I != IEnd; ++I) {
752 if (!(*I)->isWritten())
753 continue;
754
755 WrittenInits.push_back(*I);
756 }
757
758 // Sort the initializers in source order
759 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000760 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761
762 // Visit the initializers in source order
763 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000764 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000765 if (Init->isAnyMemberInitializer()) {
766 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000767 Init->getMemberLocation(), TU)))
768 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000769 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
770 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000771 return true;
772 }
773
774 // Visit the initializer value.
775 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000776 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000777 return true;
778 }
779 }
780
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000781 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000782 return true;
783 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregorb1373d02010-01-20 20:59:29 +0000785 return false;
786}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
789 if (VisitDeclaratorDecl(D))
790 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000791
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000792 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000793 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 return false;
796}
797
798bool CursorVisitor::VisitVarDecl(VarDecl *D) {
799 if (VisitDeclaratorDecl(D))
800 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000803 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 return false;
806}
807
Douglas Gregor84b51d72010-09-01 20:16:53 +0000808bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
809 if (VisitDeclaratorDecl(D))
810 return true;
811
812 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
813 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000814 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000815
816 return false;
817}
818
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000819bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
820 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
821 // before visiting these template parameters.
822 if (VisitTemplateParameters(D->getTemplateParameters()))
823 return true;
824
825 return VisitFunctionDecl(D->getTemplatedDecl());
826}
827
Douglas Gregor39d6f072010-08-31 19:02:00 +0000828bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
829 // FIXME: Visit the "outer" template parameter lists on the TagDecl
830 // before visiting these template parameters.
831 if (VisitTemplateParameters(D->getTemplateParameters()))
832 return true;
833
834 return VisitCXXRecordDecl(D->getTemplatedDecl());
835}
836
Douglas Gregor84b51d72010-09-01 20:16:53 +0000837bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
838 if (VisitTemplateParameters(D->getTemplateParameters()))
839 return true;
840
841 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
842 VisitTemplateArgumentLoc(D->getDefaultArgument()))
843 return true;
844
845 return false;
846}
847
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000849 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
850 if (Visit(TSInfo->getTypeLoc()))
851 return true;
852
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 PEnd = ND->param_end();
855 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000856 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 return true;
858 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000859
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000861 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000862 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000863
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000864 return false;
865}
866
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000867template <typename DeclIt>
868static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
869 SourceManager &SM, SourceLocation EndLoc,
870 SmallVectorImpl<Decl *> &Decls) {
871 DeclIt next = *DI_current;
872 while (++next != DE_current) {
873 Decl *D_next = *next;
874 if (!D_next)
875 break;
876 SourceLocation L = D_next->getLocStart();
877 if (!L.isValid())
878 break;
879 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
880 *DI_current = next;
881 Decls.push_back(D_next);
882 continue;
883 }
884 break;
885 }
886}
887
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000888namespace {
889 struct ContainerDeclsSort {
890 SourceManager &SM;
891 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
892 bool operator()(Decl *A, Decl *B) {
893 SourceLocation L_A = A->getLocStart();
894 SourceLocation L_B = B->getLocStart();
895 assert(L_A.isValid() && L_B.isValid());
896 return SM.isBeforeInTranslationUnit(L_A, L_B);
897 }
898 };
899}
900
Douglas Gregora59e3902010-01-21 23:27:09 +0000901bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000902 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
903 // an @implementation can lexically contain Decls that are not properly
904 // nested in the AST. When we identify such cases, we need to retrofit
905 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000906 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000907 return VisitDeclContext(D);
908
909 // Scan the Decls that immediately come after the container
910 // in the current DeclContext. If any fall within the
911 // container's lexical region, stash them into a vector
912 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000913 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000914 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000915 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000916 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000917 if (DI_current) {
918 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
919 DeclsInContainer);
920 } else {
921 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
922 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000923 }
924 }
925
926 // The common case.
927 if (DeclsInContainer.empty())
928 return VisitDeclContext(D);
929
930 // Get all the Decls in the DeclContext, and sort them with the
931 // additional ones we've collected. Then visit them.
932 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
933 I!=E; ++I) {
934 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000935 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
936 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000937 continue;
938 DeclsInContainer.push_back(subDecl);
939 }
940
941 // Now sort the Decls so that they appear in lexical order.
942 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
943 ContainerDeclsSort(SM));
944
945 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000946 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000947 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000948 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000949 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
950 if (!V.hasValue())
951 continue;
952 if (!V.getValue())
953 return false;
954 if (Visit(Cursor, true))
955 return true;
956 }
957 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000958}
959
Douglas Gregorb1373d02010-01-20 20:59:29 +0000960bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000961 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
962 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000963 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000964
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000965 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
966 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
967 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000968 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000969 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000970
Douglas Gregora59e3902010-01-21 23:27:09 +0000971 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000972}
973
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000974bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
975 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
976 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
977 E = PID->protocol_end(); I != E; ++I, ++PL)
978 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
979 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000980
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000981 return VisitObjCContainerDecl(PID);
982}
983
Ted Kremenek23173d72010-05-18 21:09:07 +0000984bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000985 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000986 return true;
987
Ted Kremenek23173d72010-05-18 21:09:07 +0000988 // FIXME: This implements a workaround with @property declarations also being
989 // installed in the DeclContext for the @interface. Eventually this code
990 // should be removed.
991 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
992 if (!CDecl || !CDecl->IsClassExtension())
993 return false;
994
995 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
996 if (!ID)
997 return false;
998
999 IdentifierInfo *PropertyId = PD->getIdentifier();
1000 ObjCPropertyDecl *prevDecl =
1001 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1002
1003 if (!prevDecl)
1004 return false;
1005
1006 // Visit synthesized methods since they will be skipped when visiting
1007 // the @interface.
1008 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001009 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001010 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001011 return true;
1012
1013 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001014 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001015 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001016 return true;
1017
1018 return false;
1019}
1020
Douglas Gregorb1373d02010-01-20 20:59:29 +00001021bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001022 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001023 if (D->getSuperClass() &&
1024 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001026 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001027 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001029 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1030 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1031 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001032 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregora59e3902010-01-21 23:27:09 +00001035 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001036}
1037
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001038bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1039 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001040}
1041
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001043 // 'ID' could be null when dealing with invalid code.
1044 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1045 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1046 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001048 return VisitObjCImplDecl(D);
1049}
1050
1051bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1052#if 0
1053 // Issue callbacks for super class.
1054 // FIXME: No source location information!
1055 if (D->getSuperClass() &&
1056 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001057 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001058 TU)))
1059 return true;
1060#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062 return VisitObjCImplDecl(D);
1063}
1064
1065bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1066 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1067 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1068 E = D->protocol_end();
1069 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001070 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001071 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001072
1073 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001074}
1075
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001076bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001077 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
Douglas Gregoraf764722011-12-14 17:12:03 +00001078 D->getNameLoc(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001079 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001080 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001081}
1082
Douglas Gregora4ffd852010-11-17 01:03:52 +00001083bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1084 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1085 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1086
1087 return false;
1088}
1089
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001090bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1091 return VisitDeclContext(D);
1092}
1093
Douglas Gregor69319002010-08-31 23:48:11 +00001094bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001095 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001096 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1097 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001098 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001099
1100 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1101 D->getTargetNameLoc(), TU));
1102}
1103
Douglas Gregor7e242562010-09-01 19:52:22 +00001104bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001106 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1107 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001108 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001109 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001110
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001111 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1112 return true;
1113
Douglas Gregor7e242562010-09-01 19:52:22 +00001114 return VisitDeclarationNameInfo(D->getNameInfo());
1115}
1116
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001117bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001119 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1120 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001122
1123 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1124 D->getIdentLocation(), TU));
1125}
1126
Douglas Gregor7e242562010-09-01 19:52:22 +00001127bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001128 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001129 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1130 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001131 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001132 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133
Douglas Gregor7e242562010-09-01 19:52:22 +00001134 return VisitDeclarationNameInfo(D->getNameInfo());
1135}
1136
1137bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1138 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001139 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001140 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1141 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001142 return true;
1143
Douglas Gregor7e242562010-09-01 19:52:22 +00001144 return false;
1145}
1146
Douglas Gregor01829d32010-08-31 14:41:23 +00001147bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1148 switch (Name.getName().getNameKind()) {
1149 case clang::DeclarationName::Identifier:
1150 case clang::DeclarationName::CXXLiteralOperatorName:
1151 case clang::DeclarationName::CXXOperatorName:
1152 case clang::DeclarationName::CXXUsingDirective:
1153 return false;
1154
1155 case clang::DeclarationName::CXXConstructorName:
1156 case clang::DeclarationName::CXXDestructorName:
1157 case clang::DeclarationName::CXXConversionFunctionName:
1158 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1159 return Visit(TSInfo->getTypeLoc());
1160 return false;
1161
1162 case clang::DeclarationName::ObjCZeroArgSelector:
1163 case clang::DeclarationName::ObjCOneArgSelector:
1164 case clang::DeclarationName::ObjCMultiArgSelector:
1165 // FIXME: Per-identifier location info?
1166 return false;
1167 }
1168
1169 return false;
1170}
1171
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001172bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1173 SourceRange Range) {
1174 // FIXME: This whole routine is a hack to work around the lack of proper
1175 // source information in nested-name-specifiers (PR5791). Since we do have
1176 // a beginning source location, we can visit the first component of the
1177 // nested-name-specifier, if it's a single-token component.
1178 if (!NNS)
1179 return false;
1180
1181 // Get the first component in the nested-name-specifier.
1182 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1183 NNS = Prefix;
1184
1185 switch (NNS->getKind()) {
1186 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001187 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1188 TU));
1189
Douglas Gregor14aba762011-02-24 02:36:08 +00001190 case NestedNameSpecifier::NamespaceAlias:
1191 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1192 Range.getBegin(), TU));
1193
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001194 case NestedNameSpecifier::TypeSpec: {
1195 // If the type has a form where we know that the beginning of the source
1196 // range matches up with a reference cursor. Visit the appropriate reference
1197 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001198 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001199 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1200 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1201 if (const TagType *Tag = dyn_cast<TagType>(T))
1202 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1203 if (const TemplateSpecializationType *TST
1204 = dyn_cast<TemplateSpecializationType>(T))
1205 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1206 break;
1207 }
1208
1209 case NestedNameSpecifier::TypeSpecWithTemplate:
1210 case NestedNameSpecifier::Global:
1211 case NestedNameSpecifier::Identifier:
1212 break;
1213 }
1214
1215 return false;
1216}
1217
Douglas Gregordc355712011-02-25 00:36:19 +00001218bool
1219CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001220 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001221 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1222 Qualifiers.push_back(Qualifier);
1223
1224 while (!Qualifiers.empty()) {
1225 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1226 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1227 switch (NNS->getKind()) {
1228 case NestedNameSpecifier::Namespace:
1229 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001230 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001231 TU)))
1232 return true;
1233
1234 break;
1235
1236 case NestedNameSpecifier::NamespaceAlias:
1237 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001238 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001239 TU)))
1240 return true;
1241
1242 break;
1243
1244 case NestedNameSpecifier::TypeSpec:
1245 case NestedNameSpecifier::TypeSpecWithTemplate:
1246 if (Visit(Q.getTypeLoc()))
1247 return true;
1248
1249 break;
1250
1251 case NestedNameSpecifier::Global:
1252 case NestedNameSpecifier::Identifier:
1253 break;
1254 }
1255 }
1256
1257 return false;
1258}
1259
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001260bool CursorVisitor::VisitTemplateParameters(
1261 const TemplateParameterList *Params) {
1262 if (!Params)
1263 return false;
1264
1265 for (TemplateParameterList::const_iterator P = Params->begin(),
1266 PEnd = Params->end();
1267 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001268 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001269 return true;
1270 }
1271
1272 return false;
1273}
1274
Douglas Gregor0b36e612010-08-31 20:37:03 +00001275bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1276 switch (Name.getKind()) {
1277 case TemplateName::Template:
1278 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1279
1280 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001281 // Visit the overloaded template set.
1282 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1283 return true;
1284
Douglas Gregor0b36e612010-08-31 20:37:03 +00001285 return false;
1286
1287 case TemplateName::DependentTemplate:
1288 // FIXME: Visit nested-name-specifier.
1289 return false;
1290
1291 case TemplateName::QualifiedTemplate:
1292 // FIXME: Visit nested-name-specifier.
1293 return Visit(MakeCursorTemplateRef(
1294 Name.getAsQualifiedTemplateName()->getDecl(),
1295 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001296
1297 case TemplateName::SubstTemplateTemplateParm:
1298 return Visit(MakeCursorTemplateRef(
1299 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1300 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001301
1302 case TemplateName::SubstTemplateTemplateParmPack:
1303 return Visit(MakeCursorTemplateRef(
1304 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1305 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001306 }
1307
1308 return false;
1309}
1310
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001311bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1312 switch (TAL.getArgument().getKind()) {
1313 case TemplateArgument::Null:
1314 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001315 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001316 return false;
1317
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001318 case TemplateArgument::Type:
1319 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1320 return Visit(TSInfo->getTypeLoc());
1321 return false;
1322
1323 case TemplateArgument::Declaration:
1324 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001325 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001326 return false;
1327
1328 case TemplateArgument::Expression:
1329 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001330 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001331 return false;
1332
1333 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001334 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001335 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1336 return true;
1337
Douglas Gregora7fc9012011-01-05 18:58:31 +00001338 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001339 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001340 }
1341
1342 return false;
1343}
1344
Ted Kremeneka0536d82010-05-07 01:04:29 +00001345bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1346 return VisitDeclContext(D);
1347}
1348
Douglas Gregor01829d32010-08-31 14:41:23 +00001349bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1350 return Visit(TL.getUnqualifiedLoc());
1351}
1352
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001353bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001354 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001355
1356 // Some builtin types (such as Objective-C's "id", "sel", and
1357 // "Class") have associated declarations. Create cursors for those.
1358 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001359 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001360
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001361 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001362 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001363 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001364#define BUILTIN_TYPE(Id, SingletonId)
1365#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1366#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1367#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1368#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1369#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001371
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001372 case BuiltinType::ObjCId:
1373 VisitType = Context.getObjCIdType();
1374 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001375
1376 case BuiltinType::ObjCClass:
1377 VisitType = Context.getObjCClassType();
1378 break;
1379
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380 case BuiltinType::ObjCSel:
1381 VisitType = Context.getObjCSelType();
1382 break;
1383 }
1384
1385 if (!VisitType.isNull()) {
1386 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001387 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388 TU));
1389 }
1390
1391 return false;
1392}
1393
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001394bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001395 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001396}
1397
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001398bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1399 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1400}
1401
1402bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001403 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001404 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001405
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001406 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1407}
1408
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001409bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001410 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001411}
1412
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001413bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1414 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1415 return true;
1416
John McCallc12c5bb2010-05-15 11:32:37 +00001417 return false;
1418}
1419
1420bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1421 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1422 return true;
1423
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001424 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1425 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1426 TU)))
1427 return true;
1428 }
1429
1430 return false;
1431}
1432
1433bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001434 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001435}
1436
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001437bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1438 return Visit(TL.getInnerLoc());
1439}
1440
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001441bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1442 return Visit(TL.getPointeeLoc());
1443}
1444
1445bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1446 return Visit(TL.getPointeeLoc());
1447}
1448
1449bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1450 return Visit(TL.getPointeeLoc());
1451}
1452
1453bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455}
1456
1457bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001458 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001459}
1460
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001461bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1462 return Visit(TL.getModifiedLoc());
1463}
1464
Douglas Gregor01829d32010-08-31 14:41:23 +00001465bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1466 bool SkipResultType) {
1467 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001468 return true;
1469
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001470 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001471 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001472 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001473 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001474
1475 return false;
1476}
1477
1478bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1479 if (Visit(TL.getElementLoc()))
1480 return true;
1481
1482 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001483 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001484
1485 return false;
1486}
1487
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001488bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1489 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001490 // Visit the template name.
1491 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1492 TL.getTemplateNameLoc()))
1493 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001494
1495 // Visit the template arguments.
1496 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1497 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1498 return true;
1499
1500 return false;
1501}
1502
Douglas Gregor2332c112010-01-21 20:48:56 +00001503bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1504 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1505}
1506
1507bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1508 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1509 return Visit(TSInfo->getTypeLoc());
1510
1511 return false;
1512}
1513
Sean Huntca63c202011-05-24 22:41:36 +00001514bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1515 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1516 return Visit(TSInfo->getTypeLoc());
1517
1518 return false;
1519}
1520
Douglas Gregor2494dd02011-03-01 01:34:45 +00001521bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1522 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1523 return true;
1524
1525 return false;
1526}
1527
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001528bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1529 DependentTemplateSpecializationTypeLoc TL) {
1530 // Visit the nested-name-specifier, if there is one.
1531 if (TL.getQualifierLoc() &&
1532 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1533 return true;
1534
1535 // Visit the template arguments.
1536 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1537 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1538 return true;
1539
1540 return false;
1541}
1542
Douglas Gregor9e876872011-03-01 18:12:44 +00001543bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1544 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1545 return true;
1546
1547 return Visit(TL.getNamedTypeLoc());
1548}
1549
Douglas Gregor7536dd52010-12-20 02:24:11 +00001550bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1551 return Visit(TL.getPatternLoc());
1552}
1553
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001554bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1555 if (Expr *E = TL.getUnderlyingExpr())
1556 return Visit(MakeCXCursor(E, StmtParent, TU));
1557
1558 return false;
1559}
1560
1561bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1562 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1563}
1564
Eli Friedmanb001de72011-10-06 23:00:33 +00001565bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1566 return Visit(TL.getValueLoc());
1567}
1568
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001569#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1570bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1571 return Visit##PARENT##Loc(TL); \
1572}
1573
1574DEFAULT_TYPELOC_IMPL(Complex, Type)
1575DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1576DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1577DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1578DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1579DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1580DEFAULT_TYPELOC_IMPL(Vector, Type)
1581DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1582DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1583DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1584DEFAULT_TYPELOC_IMPL(Record, TagType)
1585DEFAULT_TYPELOC_IMPL(Enum, TagType)
1586DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1587DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1588DEFAULT_TYPELOC_IMPL(Auto, Type)
1589
Ted Kremenek3064ef92010-08-27 21:34:58 +00001590bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001591 // Visit the nested-name-specifier, if present.
1592 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1593 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1594 return true;
1595
John McCall5e1cdac2011-10-07 06:10:15 +00001596 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001597 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1598 E = D->bases_end(); I != E; ++I) {
1599 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1600 return true;
1601 }
1602 }
1603
1604 return VisitTagDecl(D);
1605}
1606
Ted Kremenek09dfa372010-02-18 05:46:33 +00001607bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001608 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1609 i != e; ++i)
1610 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001611 return true;
1612
1613 return false;
1614}
1615
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001616//===----------------------------------------------------------------------===//
1617// Data-recursive visitor methods.
1618//===----------------------------------------------------------------------===//
1619
Ted Kremenek28a71942010-11-13 00:36:47 +00001620namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001621#define DEF_JOB(NAME, DATA, KIND)\
1622class NAME : public VisitorJob {\
1623public:\
1624 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1625 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001626 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001627};
1628
1629DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1630DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001631DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001632DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001633DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001634 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001635DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001636#undef DEF_JOB
1637
1638class DeclVisit : public VisitorJob {
1639public:
1640 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1641 VisitorJob(parent, VisitorJob::DeclVisitKind,
1642 d, isFirst ? (void*) 1 : (void*) 0) {}
1643 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001644 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001645 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001646 Decl *get() const { return static_cast<Decl*>(data[0]); }
1647 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001648};
Ted Kremenek035dc412010-11-13 00:36:50 +00001649class TypeLocVisit : public VisitorJob {
1650public:
1651 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1652 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1653 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1654
1655 static bool classof(const VisitorJob *VJ) {
1656 return VJ->getKind() == TypeLocVisitKind;
1657 }
1658
Ted Kremenek82f3c502010-11-15 22:23:26 +00001659 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001660 QualType T = QualType::getFromOpaquePtr(data[0]);
1661 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001662 }
1663};
1664
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001665class LabelRefVisit : public VisitorJob {
1666public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001667 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1668 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001669 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001670
1671 static bool classof(const VisitorJob *VJ) {
1672 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1673 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001674 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001675 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001676 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001677};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001678
1679class NestedNameSpecifierLocVisit : public VisitorJob {
1680public:
1681 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1682 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1683 Qualifier.getNestedNameSpecifier(),
1684 Qualifier.getOpaqueData()) { }
1685
1686 static bool classof(const VisitorJob *VJ) {
1687 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1688 }
1689
1690 NestedNameSpecifierLoc get() const {
1691 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1692 data[1]);
1693 }
1694};
1695
Ted Kremenekf64d8032010-11-18 00:02:32 +00001696class DeclarationNameInfoVisit : public VisitorJob {
1697public:
1698 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1699 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1700 static bool classof(const VisitorJob *VJ) {
1701 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1702 }
1703 DeclarationNameInfo get() const {
1704 Stmt *S = static_cast<Stmt*>(data[0]);
1705 switch (S->getStmtClass()) {
1706 default:
1707 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001708 case clang::Stmt::MSDependentExistsStmtClass:
1709 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001710 case Stmt::CXXDependentScopeMemberExprClass:
1711 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1712 case Stmt::DependentScopeDeclRefExprClass:
1713 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1714 }
1715 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001716};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001717class MemberRefVisit : public VisitorJob {
1718public:
1719 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1720 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001721 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001722 static bool classof(const VisitorJob *VJ) {
1723 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1724 }
1725 FieldDecl *get() const {
1726 return static_cast<FieldDecl*>(data[0]);
1727 }
1728 SourceLocation getLoc() const {
1729 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1730 }
1731};
Ted Kremenek28a71942010-11-13 00:36:47 +00001732class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1733 VisitorWorkList &WL;
1734 CXCursor Parent;
1735public:
1736 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1737 : WL(wl), Parent(parent) {}
1738
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001739 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001740 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001741 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001742 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001743 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001744 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001745 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001746 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001747 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001748 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001749 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001750 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001751 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001752 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001753 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001754 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001755 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001756 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001757 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001758 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001759 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1760 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001761 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001762 void VisitIfStmt(IfStmt *If);
1763 void VisitInitListExpr(InitListExpr *IE);
1764 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001765 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001766 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001767 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1768 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001769 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001770 void VisitStmt(Stmt *S);
1771 void VisitSwitchStmt(SwitchStmt *S);
1772 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001773 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001774 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001775 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001776 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001777 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001778 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001779 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001780 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1781 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001782
Ted Kremenek28a71942010-11-13 00:36:47 +00001783private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001784 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001785 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001786 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001787 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001788 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001789 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001790 void AddTypeLoc(TypeSourceInfo *TI);
1791 void EnqueueChildren(Stmt *S);
1792};
1793} // end anonyous namespace
1794
Ted Kremenekf64d8032010-11-18 00:02:32 +00001795void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1796 // 'S' should always be non-null, since it comes from the
1797 // statement we are visiting.
1798 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1799}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001800
1801void
1802EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1803 if (Qualifier)
1804 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1805}
1806
Ted Kremenek28a71942010-11-13 00:36:47 +00001807void EnqueueVisitor::AddStmt(Stmt *S) {
1808 if (S)
1809 WL.push_back(StmtVisit(S, Parent));
1810}
Ted Kremenek035dc412010-11-13 00:36:50 +00001811void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001812 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001813 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001814}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001815void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001816 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001817 if (A)
1818 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001819 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001820}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001821void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1822 if (D)
1823 WL.push_back(MemberRefVisit(D, L, Parent));
1824}
Ted Kremenek28a71942010-11-13 00:36:47 +00001825void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1826 if (TI)
1827 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1828 }
1829void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001830 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001831 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001832 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001833 }
1834 if (size == WL.size())
1835 return;
1836 // Now reverse the entries we just added. This will match the DFS
1837 // ordering performed by the worklist.
1838 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1839 std::reverse(I, E);
1840}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001841void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1842 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1843}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001844void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1845 AddDecl(B->getBlockDecl());
1846}
Ted Kremenek28a71942010-11-13 00:36:47 +00001847void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1848 EnqueueChildren(E);
1849 AddTypeLoc(E->getTypeSourceInfo());
1850}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001851void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1852 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1853 E = S->body_rend(); I != E; ++I) {
1854 AddStmt(*I);
1855 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001856}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001857void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001858VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1859 AddStmt(S->getSubStmt());
1860 AddDeclarationNameInfo(S);
1861 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1862 AddNestedNameSpecifierLoc(QualifierLoc);
1863}
1864
1865void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001866VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1867 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1868 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001869 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1870 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001871 if (!E->isImplicitAccess())
1872 AddStmt(E->getBase());
1873}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001874void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1875 // Enqueue the initializer or constructor arguments.
1876 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1877 AddStmt(E->getConstructorArg(I-1));
1878 // Enqueue the array size, if any.
1879 AddStmt(E->getArraySize());
1880 // Enqueue the allocated type.
1881 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1882 // Enqueue the placement arguments.
1883 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1884 AddStmt(E->getPlacementArg(I-1));
1885}
Ted Kremenek28a71942010-11-13 00:36:47 +00001886void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001887 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1888 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001889 AddStmt(CE->getCallee());
1890 AddStmt(CE->getArg(0));
1891}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001892void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1893 // Visit the name of the type being destroyed.
1894 AddTypeLoc(E->getDestroyedTypeInfo());
1895 // Visit the scope type that looks disturbingly like the nested-name-specifier
1896 // but isn't.
1897 AddTypeLoc(E->getScopeTypeInfo());
1898 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001899 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1900 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001901 // Visit base expression.
1902 AddStmt(E->getBase());
1903}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001904void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1905 AddTypeLoc(E->getTypeSourceInfo());
1906}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001907void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1908 EnqueueChildren(E);
1909 AddTypeLoc(E->getTypeSourceInfo());
1910}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001911void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1912 EnqueueChildren(E);
1913 if (E->isTypeOperand())
1914 AddTypeLoc(E->getTypeOperandSourceInfo());
1915}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001916
1917void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1918 *E) {
1919 EnqueueChildren(E);
1920 AddTypeLoc(E->getTypeSourceInfo());
1921}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001922void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1923 EnqueueChildren(E);
1924 if (E->isTypeOperand())
1925 AddTypeLoc(E->getTypeOperandSourceInfo());
1926}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001927
1928void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1929 EnqueueChildren(S);
1930 AddDecl(S->getExceptionDecl());
1931}
1932
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001933void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001934 if (DR->hasExplicitTemplateArgs()) {
1935 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1936 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001937 WL.push_back(DeclRefExprParts(DR, Parent));
1938}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001939void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1940 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1941 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001942 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001943}
Ted Kremenek035dc412010-11-13 00:36:50 +00001944void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1945 unsigned size = WL.size();
1946 bool isFirst = true;
1947 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1948 D != DEnd; ++D) {
1949 AddDecl(*D, isFirst);
1950 isFirst = false;
1951 }
1952 if (size == WL.size())
1953 return;
1954 // Now reverse the entries we just added. This will match the DFS
1955 // ordering performed by the worklist.
1956 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1957 std::reverse(I, E);
1958}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001959void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1960 AddStmt(E->getInit());
1961 typedef DesignatedInitExpr::Designator Designator;
1962 for (DesignatedInitExpr::reverse_designators_iterator
1963 D = E->designators_rbegin(), DEnd = E->designators_rend();
1964 D != DEnd; ++D) {
1965 if (D->isFieldDesignator()) {
1966 if (FieldDecl *Field = D->getField())
1967 AddMemberRef(Field, D->getFieldLoc());
1968 continue;
1969 }
1970 if (D->isArrayDesignator()) {
1971 AddStmt(E->getArrayIndex(*D));
1972 continue;
1973 }
1974 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1975 AddStmt(E->getArrayRangeEnd(*D));
1976 AddStmt(E->getArrayRangeStart(*D));
1977 }
1978}
Ted Kremenek28a71942010-11-13 00:36:47 +00001979void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1980 EnqueueChildren(E);
1981 AddTypeLoc(E->getTypeInfoAsWritten());
1982}
1983void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1984 AddStmt(FS->getBody());
1985 AddStmt(FS->getInc());
1986 AddStmt(FS->getCond());
1987 AddDecl(FS->getConditionVariable());
1988 AddStmt(FS->getInit());
1989}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001990void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1991 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1992}
Ted Kremenek28a71942010-11-13 00:36:47 +00001993void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1994 AddStmt(If->getElse());
1995 AddStmt(If->getThen());
1996 AddStmt(If->getCond());
1997 AddDecl(If->getConditionVariable());
1998}
1999void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2000 // We care about the syntactic form of the initializer list, only.
2001 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2002 IE = Syntactic;
2003 EnqueueChildren(IE);
2004}
2005void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002006 WL.push_back(MemberExprParts(M, Parent));
2007
2008 // If the base of the member access expression is an implicit 'this', don't
2009 // visit it.
2010 // FIXME: If we ever want to show these implicit accesses, this will be
2011 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002012 if (!M->isImplicitAccess())
2013 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002014}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002015void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2016 AddTypeLoc(E->getEncodedTypeSourceInfo());
2017}
Ted Kremenek28a71942010-11-13 00:36:47 +00002018void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2019 EnqueueChildren(M);
2020 AddTypeLoc(M->getClassReceiverTypeInfo());
2021}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002022void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2023 // Visit the components of the offsetof expression.
2024 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2025 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2026 const OffsetOfNode &Node = E->getComponent(I-1);
2027 switch (Node.getKind()) {
2028 case OffsetOfNode::Array:
2029 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2030 break;
2031 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002032 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002033 break;
2034 case OffsetOfNode::Identifier:
2035 case OffsetOfNode::Base:
2036 continue;
2037 }
2038 }
2039 // Visit the type into which we're computing the offset.
2040 AddTypeLoc(E->getTypeSourceInfo());
2041}
Ted Kremenek28a71942010-11-13 00:36:47 +00002042void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002043 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002044 WL.push_back(OverloadExprParts(E, Parent));
2045}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002046void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2047 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002048 EnqueueChildren(E);
2049 if (E->isArgumentType())
2050 AddTypeLoc(E->getArgumentTypeInfo());
2051}
Ted Kremenek28a71942010-11-13 00:36:47 +00002052void EnqueueVisitor::VisitStmt(Stmt *S) {
2053 EnqueueChildren(S);
2054}
2055void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2056 AddStmt(S->getBody());
2057 AddStmt(S->getCond());
2058 AddDecl(S->getConditionVariable());
2059}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002060
Ted Kremenek28a71942010-11-13 00:36:47 +00002061void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2062 AddStmt(W->getBody());
2063 AddStmt(W->getCond());
2064 AddDecl(W->getConditionVariable());
2065}
John Wiegley21ff2e52011-04-28 00:16:57 +00002066
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002067void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2068 AddTypeLoc(E->getQueriedTypeSourceInfo());
2069}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002070
2071void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002072 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002073 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002074}
2075
John Wiegley21ff2e52011-04-28 00:16:57 +00002076void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2077 AddTypeLoc(E->getQueriedTypeSourceInfo());
2078}
2079
John Wiegley55262202011-04-25 06:54:41 +00002080void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2081 EnqueueChildren(E);
2082}
2083
Ted Kremenek28a71942010-11-13 00:36:47 +00002084void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2085 VisitOverloadExpr(U);
2086 if (!U->isImplicitAccess())
2087 AddStmt(U->getBase());
2088}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002089void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2090 AddStmt(E->getSubExpr());
2091 AddTypeLoc(E->getWrittenTypeInfo());
2092}
Douglas Gregor94d96292011-01-19 20:34:17 +00002093void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2094 WL.push_back(SizeOfPackExprParts(E, Parent));
2095}
John McCall4b9c2d22011-11-06 09:01:30 +00002096void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2097 // If the opaque value has a source expression, just transparently
2098 // visit that. This is useful for (e.g.) pseudo-object expressions.
2099 if (Expr *SourceExpr = E->getSourceExpr())
2100 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002101}
2102void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2103 // Treat the expression like its syntactic form.
2104 Visit(E->getSyntacticForm());
2105}
Ted Kremenek60458782010-11-12 21:34:16 +00002106
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002107void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002108 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002109}
2110
2111bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2112 if (RegionOfInterest.isValid()) {
2113 SourceRange Range = getRawCursorExtent(C);
2114 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2115 return false;
2116 }
2117 return true;
2118}
2119
2120bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2121 while (!WL.empty()) {
2122 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002123 VisitorJob LI = WL.back();
2124 WL.pop_back();
2125
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002126 // Set the Parent field, then back to its old value once we're done.
2127 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2128
2129 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002130 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002131 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002132 if (!D)
2133 continue;
2134
2135 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002136 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2137 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002138 return true;
2139
2140 continue;
2141 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002142 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002143 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002144 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2145 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2146 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2147 Arg != ArgEnd; ++Arg) {
2148 if (VisitTemplateArgumentLoc(*Arg))
2149 return true;
2150 }
2151 continue;
2152 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002153 case VisitorJob::TypeLocVisitKind: {
2154 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002155 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002156 return true;
2157 continue;
2158 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002159 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002160 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002161 if (LabelStmt *stmt = LS->getStmt()) {
2162 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2163 TU))) {
2164 return true;
2165 }
2166 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002167 continue;
2168 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002169
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002170 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2171 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2172 if (VisitNestedNameSpecifierLoc(V->get()))
2173 return true;
2174 continue;
2175 }
2176
Ted Kremenekf64d8032010-11-18 00:02:32 +00002177 case VisitorJob::DeclarationNameInfoVisitKind: {
2178 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2179 ->get()))
2180 return true;
2181 continue;
2182 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002183 case VisitorJob::MemberRefVisitKind: {
2184 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2185 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2186 return true;
2187 continue;
2188 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002189 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002190 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002191 if (!S)
2192 continue;
2193
Ted Kremenekf1107452010-11-12 18:26:56 +00002194 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002195 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002196 if (!IsInRegionOfInterest(Cursor))
2197 continue;
2198 switch (Visitor(Cursor, Parent, ClientData)) {
2199 case CXChildVisit_Break: return true;
2200 case CXChildVisit_Continue: break;
2201 case CXChildVisit_Recurse:
2202 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002203 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002204 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002205 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002206 }
2207 case VisitorJob::MemberExprPartsKind: {
2208 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002209 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002210
2211 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002212 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2213 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002214 return true;
2215
2216 // Visit the declaration name.
2217 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2218 return true;
2219
2220 // Visit the explicitly-specified template arguments, if any.
2221 if (M->hasExplicitTemplateArgs()) {
2222 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2223 *ArgEnd = Arg + M->getNumTemplateArgs();
2224 Arg != ArgEnd; ++Arg) {
2225 if (VisitTemplateArgumentLoc(*Arg))
2226 return true;
2227 }
2228 }
2229 continue;
2230 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002231 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002232 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002233 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002234 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2235 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002236 return true;
2237 // Visit declaration name.
2238 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2239 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002240 continue;
2241 }
Ted Kremenek60458782010-11-12 21:34:16 +00002242 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002243 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002244 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002245 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2246 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002247 return true;
2248 // Visit the declaration name.
2249 if (VisitDeclarationNameInfo(O->getNameInfo()))
2250 return true;
2251 // Visit the overloaded declaration reference.
2252 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2253 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002254 continue;
2255 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002256 case VisitorJob::SizeOfPackExprPartsKind: {
2257 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2258 NamedDecl *Pack = E->getPack();
2259 if (isa<TemplateTypeParmDecl>(Pack)) {
2260 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2261 E->getPackLoc(), TU)))
2262 return true;
2263
2264 continue;
2265 }
2266
2267 if (isa<TemplateTemplateParmDecl>(Pack)) {
2268 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2269 E->getPackLoc(), TU)))
2270 return true;
2271
2272 continue;
2273 }
2274
2275 // Non-type template parameter packs and function parameter packs are
2276 // treated like DeclRefExpr cursors.
2277 continue;
2278 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002279 }
2280 }
2281 return false;
2282}
2283
Ted Kremenekcdba6592010-11-18 00:42:18 +00002284bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002285 VisitorWorkList *WL = 0;
2286 if (!WorkListFreeList.empty()) {
2287 WL = WorkListFreeList.back();
2288 WL->clear();
2289 WorkListFreeList.pop_back();
2290 }
2291 else {
2292 WL = new VisitorWorkList();
2293 WorkListCache.push_back(WL);
2294 }
2295 EnqueueWorkList(*WL, S);
2296 bool result = RunVisitorWorkList(*WL);
2297 WorkListFreeList.push_back(WL);
2298 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002299}
2300
Francois Pichet48a8d142011-07-25 22:00:44 +00002301namespace {
2302typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2303RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2304 const DeclarationNameInfo &NI,
2305 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002306 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002307 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2308 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2309 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2310
2311 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2312
2313 RefNamePieces Pieces;
2314
2315 if (WantQualifier && QLoc.isValid())
2316 Pieces.push_back(QLoc);
2317
2318 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2319 Pieces.push_back(NI.getLoc());
2320
2321 if (WantTemplateArgs && TemplateArgs)
2322 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2323 TemplateArgs->RAngleLoc));
2324
2325 if (Kind == DeclarationName::CXXOperatorName) {
2326 Pieces.push_back(SourceLocation::getFromRawEncoding(
2327 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2328 Pieces.push_back(SourceLocation::getFromRawEncoding(
2329 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2330 }
2331
2332 if (WantSinglePiece) {
2333 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2334 Pieces.clear();
2335 Pieces.push_back(R);
2336 }
2337
2338 return Pieces;
2339}
2340}
2341
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002342//===----------------------------------------------------------------------===//
2343// Misc. API hooks.
2344//===----------------------------------------------------------------------===//
2345
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002346static llvm::sys::Mutex EnableMultithreadingMutex;
2347static bool EnabledMultithreading;
2348
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002349static void fatal_error_handler(void *user_data, const std::string& reason) {
2350 llvm::SmallString<64> Buffer;
2351 llvm::raw_svector_ostream OS(Buffer);
2352 OS << "LIBCLANG FATAL ERROR: " << reason << "\n";
2353 StringRef MessageStr = OS.str();
2354 // Write the result out to stderr avoiding errs() because raw_ostreams can
2355 // call report_fatal_error.
2356 ::write(2, MessageStr.data(), MessageStr.size());
2357 ::abort();
2358}
2359
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002360extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002361CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2362 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002363 // Disable pretty stack trace functionality, which will otherwise be a very
2364 // poor citizen of the world and set up all sorts of signal handlers.
2365 llvm::DisablePrettyStackTrace = true;
2366
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002367 // We use crash recovery to make some of our APIs more reliable, implicitly
2368 // enable it.
2369 llvm::CrashRecoveryContext::Enable();
2370
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002371 // Enable support for multithreading in LLVM.
2372 {
2373 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2374 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002375 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002376 llvm::llvm_start_multithreaded();
2377 EnabledMultithreading = true;
2378 }
2379 }
2380
Douglas Gregora030b7c2010-01-22 20:35:53 +00002381 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002382 if (excludeDeclarationsFromPCH)
2383 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002384 if (displayDiagnostics)
2385 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002386 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002387}
2388
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002389void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002390 if (CIdx)
2391 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002392}
2393
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002394void clang_toggleCrashRecovery(unsigned isEnabled) {
2395 if (isEnabled)
2396 llvm::CrashRecoveryContext::Enable();
2397 else
2398 llvm::CrashRecoveryContext::Disable();
2399}
2400
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002401CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002402 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002403 if (!CIdx)
2404 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002405
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002406 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002407 FileSystemOptions FileSystemOpts;
2408 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002409
David Blaikied6471f72011-09-25 23:23:43 +00002410 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002411 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002412 CXXIdx->getOnlyLocalDecls(),
2413 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002414 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002415}
2416
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002417unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002418 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002419 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002420}
2421
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002422CXTranslationUnit
2423clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2424 const char *source_filename,
2425 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002426 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002427 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002428 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002429 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002430 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002431 return clang_parseTranslationUnit(CIdx, source_filename,
2432 command_line_args, num_command_line_args,
2433 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002434 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002435}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002436
2437struct ParseTranslationUnitInfo {
2438 CXIndex CIdx;
2439 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002440 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002441 int num_command_line_args;
2442 struct CXUnsavedFile *unsaved_files;
2443 unsigned num_unsaved_files;
2444 unsigned options;
2445 CXTranslationUnit result;
2446};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002447static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002448 ParseTranslationUnitInfo *PTUI =
2449 static_cast<ParseTranslationUnitInfo*>(UserData);
2450 CXIndex CIdx = PTUI->CIdx;
2451 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002452 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002453 int num_command_line_args = PTUI->num_command_line_args;
2454 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2455 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2456 unsigned options = PTUI->options;
2457 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002458
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002459 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002460 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002461
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002462 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2463
Douglas Gregor44c181a2010-07-23 00:33:23 +00002464 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002465 // FIXME: Add a flag for modules.
2466 TranslationUnitKind TUKind
2467 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002468 bool CacheCodeCompetionResults
2469 = options & CXTranslationUnit_CacheCompletionResults;
2470
Douglas Gregor5352ac02010-01-28 00:27:43 +00002471 // Configure the diagnostics.
2472 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002473 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002474 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2475 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002476
Ted Kremenek25a11e12011-03-22 01:15:24 +00002477 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002478 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2479 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002480 DiagCleanup(Diags.getPtr());
2481
2482 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2483 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2484
2485 // Recover resources if we crash before exiting this function.
2486 llvm::CrashRecoveryContextCleanupRegistrar<
2487 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2488
Douglas Gregor4db64a42010-01-23 00:14:00 +00002489 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002490 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002491 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002492 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002493 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2494 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002495 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002496
Ted Kremenek25a11e12011-03-22 01:15:24 +00002497 llvm::OwningPtr<std::vector<const char *> >
2498 Args(new std::vector<const char*>());
2499
2500 // Recover resources if we crash before exiting this method.
2501 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2502 ArgsCleanup(Args.get());
2503
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002504 // Since the Clang C library is primarily used by batch tools dealing with
2505 // (often very broken) source code, where spell-checking can have a
2506 // significant negative impact on performance (particularly when
2507 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002508 // Only do this if we haven't found a spell-checking-related argument.
2509 bool FoundSpellCheckingArgument = false;
2510 for (int I = 0; I != num_command_line_args; ++I) {
2511 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2512 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2513 FoundSpellCheckingArgument = true;
2514 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002515 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002516 }
2517 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002518 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002519
Ted Kremenek25a11e12011-03-22 01:15:24 +00002520 Args->insert(Args->end(), command_line_args,
2521 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002522
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002523 // The 'source_filename' argument is optional. If the caller does not
2524 // specify it then it is assumed that the source file is specified
2525 // in the actual argument list.
2526 // Put the source file after command_line_args otherwise if '-x' flag is
2527 // present it will be unused.
2528 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002529 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002530
Douglas Gregor44c181a2010-07-23 00:33:23 +00002531 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002532 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002533 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002534 Args->push_back("-Xclang");
2535 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002536 NestedMacroExpansions
2537 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002538 }
2539
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002540 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002541 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002542 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2543 /* vector::data() not portable */,
2544 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002545 Diags,
2546 CXXIdx->getClangResourcesPath(),
2547 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002548 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002549 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002550 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002551 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002552 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002553 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002554 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002555 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002556
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002557 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002558 // Make sure to check that 'Unit' is non-NULL.
2559 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2560 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2561 DEnd = Unit->stored_diag_end();
2562 D != DEnd; ++D) {
2563 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2564 CXString Msg = clang_formatDiagnostic(&Diag,
2565 clang_defaultDiagnosticDisplayOptions());
2566 fprintf(stderr, "%s\n", clang_getCString(Msg));
2567 clang_disposeString(Msg);
2568 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002569#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002570 // On Windows, force a flush, since there may be multiple copies of
2571 // stderr and stdout in the file system, all with different buffers
2572 // but writing to the same device.
2573 fflush(stderr);
2574#endif
2575 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002576 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002577
Ted Kremeneka60ed472010-11-16 08:15:36 +00002578 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002579}
2580CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2581 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002582 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002583 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002584 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002585 unsigned num_unsaved_files,
2586 unsigned options) {
2587 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002588 num_command_line_args, unsaved_files,
2589 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002590 llvm::CrashRecoveryContext CRC;
2591
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002592 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002593 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2594 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2595 fprintf(stderr, " 'command_line_args' : [");
2596 for (int i = 0; i != num_command_line_args; ++i) {
2597 if (i)
2598 fprintf(stderr, ", ");
2599 fprintf(stderr, "'%s'", command_line_args[i]);
2600 }
2601 fprintf(stderr, "],\n");
2602 fprintf(stderr, " 'unsaved_files' : [");
2603 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2604 if (i)
2605 fprintf(stderr, ", ");
2606 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2607 unsaved_files[i].Length);
2608 }
2609 fprintf(stderr, "],\n");
2610 fprintf(stderr, " 'options' : %d,\n", options);
2611 fprintf(stderr, "}\n");
2612
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002613 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002614 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2615 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002616 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002617
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002618 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002619}
2620
Douglas Gregor19998442010-08-13 15:35:05 +00002621unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2622 return CXSaveTranslationUnit_None;
2623}
2624
2625int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2626 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002627 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002628 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002629
Douglas Gregor39c411f2011-07-06 16:43:36 +00002630 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002631 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2632 PrintLibclangResourceUsage(TU);
2633 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002634}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002635
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002636void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002637 if (CTUnit) {
2638 // If the translation unit has been marked as unsafe to free, just discard
2639 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002640 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002641 return;
2642
Ted Kremeneka60ed472010-11-16 08:15:36 +00002643 delete static_cast<ASTUnit *>(CTUnit->TUData);
2644 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002645 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002646 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002647 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002648}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002649
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002650unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2651 return CXReparse_None;
2652}
2653
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002654struct ReparseTranslationUnitInfo {
2655 CXTranslationUnit TU;
2656 unsigned num_unsaved_files;
2657 struct CXUnsavedFile *unsaved_files;
2658 unsigned options;
2659 int result;
2660};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002661
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002662static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002663 ReparseTranslationUnitInfo *RTUI =
2664 static_cast<ReparseTranslationUnitInfo*>(UserData);
2665 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002666
2667 // Reset the associated diagnostics.
2668 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2669 TU->Diagnostics = 0;
2670
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002671 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2672 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2673 unsigned options = RTUI->options;
2674 (void) options;
2675 RTUI->result = 1;
2676
Douglas Gregorabc563f2010-07-19 21:46:24 +00002677 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002678 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002679
Ted Kremeneka60ed472010-11-16 08:15:36 +00002680 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002681 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002682
Ted Kremenek25a11e12011-03-22 01:15:24 +00002683 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2684 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2685
2686 // Recover resources if we crash before exiting this function.
2687 llvm::CrashRecoveryContextCleanupRegistrar<
2688 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2689
Douglas Gregorabc563f2010-07-19 21:46:24 +00002690 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002691 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002692 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002693 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002694 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2695 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002696 }
2697
Ted Kremenek4ee99262011-03-22 20:16:19 +00002698 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2699 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002700 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002701}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002702
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002703int clang_reparseTranslationUnit(CXTranslationUnit TU,
2704 unsigned num_unsaved_files,
2705 struct CXUnsavedFile *unsaved_files,
2706 unsigned options) {
2707 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2708 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002709
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002710 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002711 clang_reparseTranslationUnit_Impl(&RTUI);
2712 return RTUI.result;
2713 }
2714
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002715 llvm::CrashRecoveryContext CRC;
2716
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002717 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002718 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002719 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002720 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002721 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2722 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002723
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002724 return RTUI.result;
2725}
2726
Douglas Gregordf95a132010-08-09 20:45:32 +00002727
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002728CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002729 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002730 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002731
Ted Kremeneka60ed472010-11-16 08:15:36 +00002732 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002733 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002734}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002735
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002736CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002737 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002738 return Result;
2739}
2740
Ted Kremenekfb480492010-01-13 21:46:36 +00002741} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002742
Ted Kremenekfb480492010-01-13 21:46:36 +00002743//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002744// CXFile Operations.
2745//===----------------------------------------------------------------------===//
2746
2747extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002748CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002749 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002750 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002751
Steve Naroff88145032009-10-27 14:35:18 +00002752 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002753 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002754}
2755
2756time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002757 if (!SFile)
2758 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002759
Steve Naroff88145032009-10-27 14:35:18 +00002760 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2761 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002762}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002763
Douglas Gregorb9790342010-01-22 21:44:22 +00002764CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2765 if (!tu)
2766 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002767
Ted Kremeneka60ed472010-11-16 08:15:36 +00002768 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002769
Douglas Gregorb9790342010-01-22 21:44:22 +00002770 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002771 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002772}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002773
Douglas Gregordd3e5542011-05-04 00:14:37 +00002774unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2775 if (!tu || !file)
2776 return 0;
2777
2778 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2779 FileEntry *FEnt = static_cast<FileEntry *>(file);
2780 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2781 .isFileMultipleIncludeGuarded(FEnt);
2782}
2783
Ted Kremenekfb480492010-01-13 21:46:36 +00002784} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002785
Ted Kremenekfb480492010-01-13 21:46:36 +00002786//===----------------------------------------------------------------------===//
2787// CXCursor Operations.
2788//===----------------------------------------------------------------------===//
2789
Ted Kremenekfb480492010-01-13 21:46:36 +00002790static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002791 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002792 return getDeclFromExpr(CE->getSubExpr());
2793
Ted Kremenekfb480492010-01-13 21:46:36 +00002794 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2795 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002796 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2797 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002798 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2799 return ME->getMemberDecl();
2800 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2801 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002802 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002803 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002804 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2805 return getDeclFromExpr(POE->getSyntacticForm());
2806 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2807 if (Expr *Src = OVE->getSourceExpr())
2808 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002809
Ted Kremenekfb480492010-01-13 21:46:36 +00002810 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2811 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002812 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002813 if (!CE->isElidable())
2814 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002815 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2816 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002817
Douglas Gregordb1314e2010-10-01 21:11:22 +00002818 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2819 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002820 if (SubstNonTypeTemplateParmPackExpr *NTTP
2821 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2822 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002823 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2824 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2825 isa<ParmVarDecl>(SizeOfPack->getPack()))
2826 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002827
Ted Kremenekfb480492010-01-13 21:46:36 +00002828 return 0;
2829}
2830
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002831static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002832 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2833 return getLocationFromExpr(CE->getSubExpr());
2834
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002835 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2836 return /*FIXME:*/Msg->getLeftLoc();
2837 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2838 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002839 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2840 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002841 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2842 return Member->getMemberLoc();
2843 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2844 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002845 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2846 return SizeOfPack->getPackLoc();
2847
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002848 return E->getLocStart();
2849}
2850
Ted Kremenekfb480492010-01-13 21:46:36 +00002851extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002852
2853unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002854 CXCursorVisitor visitor,
2855 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002856 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2857 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002858 return CursorVis.VisitChildren(parent);
2859}
2860
David Chisnall3387c652010-11-03 14:12:26 +00002861#ifndef __has_feature
2862#define __has_feature(x) 0
2863#endif
2864#if __has_feature(blocks)
2865typedef enum CXChildVisitResult
2866 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2867
2868static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2869 CXClientData client_data) {
2870 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2871 return block(cursor, parent);
2872}
2873#else
2874// If we are compiled with a compiler that doesn't have native blocks support,
2875// define and call the block manually, so the
2876typedef struct _CXChildVisitResult
2877{
2878 void *isa;
2879 int flags;
2880 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002881 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2882 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002883} *CXCursorVisitorBlock;
2884
2885static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2886 CXClientData client_data) {
2887 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2888 return block->invoke(block, cursor, parent);
2889}
2890#endif
2891
2892
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002893unsigned clang_visitChildrenWithBlock(CXCursor parent,
2894 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002895 return clang_visitChildren(parent, visitWithBlock, block);
2896}
2897
Douglas Gregor78205d42010-01-20 21:45:58 +00002898static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00002899 if (!D)
2900 return createCXString("");
2901
2902 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002903 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002904 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002905 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2906 return createCXString(Property->getIdentifier()->getName());
2907
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002908 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002909 }
2910
Douglas Gregor78205d42010-01-20 21:45:58 +00002911 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002912 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002913
Douglas Gregor78205d42010-01-20 21:45:58 +00002914 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2915 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2916 // and returns different names. NamedDecl returns the class name and
2917 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002918 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002919
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002920 if (isa<UsingDirectiveDecl>(D))
2921 return createCXString("");
2922
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002923 llvm::SmallString<1024> S;
2924 llvm::raw_svector_ostream os(S);
2925 ND->printName(os);
2926
2927 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002928}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002929
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002930CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002931 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002932 return clang_getTranslationUnitSpelling(
2933 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002934
Steve Narofff334b4e2009-09-02 18:26:48 +00002935 if (clang_isReference(C.kind)) {
2936 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002937 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002938 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002939 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002940 }
2941 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002942 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002943 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002944 }
2945 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002946 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002947 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002948 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002949 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002950 case CXCursor_CXXBaseSpecifier: {
2951 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2952 return createCXString(B->getType().getAsString());
2953 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002954 case CXCursor_TypeRef: {
2955 TypeDecl *Type = getCursorTypeRef(C).first;
2956 assert(Type && "Missing type decl");
2957
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002958 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2959 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002960 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002961 case CXCursor_TemplateRef: {
2962 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002963 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002964
2965 return createCXString(Template->getNameAsString());
2966 }
Douglas Gregor69319002010-08-31 23:48:11 +00002967
2968 case CXCursor_NamespaceRef: {
2969 NamedDecl *NS = getCursorNamespaceRef(C).first;
2970 assert(NS && "Missing namespace decl");
2971
2972 return createCXString(NS->getNameAsString());
2973 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002974
Douglas Gregora67e03f2010-09-09 21:42:20 +00002975 case CXCursor_MemberRef: {
2976 FieldDecl *Field = getCursorMemberRef(C).first;
2977 assert(Field && "Missing member decl");
2978
2979 return createCXString(Field->getNameAsString());
2980 }
2981
Douglas Gregor36897b02010-09-10 00:22:18 +00002982 case CXCursor_LabelRef: {
2983 LabelStmt *Label = getCursorLabelRef(C).first;
2984 assert(Label && "Missing label");
2985
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002986 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002987 }
2988
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002989 case CXCursor_OverloadedDeclRef: {
2990 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2991 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2992 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2993 return createCXString(ND->getNameAsString());
2994 return createCXString("");
2995 }
2996 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2997 return createCXString(E->getName().getAsString());
2998 OverloadedTemplateStorage *Ovl
2999 = Storage.get<OverloadedTemplateStorage*>();
3000 if (Ovl->size() == 0)
3001 return createCXString("");
3002 return createCXString((*Ovl->begin())->getNameAsString());
3003 }
3004
Daniel Dunbaracca7252009-11-30 20:42:49 +00003005 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003006 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003007 }
3008 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003009
3010 if (clang_isExpression(C.kind)) {
3011 Decl *D = getDeclFromExpr(getCursorExpr(C));
3012 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003013 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003014 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003015 }
3016
Douglas Gregor36897b02010-09-10 00:22:18 +00003017 if (clang_isStatement(C.kind)) {
3018 Stmt *S = getCursorStmt(C);
3019 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003020 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003021
3022 return createCXString("");
3023 }
3024
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003025 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003026 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003027 ->getNameStart());
3028
Douglas Gregor572feb22010-03-18 18:04:21 +00003029 if (C.kind == CXCursor_MacroDefinition)
3030 return createCXString(getCursorMacroDefinition(C)->getName()
3031 ->getNameStart());
3032
Douglas Gregorecdcb882010-10-20 22:00:55 +00003033 if (C.kind == CXCursor_InclusionDirective)
3034 return createCXString(getCursorInclusionDirective(C)->getFileName());
3035
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003036 if (clang_isDeclaration(C.kind))
3037 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003038
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003039 if (C.kind == CXCursor_AnnotateAttr) {
3040 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3041 return createCXString(AA->getAnnotation());
3042 }
3043
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003044 if (C.kind == CXCursor_AsmLabelAttr) {
3045 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3046 return createCXString(AA->getLabel());
3047 }
3048
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003049 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003050}
3051
Douglas Gregor358559d2010-10-02 22:49:11 +00003052CXString clang_getCursorDisplayName(CXCursor C) {
3053 if (!clang_isDeclaration(C.kind))
3054 return clang_getCursorSpelling(C);
3055
3056 Decl *D = getCursorDecl(C);
3057 if (!D)
3058 return createCXString("");
3059
Douglas Gregor30c42402011-09-27 22:38:19 +00003060 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003061 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3062 D = FunTmpl->getTemplatedDecl();
3063
3064 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3065 llvm::SmallString<64> Str;
3066 llvm::raw_svector_ostream OS(Str);
3067 OS << Function->getNameAsString();
3068 if (Function->getPrimaryTemplate())
3069 OS << "<>";
3070 OS << "(";
3071 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3072 if (I)
3073 OS << ", ";
3074 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3075 }
3076
3077 if (Function->isVariadic()) {
3078 if (Function->getNumParams())
3079 OS << ", ";
3080 OS << "...";
3081 }
3082 OS << ")";
3083 return createCXString(OS.str());
3084 }
3085
3086 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3087 llvm::SmallString<64> Str;
3088 llvm::raw_svector_ostream OS(Str);
3089 OS << ClassTemplate->getNameAsString();
3090 OS << "<";
3091 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3092 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3093 if (I)
3094 OS << ", ";
3095
3096 NamedDecl *Param = Params->getParam(I);
3097 if (Param->getIdentifier()) {
3098 OS << Param->getIdentifier()->getName();
3099 continue;
3100 }
3101
3102 // There is no parameter name, which makes this tricky. Try to come up
3103 // with something useful that isn't too long.
3104 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3105 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3106 else if (NonTypeTemplateParmDecl *NTTP
3107 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3108 OS << NTTP->getType().getAsString(Policy);
3109 else
3110 OS << "template<...> class";
3111 }
3112
3113 OS << ">";
3114 return createCXString(OS.str());
3115 }
3116
3117 if (ClassTemplateSpecializationDecl *ClassSpec
3118 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3119 // If the type was explicitly written, use that.
3120 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3121 return createCXString(TSInfo->getType().getAsString(Policy));
3122
3123 llvm::SmallString<64> Str;
3124 llvm::raw_svector_ostream OS(Str);
3125 OS << ClassSpec->getNameAsString();
3126 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003127 ClassSpec->getTemplateArgs().data(),
3128 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003129 Policy);
3130 return createCXString(OS.str());
3131 }
3132
3133 return clang_getCursorSpelling(C);
3134}
3135
Ted Kremeneke68fff62010-02-17 00:41:32 +00003136CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003137 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003138 case CXCursor_FunctionDecl:
3139 return createCXString("FunctionDecl");
3140 case CXCursor_TypedefDecl:
3141 return createCXString("TypedefDecl");
3142 case CXCursor_EnumDecl:
3143 return createCXString("EnumDecl");
3144 case CXCursor_EnumConstantDecl:
3145 return createCXString("EnumConstantDecl");
3146 case CXCursor_StructDecl:
3147 return createCXString("StructDecl");
3148 case CXCursor_UnionDecl:
3149 return createCXString("UnionDecl");
3150 case CXCursor_ClassDecl:
3151 return createCXString("ClassDecl");
3152 case CXCursor_FieldDecl:
3153 return createCXString("FieldDecl");
3154 case CXCursor_VarDecl:
3155 return createCXString("VarDecl");
3156 case CXCursor_ParmDecl:
3157 return createCXString("ParmDecl");
3158 case CXCursor_ObjCInterfaceDecl:
3159 return createCXString("ObjCInterfaceDecl");
3160 case CXCursor_ObjCCategoryDecl:
3161 return createCXString("ObjCCategoryDecl");
3162 case CXCursor_ObjCProtocolDecl:
3163 return createCXString("ObjCProtocolDecl");
3164 case CXCursor_ObjCPropertyDecl:
3165 return createCXString("ObjCPropertyDecl");
3166 case CXCursor_ObjCIvarDecl:
3167 return createCXString("ObjCIvarDecl");
3168 case CXCursor_ObjCInstanceMethodDecl:
3169 return createCXString("ObjCInstanceMethodDecl");
3170 case CXCursor_ObjCClassMethodDecl:
3171 return createCXString("ObjCClassMethodDecl");
3172 case CXCursor_ObjCImplementationDecl:
3173 return createCXString("ObjCImplementationDecl");
3174 case CXCursor_ObjCCategoryImplDecl:
3175 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003176 case CXCursor_CXXMethod:
3177 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003178 case CXCursor_UnexposedDecl:
3179 return createCXString("UnexposedDecl");
3180 case CXCursor_ObjCSuperClassRef:
3181 return createCXString("ObjCSuperClassRef");
3182 case CXCursor_ObjCProtocolRef:
3183 return createCXString("ObjCProtocolRef");
3184 case CXCursor_ObjCClassRef:
3185 return createCXString("ObjCClassRef");
3186 case CXCursor_TypeRef:
3187 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003188 case CXCursor_TemplateRef:
3189 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003190 case CXCursor_NamespaceRef:
3191 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003192 case CXCursor_MemberRef:
3193 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003194 case CXCursor_LabelRef:
3195 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003196 case CXCursor_OverloadedDeclRef:
3197 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003198 case CXCursor_IntegerLiteral:
3199 return createCXString("IntegerLiteral");
3200 case CXCursor_FloatingLiteral:
3201 return createCXString("FloatingLiteral");
3202 case CXCursor_ImaginaryLiteral:
3203 return createCXString("ImaginaryLiteral");
3204 case CXCursor_StringLiteral:
3205 return createCXString("StringLiteral");
3206 case CXCursor_CharacterLiteral:
3207 return createCXString("CharacterLiteral");
3208 case CXCursor_ParenExpr:
3209 return createCXString("ParenExpr");
3210 case CXCursor_UnaryOperator:
3211 return createCXString("UnaryOperator");
3212 case CXCursor_ArraySubscriptExpr:
3213 return createCXString("ArraySubscriptExpr");
3214 case CXCursor_BinaryOperator:
3215 return createCXString("BinaryOperator");
3216 case CXCursor_CompoundAssignOperator:
3217 return createCXString("CompoundAssignOperator");
3218 case CXCursor_ConditionalOperator:
3219 return createCXString("ConditionalOperator");
3220 case CXCursor_CStyleCastExpr:
3221 return createCXString("CStyleCastExpr");
3222 case CXCursor_CompoundLiteralExpr:
3223 return createCXString("CompoundLiteralExpr");
3224 case CXCursor_InitListExpr:
3225 return createCXString("InitListExpr");
3226 case CXCursor_AddrLabelExpr:
3227 return createCXString("AddrLabelExpr");
3228 case CXCursor_StmtExpr:
3229 return createCXString("StmtExpr");
3230 case CXCursor_GenericSelectionExpr:
3231 return createCXString("GenericSelectionExpr");
3232 case CXCursor_GNUNullExpr:
3233 return createCXString("GNUNullExpr");
3234 case CXCursor_CXXStaticCastExpr:
3235 return createCXString("CXXStaticCastExpr");
3236 case CXCursor_CXXDynamicCastExpr:
3237 return createCXString("CXXDynamicCastExpr");
3238 case CXCursor_CXXReinterpretCastExpr:
3239 return createCXString("CXXReinterpretCastExpr");
3240 case CXCursor_CXXConstCastExpr:
3241 return createCXString("CXXConstCastExpr");
3242 case CXCursor_CXXFunctionalCastExpr:
3243 return createCXString("CXXFunctionalCastExpr");
3244 case CXCursor_CXXTypeidExpr:
3245 return createCXString("CXXTypeidExpr");
3246 case CXCursor_CXXBoolLiteralExpr:
3247 return createCXString("CXXBoolLiteralExpr");
3248 case CXCursor_CXXNullPtrLiteralExpr:
3249 return createCXString("CXXNullPtrLiteralExpr");
3250 case CXCursor_CXXThisExpr:
3251 return createCXString("CXXThisExpr");
3252 case CXCursor_CXXThrowExpr:
3253 return createCXString("CXXThrowExpr");
3254 case CXCursor_CXXNewExpr:
3255 return createCXString("CXXNewExpr");
3256 case CXCursor_CXXDeleteExpr:
3257 return createCXString("CXXDeleteExpr");
3258 case CXCursor_UnaryExpr:
3259 return createCXString("UnaryExpr");
3260 case CXCursor_ObjCStringLiteral:
3261 return createCXString("ObjCStringLiteral");
3262 case CXCursor_ObjCEncodeExpr:
3263 return createCXString("ObjCEncodeExpr");
3264 case CXCursor_ObjCSelectorExpr:
3265 return createCXString("ObjCSelectorExpr");
3266 case CXCursor_ObjCProtocolExpr:
3267 return createCXString("ObjCProtocolExpr");
3268 case CXCursor_ObjCBridgedCastExpr:
3269 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003270 case CXCursor_BlockExpr:
3271 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003272 case CXCursor_PackExpansionExpr:
3273 return createCXString("PackExpansionExpr");
3274 case CXCursor_SizeOfPackExpr:
3275 return createCXString("SizeOfPackExpr");
3276 case CXCursor_UnexposedExpr:
3277 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003278 case CXCursor_DeclRefExpr:
3279 return createCXString("DeclRefExpr");
3280 case CXCursor_MemberRefExpr:
3281 return createCXString("MemberRefExpr");
3282 case CXCursor_CallExpr:
3283 return createCXString("CallExpr");
3284 case CXCursor_ObjCMessageExpr:
3285 return createCXString("ObjCMessageExpr");
3286 case CXCursor_UnexposedStmt:
3287 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003288 case CXCursor_DeclStmt:
3289 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003290 case CXCursor_LabelStmt:
3291 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003292 case CXCursor_CompoundStmt:
3293 return createCXString("CompoundStmt");
3294 case CXCursor_CaseStmt:
3295 return createCXString("CaseStmt");
3296 case CXCursor_DefaultStmt:
3297 return createCXString("DefaultStmt");
3298 case CXCursor_IfStmt:
3299 return createCXString("IfStmt");
3300 case CXCursor_SwitchStmt:
3301 return createCXString("SwitchStmt");
3302 case CXCursor_WhileStmt:
3303 return createCXString("WhileStmt");
3304 case CXCursor_DoStmt:
3305 return createCXString("DoStmt");
3306 case CXCursor_ForStmt:
3307 return createCXString("ForStmt");
3308 case CXCursor_GotoStmt:
3309 return createCXString("GotoStmt");
3310 case CXCursor_IndirectGotoStmt:
3311 return createCXString("IndirectGotoStmt");
3312 case CXCursor_ContinueStmt:
3313 return createCXString("ContinueStmt");
3314 case CXCursor_BreakStmt:
3315 return createCXString("BreakStmt");
3316 case CXCursor_ReturnStmt:
3317 return createCXString("ReturnStmt");
3318 case CXCursor_AsmStmt:
3319 return createCXString("AsmStmt");
3320 case CXCursor_ObjCAtTryStmt:
3321 return createCXString("ObjCAtTryStmt");
3322 case CXCursor_ObjCAtCatchStmt:
3323 return createCXString("ObjCAtCatchStmt");
3324 case CXCursor_ObjCAtFinallyStmt:
3325 return createCXString("ObjCAtFinallyStmt");
3326 case CXCursor_ObjCAtThrowStmt:
3327 return createCXString("ObjCAtThrowStmt");
3328 case CXCursor_ObjCAtSynchronizedStmt:
3329 return createCXString("ObjCAtSynchronizedStmt");
3330 case CXCursor_ObjCAutoreleasePoolStmt:
3331 return createCXString("ObjCAutoreleasePoolStmt");
3332 case CXCursor_ObjCForCollectionStmt:
3333 return createCXString("ObjCForCollectionStmt");
3334 case CXCursor_CXXCatchStmt:
3335 return createCXString("CXXCatchStmt");
3336 case CXCursor_CXXTryStmt:
3337 return createCXString("CXXTryStmt");
3338 case CXCursor_CXXForRangeStmt:
3339 return createCXString("CXXForRangeStmt");
3340 case CXCursor_SEHTryStmt:
3341 return createCXString("SEHTryStmt");
3342 case CXCursor_SEHExceptStmt:
3343 return createCXString("SEHExceptStmt");
3344 case CXCursor_SEHFinallyStmt:
3345 return createCXString("SEHFinallyStmt");
3346 case CXCursor_NullStmt:
3347 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003348 case CXCursor_InvalidFile:
3349 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003350 case CXCursor_InvalidCode:
3351 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003352 case CXCursor_NoDeclFound:
3353 return createCXString("NoDeclFound");
3354 case CXCursor_NotImplemented:
3355 return createCXString("NotImplemented");
3356 case CXCursor_TranslationUnit:
3357 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003358 case CXCursor_UnexposedAttr:
3359 return createCXString("UnexposedAttr");
3360 case CXCursor_IBActionAttr:
3361 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003362 case CXCursor_IBOutletAttr:
3363 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003364 case CXCursor_IBOutletCollectionAttr:
3365 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003366 case CXCursor_CXXFinalAttr:
3367 return createCXString("attribute(final)");
3368 case CXCursor_CXXOverrideAttr:
3369 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003370 case CXCursor_AnnotateAttr:
3371 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003372 case CXCursor_AsmLabelAttr:
3373 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003374 case CXCursor_PreprocessingDirective:
3375 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003376 case CXCursor_MacroDefinition:
3377 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003378 case CXCursor_MacroExpansion:
3379 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003380 case CXCursor_InclusionDirective:
3381 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003382 case CXCursor_Namespace:
3383 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003384 case CXCursor_LinkageSpec:
3385 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003386 case CXCursor_CXXBaseSpecifier:
3387 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003388 case CXCursor_Constructor:
3389 return createCXString("CXXConstructor");
3390 case CXCursor_Destructor:
3391 return createCXString("CXXDestructor");
3392 case CXCursor_ConversionFunction:
3393 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003394 case CXCursor_TemplateTypeParameter:
3395 return createCXString("TemplateTypeParameter");
3396 case CXCursor_NonTypeTemplateParameter:
3397 return createCXString("NonTypeTemplateParameter");
3398 case CXCursor_TemplateTemplateParameter:
3399 return createCXString("TemplateTemplateParameter");
3400 case CXCursor_FunctionTemplate:
3401 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003402 case CXCursor_ClassTemplate:
3403 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003404 case CXCursor_ClassTemplatePartialSpecialization:
3405 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003406 case CXCursor_NamespaceAlias:
3407 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003408 case CXCursor_UsingDirective:
3409 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003410 case CXCursor_UsingDeclaration:
3411 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003412 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003413 return createCXString("TypeAliasDecl");
3414 case CXCursor_ObjCSynthesizeDecl:
3415 return createCXString("ObjCSynthesizeDecl");
3416 case CXCursor_ObjCDynamicDecl:
3417 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003418 case CXCursor_CXXAccessSpecifier:
3419 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003420 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003421
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003422 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003423 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003424}
Steve Naroff89922f82009-08-31 00:59:03 +00003425
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003426struct GetCursorData {
3427 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003428 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003429 CXCursor &BestCursor;
3430
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003431 GetCursorData(SourceManager &SM,
3432 SourceLocation tokenBegin, CXCursor &outputCursor)
3433 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3434 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3435 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003436};
3437
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003438static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3439 CXCursor parent,
3440 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003441 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3442 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003443
3444 // If we point inside a macro argument we should provide info of what the
3445 // token is so use the actual cursor, don't replace it with a macro expansion
3446 // cursor.
3447 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3448 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003449
3450 if (clang_isDeclaration(cursor.kind)) {
3451 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003452 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003453 if (MD->isImplicit())
3454 return CXChildVisit_Break;
3455 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003456
3457 if (clang_isExpression(cursor.kind) &&
3458 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003459 if (Decl *D = getCursorDecl(*BestCursor)) {
3460 // Avoid having the cursor of an expression replace the declaration cursor
3461 // when the expression source range overlaps the declaration range.
3462 // This can happen for C++ constructor expressions whose range generally
3463 // include the variable declaration, e.g.:
3464 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3465 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3466 D->getLocation() == Data->TokenBeginLoc)
3467 return CXChildVisit_Break;
3468 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003469 }
3470
Douglas Gregor93798e22010-11-05 21:11:19 +00003471 // If our current best cursor is the construction of a temporary object,
3472 // don't replace that cursor with a type reference, because we want
3473 // clang_getCursor() to point at the constructor.
3474 if (clang_isExpression(BestCursor->kind) &&
3475 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003476 cursor.kind == CXCursor_TypeRef) {
3477 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3478 // as having the actual point on the type reference.
3479 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003480 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003481 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003482
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003483 *BestCursor = cursor;
3484 return CXChildVisit_Recurse;
3485}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003486
Douglas Gregorb9790342010-01-22 21:44:22 +00003487CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3488 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003489 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003490
Ted Kremeneka60ed472010-11-16 08:15:36 +00003491 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003492 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3493
Ted Kremeneka297de22010-01-25 22:34:44 +00003494 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003495 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003496
Douglas Gregor40749ee2010-11-03 00:35:38 +00003497 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003498 if (Logging) {
3499 CXFile SearchFile;
3500 unsigned SearchLine, SearchColumn;
3501 CXFile ResultFile;
3502 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003503 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3504 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003505 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3506
Chandler Carruth20174222011-08-31 16:53:37 +00003507 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3508 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3509 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003510 SearchFileName = clang_getFileName(SearchFile);
3511 ResultFileName = clang_getFileName(ResultFile);
3512 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003513 USR = clang_getCursorUSR(Result);
3514 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003515 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3516 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003517 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3518 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003519 clang_disposeString(SearchFileName);
3520 clang_disposeString(ResultFileName);
3521 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003522 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003523
3524 CXCursor Definition = clang_getCursorDefinition(Result);
3525 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3526 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3527 CXString DefinitionKindSpelling
3528 = clang_getCursorKindSpelling(Definition.kind);
3529 CXFile DefinitionFile;
3530 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003531 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3532 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003533 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3534 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3535 clang_getCString(DefinitionKindSpelling),
3536 clang_getCString(DefinitionFileName),
3537 DefinitionLine, DefinitionColumn);
3538 clang_disposeString(DefinitionFileName);
3539 clang_disposeString(DefinitionKindSpelling);
3540 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003541 }
3542
Ted Kremeneke68fff62010-02-17 00:41:32 +00003543 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003544}
3545
Ted Kremenek73885552009-11-17 19:28:59 +00003546CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003547 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003548}
3549
3550unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003551 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003552}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003553
Douglas Gregor9ce55842010-11-20 00:09:34 +00003554unsigned clang_hashCursor(CXCursor C) {
3555 unsigned Index = 0;
3556 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3557 Index = 1;
3558
3559 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3560 std::make_pair(C.kind, C.data[Index]));
3561}
3562
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003563unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003564 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3565}
3566
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003567unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003568 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3569}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003570
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003571unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003572 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3573}
3574
Douglas Gregor97b98722010-01-19 23:20:36 +00003575unsigned clang_isExpression(enum CXCursorKind K) {
3576 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3577}
3578
3579unsigned clang_isStatement(enum CXCursorKind K) {
3580 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3581}
3582
Douglas Gregor8be80e12011-07-06 03:00:34 +00003583unsigned clang_isAttribute(enum CXCursorKind K) {
3584 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3585}
3586
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003587unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3588 return K == CXCursor_TranslationUnit;
3589}
3590
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003591unsigned clang_isPreprocessing(enum CXCursorKind K) {
3592 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3593}
3594
Ted Kremenekad6eff62010-03-08 21:17:29 +00003595unsigned clang_isUnexposed(enum CXCursorKind K) {
3596 switch (K) {
3597 case CXCursor_UnexposedDecl:
3598 case CXCursor_UnexposedExpr:
3599 case CXCursor_UnexposedStmt:
3600 case CXCursor_UnexposedAttr:
3601 return true;
3602 default:
3603 return false;
3604 }
3605}
3606
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003607CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003608 return C.kind;
3609}
3610
Douglas Gregor98258af2010-01-18 22:46:11 +00003611CXSourceLocation clang_getCursorLocation(CXCursor C) {
3612 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003613 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003614 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003615 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3616 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003617 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003618 }
3619
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003620 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003621 std::pair<ObjCProtocolDecl *, SourceLocation> P
3622 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003623 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003624 }
3625
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003626 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003627 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3628 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003629 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003630 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003631
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003632 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003633 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003634 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003635 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003636
3637 case CXCursor_TemplateRef: {
3638 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3639 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3640 }
3641
Douglas Gregor69319002010-08-31 23:48:11 +00003642 case CXCursor_NamespaceRef: {
3643 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3644 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3645 }
3646
Douglas Gregora67e03f2010-09-09 21:42:20 +00003647 case CXCursor_MemberRef: {
3648 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3649 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3650 }
3651
Ted Kremenek3064ef92010-08-27 21:34:58 +00003652 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003653 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3654 if (!BaseSpec)
3655 return clang_getNullLocation();
3656
3657 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3658 return cxloc::translateSourceLocation(getCursorContext(C),
3659 TSInfo->getTypeLoc().getBeginLoc());
3660
3661 return cxloc::translateSourceLocation(getCursorContext(C),
3662 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003663 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003664
Douglas Gregor36897b02010-09-10 00:22:18 +00003665 case CXCursor_LabelRef: {
3666 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3667 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3668 }
3669
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003670 case CXCursor_OverloadedDeclRef:
3671 return cxloc::translateSourceLocation(getCursorContext(C),
3672 getCursorOverloadedDeclRef(C).second);
3673
Douglas Gregorf46034a2010-01-18 23:41:10 +00003674 default:
3675 // FIXME: Need a way to enumerate all non-reference cases.
3676 llvm_unreachable("Missed a reference kind");
3677 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003678 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003679
3680 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003681 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003682 getLocationFromExpr(getCursorExpr(C)));
3683
Douglas Gregor36897b02010-09-10 00:22:18 +00003684 if (clang_isStatement(C.kind))
3685 return cxloc::translateSourceLocation(getCursorContext(C),
3686 getCursorStmt(C)->getLocStart());
3687
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003688 if (C.kind == CXCursor_PreprocessingDirective) {
3689 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3690 return cxloc::translateSourceLocation(getCursorContext(C), L);
3691 }
Douglas Gregor48072312010-03-18 15:23:44 +00003692
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003693 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003694 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003695 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003696 return cxloc::translateSourceLocation(getCursorContext(C), L);
3697 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003698
3699 if (C.kind == CXCursor_MacroDefinition) {
3700 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3701 return cxloc::translateSourceLocation(getCursorContext(C), L);
3702 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003703
3704 if (C.kind == CXCursor_InclusionDirective) {
3705 SourceLocation L
3706 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3707 return cxloc::translateSourceLocation(getCursorContext(C), L);
3708 }
3709
Ted Kremenek9a700d22010-05-12 06:16:13 +00003710 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003711 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003712
Douglas Gregorf46034a2010-01-18 23:41:10 +00003713 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003714 if (!D)
3715 return clang_getNullLocation();
3716
Douglas Gregorf46034a2010-01-18 23:41:10 +00003717 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003718 // FIXME: Multiple variables declared in a single declaration
3719 // currently lack the information needed to correctly determine their
3720 // ranges when accounting for the type-specifier. We use context
3721 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3722 // and if so, whether it is the first decl.
3723 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3724 if (!cxcursor::isFirstInDeclGroup(C))
3725 Loc = VD->getLocation();
3726 }
3727
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003728 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003729}
Douglas Gregora7bde202010-01-19 00:34:46 +00003730
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003731} // end extern "C"
3732
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003733CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3734 assert(TU);
3735
3736 // Guard against an invalid SourceLocation, or we may assert in one
3737 // of the following calls.
3738 if (SLoc.isInvalid())
3739 return clang_getNullCursor();
3740
3741 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3742
3743 // Translate the given source location to make it point at the beginning of
3744 // the token under the cursor.
3745 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3746 CXXUnit->getASTContext().getLangOptions());
3747
3748 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3749 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003750 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003751 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3752 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003753 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003754 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003755 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003756 }
3757
3758 return Result;
3759}
3760
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003761static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003762 if (clang_isReference(C.kind)) {
3763 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003764 case CXCursor_ObjCSuperClassRef:
3765 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003766
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003767 case CXCursor_ObjCProtocolRef:
3768 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003769
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003770 case CXCursor_ObjCClassRef:
3771 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003772
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003773 case CXCursor_TypeRef:
3774 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003775
3776 case CXCursor_TemplateRef:
3777 return getCursorTemplateRef(C).second;
3778
Douglas Gregor69319002010-08-31 23:48:11 +00003779 case CXCursor_NamespaceRef:
3780 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003781
3782 case CXCursor_MemberRef:
3783 return getCursorMemberRef(C).second;
3784
Ted Kremenek3064ef92010-08-27 21:34:58 +00003785 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003786 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003787
Douglas Gregor36897b02010-09-10 00:22:18 +00003788 case CXCursor_LabelRef:
3789 return getCursorLabelRef(C).second;
3790
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003791 case CXCursor_OverloadedDeclRef:
3792 return getCursorOverloadedDeclRef(C).second;
3793
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003794 default:
3795 // FIXME: Need a way to enumerate all non-reference cases.
3796 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003797 }
3798 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003799
3800 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003801 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003802
3803 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003804 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003805
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003806 if (clang_isAttribute(C.kind))
3807 return getCursorAttr(C)->getRange();
3808
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003809 if (C.kind == CXCursor_PreprocessingDirective)
3810 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003811
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003812 if (C.kind == CXCursor_MacroExpansion) {
3813 ASTUnit *TU = getCursorASTUnit(C);
3814 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3815 return TU->mapRangeFromPreamble(Range);
3816 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003817
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003818 if (C.kind == CXCursor_MacroDefinition) {
3819 ASTUnit *TU = getCursorASTUnit(C);
3820 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3821 return TU->mapRangeFromPreamble(Range);
3822 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003823
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003824 if (C.kind == CXCursor_InclusionDirective) {
3825 ASTUnit *TU = getCursorASTUnit(C);
3826 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3827 return TU->mapRangeFromPreamble(Range);
3828 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003829
Ted Kremenek007a7c92010-11-01 23:26:51 +00003830 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3831 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003832 if (!D)
3833 return SourceRange();
3834
Ted Kremenek007a7c92010-11-01 23:26:51 +00003835 SourceRange R = D->getSourceRange();
3836 // FIXME: Multiple variables declared in a single declaration
3837 // currently lack the information needed to correctly determine their
3838 // ranges when accounting for the type-specifier. We use context
3839 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3840 // and if so, whether it is the first decl.
3841 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3842 if (!cxcursor::isFirstInDeclGroup(C))
3843 R.setBegin(VD->getLocation());
3844 }
3845 return R;
3846 }
Douglas Gregor66537982010-11-17 17:14:07 +00003847 return SourceRange();
3848}
3849
3850/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3851/// the decl-specifier-seq for declarations.
3852static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3853 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3854 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003855 if (!D)
3856 return SourceRange();
3857
Douglas Gregor66537982010-11-17 17:14:07 +00003858 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003859
Douglas Gregor2494dd02011-03-01 01:34:45 +00003860 // Adjust the start of the location for declarations preceded by
3861 // declaration specifiers.
3862 SourceLocation StartLoc;
3863 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3864 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3865 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3866 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3867 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3868 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3869 }
3870
3871 if (StartLoc.isValid() && R.getBegin().isValid() &&
3872 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3873 R.setBegin(StartLoc);
3874
3875 // FIXME: Multiple variables declared in a single declaration
3876 // currently lack the information needed to correctly determine their
3877 // ranges when accounting for the type-specifier. We use context
3878 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3879 // and if so, whether it is the first decl.
3880 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3881 if (!cxcursor::isFirstInDeclGroup(C))
3882 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003883 }
3884
3885 return R;
3886 }
3887
3888 return getRawCursorExtent(C);
3889}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003890
3891extern "C" {
3892
3893CXSourceRange clang_getCursorExtent(CXCursor C) {
3894 SourceRange R = getRawCursorExtent(C);
3895 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003896 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003897
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003898 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003899}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003900
3901CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003902 if (clang_isInvalid(C.kind))
3903 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003904
Ted Kremeneka60ed472010-11-16 08:15:36 +00003905 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003906 if (clang_isDeclaration(C.kind)) {
3907 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003908 if (!D)
3909 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003910 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003911 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003912 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003913 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003914 if (ObjCForwardProtocolDecl *Protocols
3915 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003916 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003917 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003918 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3919 return MakeCXCursor(Property, tu);
3920
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003921 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003922 }
3923
Douglas Gregor97b98722010-01-19 23:20:36 +00003924 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003925 Expr *E = getCursorExpr(C);
3926 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003927 if (D) {
3928 CXCursor declCursor = MakeCXCursor(D, tu);
3929 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3930 declCursor);
3931 return declCursor;
3932 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003933
3934 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003935 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003936
Douglas Gregor97b98722010-01-19 23:20:36 +00003937 return clang_getNullCursor();
3938 }
3939
Douglas Gregor36897b02010-09-10 00:22:18 +00003940 if (clang_isStatement(C.kind)) {
3941 Stmt *S = getCursorStmt(C);
3942 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003943 if (LabelDecl *label = Goto->getLabel())
3944 if (LabelStmt *labelS = label->getStmt())
3945 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003946
3947 return clang_getNullCursor();
3948 }
3949
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003950 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003951 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003952 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003953 }
3954
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003955 if (!clang_isReference(C.kind))
3956 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003957
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003958 switch (C.kind) {
3959 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003960 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003961
3962 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003963 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003964
3965 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003966 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003967
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003968 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003969 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003970
3971 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003972 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003973
Douglas Gregor69319002010-08-31 23:48:11 +00003974 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003975 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003976
Douglas Gregora67e03f2010-09-09 21:42:20 +00003977 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003978 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003979
Ted Kremenek3064ef92010-08-27 21:34:58 +00003980 case CXCursor_CXXBaseSpecifier: {
3981 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3982 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003983 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003984 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003985
Douglas Gregor36897b02010-09-10 00:22:18 +00003986 case CXCursor_LabelRef:
3987 // FIXME: We end up faking the "parent" declaration here because we
3988 // don't want to make CXCursor larger.
3989 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003990 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3991 .getTranslationUnitDecl(),
3992 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003993
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003994 case CXCursor_OverloadedDeclRef:
3995 return C;
3996
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003997 default:
3998 // We would prefer to enumerate all non-reference cursor kinds here.
3999 llvm_unreachable("Unhandled reference cursor kind");
4000 break;
4001 }
4002 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004003
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004004 return clang_getNullCursor();
4005}
4006
Douglas Gregorb6998662010-01-19 19:34:47 +00004007CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004008 if (clang_isInvalid(C.kind))
4009 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004010
Ted Kremeneka60ed472010-11-16 08:15:36 +00004011 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004012
Douglas Gregorb6998662010-01-19 19:34:47 +00004013 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004014 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004015 C = clang_getCursorReferenced(C);
4016 WasReference = true;
4017 }
4018
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004019 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004020 return clang_getCursorReferenced(C);
4021
Douglas Gregorb6998662010-01-19 19:34:47 +00004022 if (!clang_isDeclaration(C.kind))
4023 return clang_getNullCursor();
4024
4025 Decl *D = getCursorDecl(C);
4026 if (!D)
4027 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004028
Douglas Gregorb6998662010-01-19 19:34:47 +00004029 switch (D->getKind()) {
4030 // Declaration kinds that don't really separate the notions of
4031 // declaration and definition.
4032 case Decl::Namespace:
4033 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004034 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004035 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004036 case Decl::TemplateTypeParm:
4037 case Decl::EnumConstant:
4038 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004039 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004040 case Decl::ObjCIvar:
4041 case Decl::ObjCAtDefsField:
4042 case Decl::ImplicitParam:
4043 case Decl::ParmVar:
4044 case Decl::NonTypeTemplateParm:
4045 case Decl::TemplateTemplateParm:
4046 case Decl::ObjCCategoryImpl:
4047 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004048 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004049 case Decl::LinkageSpec:
4050 case Decl::ObjCPropertyImpl:
4051 case Decl::FileScopeAsm:
4052 case Decl::StaticAssert:
4053 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004054 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004055 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004056 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004057 return C;
4058
4059 // Declaration kinds that don't make any sense here, but are
4060 // nonetheless harmless.
4061 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004062 break;
4063
4064 // Declaration kinds for which the definition is not resolvable.
4065 case Decl::UnresolvedUsingTypename:
4066 case Decl::UnresolvedUsingValue:
4067 break;
4068
4069 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004070 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004071 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004072
4073 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004074 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004075
4076 case Decl::Enum:
4077 case Decl::Record:
4078 case Decl::CXXRecord:
4079 case Decl::ClassTemplateSpecialization:
4080 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004081 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004083 return clang_getNullCursor();
4084
4085 case Decl::Function:
4086 case Decl::CXXMethod:
4087 case Decl::CXXConstructor:
4088 case Decl::CXXDestructor:
4089 case Decl::CXXConversion: {
4090 const FunctionDecl *Def = 0;
4091 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004092 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004093 return clang_getNullCursor();
4094 }
4095
4096 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004097 // Ask the variable if it has a definition.
4098 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004099 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004100 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004101 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004102
Douglas Gregorb6998662010-01-19 19:34:47 +00004103 case Decl::FunctionTemplate: {
4104 const FunctionDecl *Def = 0;
4105 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004106 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004107 return clang_getNullCursor();
4108 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004109
Douglas Gregorb6998662010-01-19 19:34:47 +00004110 case Decl::ClassTemplate: {
4111 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004112 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004113 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004115 return clang_getNullCursor();
4116 }
4117
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004118 case Decl::Using:
4119 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004120 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004121
4122 case Decl::UsingShadow:
4123 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004124 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004125 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004126
4127 case Decl::ObjCMethod: {
4128 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4129 if (Method->isThisDeclarationADefinition())
4130 return C;
4131
4132 // Dig out the method definition in the associated
4133 // @implementation, if we have it.
4134 // FIXME: The ASTs should make finding the definition easier.
4135 if (ObjCInterfaceDecl *Class
4136 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4137 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4138 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4139 Method->isInstanceMethod()))
4140 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004141 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004142
4143 return clang_getNullCursor();
4144 }
4145
4146 case Decl::ObjCCategory:
4147 if (ObjCCategoryImplDecl *Impl
4148 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004149 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004150 return clang_getNullCursor();
4151
4152 case Decl::ObjCProtocol:
4153 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4154 return C;
4155 return clang_getNullCursor();
4156
4157 case Decl::ObjCInterface:
4158 // There are two notions of a "definition" for an Objective-C
4159 // class: the interface and its implementation. When we resolved a
4160 // reference to an Objective-C class, produce the @interface as
4161 // the definition; when we were provided with the interface,
4162 // produce the @implementation as the definition.
4163 if (WasReference) {
4164 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4165 return C;
4166 } else if (ObjCImplementationDecl *Impl
4167 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004168 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004169 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004170
Douglas Gregorb6998662010-01-19 19:34:47 +00004171 case Decl::ObjCProperty:
4172 // FIXME: We don't really know where to find the
4173 // ObjCPropertyImplDecls that implement this property.
4174 return clang_getNullCursor();
4175
4176 case Decl::ObjCCompatibleAlias:
4177 if (ObjCInterfaceDecl *Class
4178 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4179 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004180 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004181
Douglas Gregorb6998662010-01-19 19:34:47 +00004182 return clang_getNullCursor();
4183
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004184 case Decl::ObjCForwardProtocol:
4185 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004186 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004187
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004188 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004189 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004190 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004191
4192 case Decl::Friend:
4193 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004194 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004195 return clang_getNullCursor();
4196
4197 case Decl::FriendTemplate:
4198 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004199 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004200 return clang_getNullCursor();
4201 }
4202
4203 return clang_getNullCursor();
4204}
4205
4206unsigned clang_isCursorDefinition(CXCursor C) {
4207 if (!clang_isDeclaration(C.kind))
4208 return 0;
4209
4210 return clang_getCursorDefinition(C) == C;
4211}
4212
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004213CXCursor clang_getCanonicalCursor(CXCursor C) {
4214 if (!clang_isDeclaration(C.kind))
4215 return C;
4216
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004217 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004218 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4219 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4220 return MakeCXCursor(CatD, getCursorTU(C));
4221
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004222 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4223 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4224 return MakeCXCursor(IFD, getCursorTU(C));
4225
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004226 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004227 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004228
4229 return C;
4230}
4231
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004232unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004233 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004234 return 0;
4235
4236 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4237 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4238 return E->getNumDecls();
4239
4240 if (OverloadedTemplateStorage *S
4241 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4242 return S->size();
4243
4244 Decl *D = Storage.get<Decl*>();
4245 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004246 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004247 if (isa<ObjCClassDecl>(D))
4248 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004249 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4250 return Protocols->protocol_size();
4251
4252 return 0;
4253}
4254
4255CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004256 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004257 return clang_getNullCursor();
4258
4259 if (index >= clang_getNumOverloadedDecls(cursor))
4260 return clang_getNullCursor();
4261
Ted Kremeneka60ed472010-11-16 08:15:36 +00004262 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004263 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4264 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004265 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004266
4267 if (OverloadedTemplateStorage *S
4268 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004269 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004270
4271 Decl *D = Storage.get<Decl*>();
4272 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4273 // FIXME: This is, unfortunately, linear time.
4274 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4275 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004276 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004277 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004278 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004279 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004280 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004281 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004282
4283 return clang_getNullCursor();
4284}
4285
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004286void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004287 const char **startBuf,
4288 const char **endBuf,
4289 unsigned *startLine,
4290 unsigned *startColumn,
4291 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004292 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004293 assert(getCursorDecl(C) && "CXCursor has null decl");
4294 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004295 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4296 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004297
Steve Naroff4ade6d62009-09-23 17:52:52 +00004298 SourceManager &SM = FD->getASTContext().getSourceManager();
4299 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4300 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4301 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4302 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4303 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4304 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4305}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004306
Douglas Gregor430d7a12011-07-25 17:48:11 +00004307
4308CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4309 unsigned PieceIndex) {
4310 RefNamePieces Pieces;
4311
4312 switch (C.kind) {
4313 case CXCursor_MemberRefExpr:
4314 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4315 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4316 E->getQualifierLoc().getSourceRange());
4317 break;
4318
4319 case CXCursor_DeclRefExpr:
4320 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4321 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4322 E->getQualifierLoc().getSourceRange(),
4323 E->getExplicitTemplateArgsOpt());
4324 break;
4325
4326 case CXCursor_CallExpr:
4327 if (CXXOperatorCallExpr *OCE =
4328 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4329 Expr *Callee = OCE->getCallee();
4330 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4331 Callee = ICE->getSubExpr();
4332
4333 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4334 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4335 DRE->getQualifierLoc().getSourceRange());
4336 }
4337 break;
4338
4339 default:
4340 break;
4341 }
4342
4343 if (Pieces.empty()) {
4344 if (PieceIndex == 0)
4345 return clang_getCursorExtent(C);
4346 } else if (PieceIndex < Pieces.size()) {
4347 SourceRange R = Pieces[PieceIndex];
4348 if (R.isValid())
4349 return cxloc::translateSourceRange(getCursorContext(C), R);
4350 }
4351
4352 return clang_getNullRange();
4353}
4354
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004355void clang_enableStackTraces(void) {
4356 llvm::sys::PrintStackTraceOnErrorSignal();
4357}
4358
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004359void clang_executeOnThread(void (*fn)(void*), void *user_data,
4360 unsigned stack_size) {
4361 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4362}
4363
Ted Kremenekfb480492010-01-13 21:46:36 +00004364} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004365
Ted Kremenekfb480492010-01-13 21:46:36 +00004366//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004367// Token-based Operations.
4368//===----------------------------------------------------------------------===//
4369
4370/* CXToken layout:
4371 * int_data[0]: a CXTokenKind
4372 * int_data[1]: starting token location
4373 * int_data[2]: token length
4374 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004375 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004376 * otherwise unused.
4377 */
4378extern "C" {
4379
4380CXTokenKind clang_getTokenKind(CXToken CXTok) {
4381 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4382}
4383
4384CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4385 switch (clang_getTokenKind(CXTok)) {
4386 case CXToken_Identifier:
4387 case CXToken_Keyword:
4388 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004389 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4390 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004391
4392 case CXToken_Literal: {
4393 // We have stashed the starting pointer in the ptr_data field. Use it.
4394 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004395 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004396 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004397
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004398 case CXToken_Punctuation:
4399 case CXToken_Comment:
4400 break;
4401 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004402
4403 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004404 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004405 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004406 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004407 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004408
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004409 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4410 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004411 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004412 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004413 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004414 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4415 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004416 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004417
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004418 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004419}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004420
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004421CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004422 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004423 if (!CXXUnit)
4424 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004425
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004426 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4427 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4428}
4429
4430CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004431 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004432 if (!CXXUnit)
4433 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004434
4435 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004436 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4437}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004438
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004439static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4440 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004441 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4442 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004443 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004444 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004445 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004446
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004447 // Cannot tokenize across files.
4448 if (BeginLocInfo.first != EndLocInfo.first)
4449 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004450
4451 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004452 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004453 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004454 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004455 if (Invalid)
4456 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004457
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004458 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4459 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004460 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004461 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004462
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004463 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004464 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004465 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004466 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004467 do {
4468 // Lex the next token
4469 Lex.LexFromRawLexer(Tok);
4470 if (Tok.is(tok::eof))
4471 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004472
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004473 // Initialize the CXToken.
4474 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004475
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004476 // - Common fields
4477 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4478 CXTok.int_data[2] = Tok.getLength();
4479 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004480
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004481 // - Kind-specific fields
4482 if (Tok.isLiteral()) {
4483 CXTok.int_data[0] = CXToken_Literal;
4484 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004485 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004486 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004487 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004488 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004489
David Chisnall096428b2010-10-13 21:44:48 +00004490 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004491 CXTok.int_data[0] = CXToken_Keyword;
4492 }
4493 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004494 CXTok.int_data[0] = Tok.is(tok::identifier)
4495 ? CXToken_Identifier
4496 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004497 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004498 CXTok.ptr_data = II;
4499 } else if (Tok.is(tok::comment)) {
4500 CXTok.int_data[0] = CXToken_Comment;
4501 CXTok.ptr_data = 0;
4502 } else {
4503 CXTok.int_data[0] = CXToken_Punctuation;
4504 CXTok.ptr_data = 0;
4505 }
4506 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004507 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004508 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004509}
4510
4511void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4512 CXToken **Tokens, unsigned *NumTokens) {
4513 if (Tokens)
4514 *Tokens = 0;
4515 if (NumTokens)
4516 *NumTokens = 0;
4517
4518 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4519 if (!CXXUnit || !Tokens || !NumTokens)
4520 return;
4521
4522 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4523
4524 SourceRange R = cxloc::translateCXSourceRange(Range);
4525 if (R.isInvalid())
4526 return;
4527
4528 SmallVector<CXToken, 32> CXTokens;
4529 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004530
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004531 if (CXTokens.empty())
4532 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004533
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004534 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4535 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4536 *NumTokens = CXTokens.size();
4537}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004538
Ted Kremenek6db61092010-05-05 00:55:15 +00004539void clang_disposeTokens(CXTranslationUnit TU,
4540 CXToken *Tokens, unsigned NumTokens) {
4541 free(Tokens);
4542}
4543
4544} // end: extern "C"
4545
4546//===----------------------------------------------------------------------===//
4547// Token annotation APIs.
4548//===----------------------------------------------------------------------===//
4549
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004550typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004551static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4552 CXCursor parent,
4553 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004554namespace {
4555class AnnotateTokensWorker {
4556 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004557 CXToken *Tokens;
4558 CXCursor *Cursors;
4559 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004560 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004561 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004562 CursorVisitor AnnotateVis;
4563 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004564 bool HasContextSensitiveKeywords;
4565
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004566 bool MoreTokens() const { return TokIdx < NumTokens; }
4567 unsigned NextToken() const { return TokIdx; }
4568 void AdvanceToken() { ++TokIdx; }
4569 SourceLocation GetTokenLoc(unsigned tokI) {
4570 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4571 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004572 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004573 return Tokens[tokI].int_data[3] != 0;
4574 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004575 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004576 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4577 }
4578
4579 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004580 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4581 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004582
Ted Kremenek6db61092010-05-05 00:55:15 +00004583public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004584 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004585 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004586 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004587 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004588 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004589 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004590 AnnotateTokensVisitor, this,
4591 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004592 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004593 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004594 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4595 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004596
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004597 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004598 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004599 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004600
4601 /// \brief Determine whether the annotator saw any cursors that have
4602 /// context-sensitive keywords.
4603 bool hasContextSensitiveKeywords() const {
4604 return HasContextSensitiveKeywords;
4605 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004606};
4607}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004608
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004609void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004610 // Walk the AST within the region of interest, annotating tokens
4611 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004612 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004613
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004614 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4615 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004616 if (Pos != Annotated.end() &&
4617 (clang_isInvalid(Cursors[I].kind) ||
4618 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004619 Cursors[I] = Pos->second;
4620 }
4621
4622 // Finish up annotating any tokens left.
4623 if (!MoreTokens())
4624 return;
4625
4626 const CXCursor &C = clang_getNullCursor();
4627 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004628 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4629 continue;
4630
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004631 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4632 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004633 }
4634}
4635
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004636/// \brief It annotates and advances tokens with a cursor until the comparison
4637//// between the cursor location and the source range is the same as
4638/// \arg compResult.
4639///
4640/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4641/// Pass RangeOverlap to annotate tokens inside a range.
4642void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4643 RangeComparisonResult compResult,
4644 SourceRange range) {
4645 while (MoreTokens()) {
4646 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004647 if (isFunctionMacroToken(I))
4648 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004649
4650 SourceLocation TokLoc = GetTokenLoc(I);
4651 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4652 Cursors[I] = updateC;
4653 AdvanceToken();
4654 continue;
4655 }
4656 break;
4657 }
4658}
4659
4660/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004661void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4662 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004663 RangeComparisonResult compResult,
4664 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004665 assert(MoreTokens());
4666 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004667 "Should be called only for macro arg tokens");
4668
4669 // This works differently than annotateAndAdvanceTokens; because expanded
4670 // macro arguments can have arbitrary translation-unit source order, we do not
4671 // advance the token index one by one until a token fails the range test.
4672 // We only advance once past all of the macro arg tokens if all of them
4673 // pass the range test. If one of them fails we keep the token index pointing
4674 // at the start of the macro arg tokens so that the failing token will be
4675 // annotated by a subsequent annotation try.
4676
4677 bool atLeastOneCompFail = false;
4678
4679 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004680 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4681 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004682 if (TokLoc.isFileID())
4683 continue; // not macro arg token, it's parens or comma.
4684 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4685 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4686 Cursors[I] = updateC;
4687 } else
4688 atLeastOneCompFail = true;
4689 }
4690
4691 if (!atLeastOneCompFail)
4692 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4693}
4694
Ted Kremenek6db61092010-05-05 00:55:15 +00004695enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004696AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004697 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004698 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004699 if (cursorRange.isInvalid())
4700 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004701
4702 if (!HasContextSensitiveKeywords) {
4703 // Objective-C properties can have context-sensitive keywords.
4704 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4705 if (ObjCPropertyDecl *Property
4706 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4707 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4708 }
4709 // Objective-C methods can have context-sensitive keywords.
4710 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4711 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4712 if (ObjCMethodDecl *Method
4713 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4714 if (Method->getObjCDeclQualifier())
4715 HasContextSensitiveKeywords = true;
4716 else {
4717 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4718 PEnd = Method->param_end();
4719 P != PEnd; ++P) {
4720 if ((*P)->getObjCDeclQualifier()) {
4721 HasContextSensitiveKeywords = true;
4722 break;
4723 }
4724 }
4725 }
4726 }
4727 }
4728 // C++ methods can have context-sensitive keywords.
4729 else if (cursor.kind == CXCursor_CXXMethod) {
4730 if (CXXMethodDecl *Method
4731 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4732 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4733 HasContextSensitiveKeywords = true;
4734 }
4735 }
4736 // C++ classes can have context-sensitive keywords.
4737 else if (cursor.kind == CXCursor_StructDecl ||
4738 cursor.kind == CXCursor_ClassDecl ||
4739 cursor.kind == CXCursor_ClassTemplate ||
4740 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4741 if (Decl *D = getCursorDecl(cursor))
4742 if (D->hasAttr<FinalAttr>())
4743 HasContextSensitiveKeywords = true;
4744 }
4745 }
4746
Douglas Gregor4419b672010-10-21 06:10:04 +00004747 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004748 // For macro expansions, just note where the beginning of the macro
4749 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004750 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004751 Annotated[Loc.int_data] = cursor;
4752 return CXChildVisit_Recurse;
4753 }
4754
Douglas Gregor4419b672010-10-21 06:10:04 +00004755 // Items in the preprocessing record are kept separate from items in
4756 // declarations, so we keep a separate token index.
4757 unsigned SavedTokIdx = TokIdx;
4758 TokIdx = PreprocessingTokIdx;
4759
4760 // Skip tokens up until we catch up to the beginning of the preprocessing
4761 // entry.
4762 while (MoreTokens()) {
4763 const unsigned I = NextToken();
4764 SourceLocation TokLoc = GetTokenLoc(I);
4765 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4766 case RangeBefore:
4767 AdvanceToken();
4768 continue;
4769 case RangeAfter:
4770 case RangeOverlap:
4771 break;
4772 }
4773 break;
4774 }
4775
4776 // Look at all of the tokens within this range.
4777 while (MoreTokens()) {
4778 const unsigned I = NextToken();
4779 SourceLocation TokLoc = GetTokenLoc(I);
4780 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4781 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004782 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004783 case RangeAfter:
4784 break;
4785 case RangeOverlap:
4786 Cursors[I] = cursor;
4787 AdvanceToken();
4788 continue;
4789 }
4790 break;
4791 }
4792
4793 // Save the preprocessing token index; restore the non-preprocessing
4794 // token index.
4795 PreprocessingTokIdx = TokIdx;
4796 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004797 return CXChildVisit_Recurse;
4798 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004799
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004800 if (cursorRange.isInvalid())
4801 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004802
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004803 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4804
Ted Kremeneka333c662010-05-12 05:29:33 +00004805 // Adjust the annotated range based specific declarations.
4806 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4807 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004808 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004809
4810 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004811 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004812 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4813 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004814 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004815 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4816 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004817 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004818
4819 if (StartLoc.isValid() && L.isValid() &&
4820 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4821 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004822 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004823
Ted Kremenek3f404602010-08-14 01:14:06 +00004824 // If the location of the cursor occurs within a macro instantiation, record
4825 // the spelling location of the cursor in our annotation map. We can then
4826 // paper over the token labelings during a post-processing step to try and
4827 // get cursor mappings for tokens that are the *arguments* of a macro
4828 // instantiation.
4829 if (L.isMacroID()) {
4830 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4831 // Only invalidate the old annotation if it isn't part of a preprocessing
4832 // directive. Here we assume that the default construction of CXCursor
4833 // results in CXCursor.kind being an initialized value (i.e., 0). If
4834 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004835
Ted Kremenek3f404602010-08-14 01:14:06 +00004836 CXCursor &oldC = Annotated[rawEncoding];
4837 if (!clang_isPreprocessing(oldC.kind))
4838 oldC = cursor;
4839 }
4840
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004841 const enum CXCursorKind K = clang_getCursorKind(parent);
4842 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004843 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4844 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004845
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004846 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004847
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004848 // Avoid having the cursor of an expression "overwrite" the annotation of the
4849 // variable declaration that it belongs to.
4850 // This can happen for C++ constructor expressions whose range generally
4851 // include the variable declaration, e.g.:
4852 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4853 if (clang_isExpression(cursorK)) {
4854 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004855 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004856 const unsigned I = NextToken();
4857 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4858 E->getLocStart() == D->getLocation() &&
4859 E->getLocStart() == GetTokenLoc(I)) {
4860 Cursors[I] = updateC;
4861 AdvanceToken();
4862 }
4863 }
4864 }
4865
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004866 // Visit children to get their cursor information.
4867 const unsigned BeforeChildren = NextToken();
4868 VisitChildren(cursor);
4869 const unsigned AfterChildren = NextToken();
4870
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004871 // Scan the tokens that are at the end of the cursor, but are not captured
4872 // but the child cursors.
4873 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004874
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004875 // Scan the tokens that are at the beginning of the cursor, but are not
4876 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004877 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4878 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4879 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004880
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004881 Cursors[I] = cursor;
4882 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004883
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004884 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004885}
4886
Ted Kremenek6db61092010-05-05 00:55:15 +00004887static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4888 CXCursor parent,
4889 CXClientData client_data) {
4890 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4891}
4892
Ted Kremenek6628a612011-03-18 22:51:30 +00004893namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004894
4895/// \brief Uses the macro expansions in the preprocessing record to find
4896/// and mark tokens that are macro arguments. This info is used by the
4897/// AnnotateTokensWorker.
4898class MarkMacroArgTokensVisitor {
4899 SourceManager &SM;
4900 CXToken *Tokens;
4901 unsigned NumTokens;
4902 unsigned CurIdx;
4903
4904public:
4905 MarkMacroArgTokensVisitor(SourceManager &SM,
4906 CXToken *tokens, unsigned numTokens)
4907 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4908
4909 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4910 if (cursor.kind != CXCursor_MacroExpansion)
4911 return CXChildVisit_Continue;
4912
4913 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4914 if (macroRange.getBegin() == macroRange.getEnd())
4915 return CXChildVisit_Continue; // it's not a function macro.
4916
4917 for (; CurIdx < NumTokens; ++CurIdx) {
4918 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4919 macroRange.getBegin()))
4920 break;
4921 }
4922
4923 if (CurIdx == NumTokens)
4924 return CXChildVisit_Break;
4925
4926 for (; CurIdx < NumTokens; ++CurIdx) {
4927 SourceLocation tokLoc = getTokenLoc(CurIdx);
4928 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4929 break;
4930
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004931 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004932 }
4933
4934 if (CurIdx == NumTokens)
4935 return CXChildVisit_Break;
4936
4937 return CXChildVisit_Continue;
4938 }
4939
4940private:
4941 SourceLocation getTokenLoc(unsigned tokI) {
4942 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4943 }
4944
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004945 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004946 // The third field is reserved and currently not used. Use it here
4947 // to mark macro arg expanded tokens with their expanded locations.
4948 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4949 }
4950};
4951
4952} // end anonymous namespace
4953
4954static CXChildVisitResult
4955MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4956 CXClientData client_data) {
4957 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4958 parent);
4959}
4960
4961namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004962 struct clang_annotateTokens_Data {
4963 CXTranslationUnit TU;
4964 ASTUnit *CXXUnit;
4965 CXToken *Tokens;
4966 unsigned NumTokens;
4967 CXCursor *Cursors;
4968 };
4969}
4970
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004971static void annotatePreprocessorTokens(CXTranslationUnit TU,
4972 SourceRange RegionOfInterest,
4973 AnnotateTokensData &Annotated) {
4974 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4975
4976 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4977 std::pair<FileID, unsigned> BeginLocInfo
4978 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4979 std::pair<FileID, unsigned> EndLocInfo
4980 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4981
4982 if (BeginLocInfo.first != EndLocInfo.first)
4983 return;
4984
4985 StringRef Buffer;
4986 bool Invalid = false;
4987 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4988 if (Buffer.empty() || Invalid)
4989 return;
4990
4991 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4992 CXXUnit->getASTContext().getLangOptions(),
4993 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4994 Buffer.end());
4995 Lex.SetCommentRetentionState(true);
4996
4997 // Lex tokens in raw mode until we hit the end of the range, to avoid
4998 // entering #includes or expanding macros.
4999 while (true) {
5000 Token Tok;
5001 Lex.LexFromRawLexer(Tok);
5002
5003 reprocess:
5004 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5005 // We have found a preprocessing directive. Gobble it up so that we
5006 // don't see it while preprocessing these tokens later, but keep track
5007 // of all of the token locations inside this preprocessing directive so
5008 // that we can annotate them appropriately.
5009 //
5010 // FIXME: Some simple tests here could identify macro definitions and
5011 // #undefs, to provide specific cursor kinds for those.
5012 SmallVector<SourceLocation, 32> Locations;
5013 do {
5014 Locations.push_back(Tok.getLocation());
5015 Lex.LexFromRawLexer(Tok);
5016 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5017
5018 using namespace cxcursor;
5019 CXCursor Cursor
5020 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5021 Locations.back()),
5022 TU);
5023 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5024 Annotated[Locations[I].getRawEncoding()] = Cursor;
5025 }
5026
5027 if (Tok.isAtStartOfLine())
5028 goto reprocess;
5029
5030 continue;
5031 }
5032
5033 if (Tok.is(tok::eof))
5034 break;
5035 }
5036}
5037
Ted Kremenekab979612010-11-11 08:05:23 +00005038// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005039static void clang_annotateTokensImpl(void *UserData) {
5040 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5041 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5042 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5043 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5044 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5045
5046 // Determine the region of interest, which contains all of the tokens.
5047 SourceRange RegionOfInterest;
5048 RegionOfInterest.setBegin(
5049 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5050 RegionOfInterest.setEnd(
5051 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5052 Tokens[NumTokens-1])));
5053
5054 // A mapping from the source locations found when re-lexing or traversing the
5055 // region of interest to the corresponding cursors.
5056 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005057
Ted Kremenek6628a612011-03-18 22:51:30 +00005058 // Relex the tokens within the source range to look for preprocessing
5059 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005060 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005061
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005062 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5063 // Search and mark tokens that are macro argument expansions.
5064 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5065 Tokens, NumTokens);
5066 CursorVisitor MacroArgMarker(TU,
5067 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005068 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005069 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005070 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005071 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5072 }
5073
Ted Kremenek6628a612011-03-18 22:51:30 +00005074 // Annotate all of the source locations in the region of interest that map to
5075 // a specific cursor.
5076 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5077 TU, RegionOfInterest);
5078
5079 // FIXME: We use a ridiculous stack size here because the data-recursion
5080 // algorithm uses a large stack frame than the non-data recursive version,
5081 // and AnnotationTokensWorker currently transforms the data-recursion
5082 // algorithm back into a traditional recursion by explicitly calling
5083 // VisitChildren(). We will need to remove this explicit recursive call.
5084 W.AnnotateTokens();
5085
5086 // If we ran into any entities that involve context-sensitive keywords,
5087 // take another pass through the tokens to mark them as such.
5088 if (W.hasContextSensitiveKeywords()) {
5089 for (unsigned I = 0; I != NumTokens; ++I) {
5090 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5091 continue;
5092
5093 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5094 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5095 if (ObjCPropertyDecl *Property
5096 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5097 if (Property->getPropertyAttributesAsWritten() != 0 &&
5098 llvm::StringSwitch<bool>(II->getName())
5099 .Case("readonly", true)
5100 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005101 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005102 .Case("readwrite", true)
5103 .Case("retain", true)
5104 .Case("copy", true)
5105 .Case("nonatomic", true)
5106 .Case("atomic", true)
5107 .Case("getter", true)
5108 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005109 .Case("strong", true)
5110 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005111 .Default(false))
5112 Tokens[I].int_data[0] = CXToken_Keyword;
5113 }
5114 continue;
5115 }
5116
5117 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5118 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5119 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5120 if (llvm::StringSwitch<bool>(II->getName())
5121 .Case("in", true)
5122 .Case("out", true)
5123 .Case("inout", true)
5124 .Case("oneway", true)
5125 .Case("bycopy", true)
5126 .Case("byref", true)
5127 .Default(false))
5128 Tokens[I].int_data[0] = CXToken_Keyword;
5129 continue;
5130 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005131
5132 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5133 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5134 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005135 continue;
5136 }
5137 }
5138 }
Ted Kremenekab979612010-11-11 08:05:23 +00005139}
5140
Ted Kremenek6db61092010-05-05 00:55:15 +00005141extern "C" {
5142
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005143void clang_annotateTokens(CXTranslationUnit TU,
5144 CXToken *Tokens, unsigned NumTokens,
5145 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005146
5147 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005148 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005149
Douglas Gregor4419b672010-10-21 06:10:04 +00005150 // Any token we don't specifically annotate will have a NULL cursor.
5151 CXCursor C = clang_getNullCursor();
5152 for (unsigned I = 0; I != NumTokens; ++I)
5153 Cursors[I] = C;
5154
Ted Kremeneka60ed472010-11-16 08:15:36 +00005155 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005156 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005157 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005158
Douglas Gregorbdf60622010-03-05 21:16:25 +00005159 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005160
5161 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005162 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005163 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005164 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005165 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5166 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005167}
Ted Kremenek6628a612011-03-18 22:51:30 +00005168
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005169} // end: extern "C"
5170
5171//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005172// Operations for querying linkage of a cursor.
5173//===----------------------------------------------------------------------===//
5174
5175extern "C" {
5176CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005177 if (!clang_isDeclaration(cursor.kind))
5178 return CXLinkage_Invalid;
5179
Ted Kremenek16b42592010-03-03 06:36:57 +00005180 Decl *D = cxcursor::getCursorDecl(cursor);
5181 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5182 switch (ND->getLinkage()) {
5183 case NoLinkage: return CXLinkage_NoLinkage;
5184 case InternalLinkage: return CXLinkage_Internal;
5185 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5186 case ExternalLinkage: return CXLinkage_External;
5187 };
5188
5189 return CXLinkage_Invalid;
5190}
5191} // end: extern "C"
5192
5193//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005194// Operations for querying language of a cursor.
5195//===----------------------------------------------------------------------===//
5196
5197static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005198 if (!D)
5199 return CXLanguage_C;
5200
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005201 switch (D->getKind()) {
5202 default:
5203 break;
5204 case Decl::ImplicitParam:
5205 case Decl::ObjCAtDefsField:
5206 case Decl::ObjCCategory:
5207 case Decl::ObjCCategoryImpl:
5208 case Decl::ObjCClass:
5209 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005210 case Decl::ObjCForwardProtocol:
5211 case Decl::ObjCImplementation:
5212 case Decl::ObjCInterface:
5213 case Decl::ObjCIvar:
5214 case Decl::ObjCMethod:
5215 case Decl::ObjCProperty:
5216 case Decl::ObjCPropertyImpl:
5217 case Decl::ObjCProtocol:
5218 return CXLanguage_ObjC;
5219 case Decl::CXXConstructor:
5220 case Decl::CXXConversion:
5221 case Decl::CXXDestructor:
5222 case Decl::CXXMethod:
5223 case Decl::CXXRecord:
5224 case Decl::ClassTemplate:
5225 case Decl::ClassTemplatePartialSpecialization:
5226 case Decl::ClassTemplateSpecialization:
5227 case Decl::Friend:
5228 case Decl::FriendTemplate:
5229 case Decl::FunctionTemplate:
5230 case Decl::LinkageSpec:
5231 case Decl::Namespace:
5232 case Decl::NamespaceAlias:
5233 case Decl::NonTypeTemplateParm:
5234 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005235 case Decl::TemplateTemplateParm:
5236 case Decl::TemplateTypeParm:
5237 case Decl::UnresolvedUsingTypename:
5238 case Decl::UnresolvedUsingValue:
5239 case Decl::Using:
5240 case Decl::UsingDirective:
5241 case Decl::UsingShadow:
5242 return CXLanguage_CPlusPlus;
5243 }
5244
5245 return CXLanguage_C;
5246}
5247
5248extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005249
5250enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5251 if (clang_isDeclaration(cursor.kind))
5252 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005253 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005254 return CXAvailability_Available;
5255
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005256 switch (D->getAvailability()) {
5257 case AR_Available:
5258 case AR_NotYetIntroduced:
5259 return CXAvailability_Available;
5260
5261 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005262 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005263
5264 case AR_Unavailable:
5265 return CXAvailability_NotAvailable;
5266 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005267 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005268
Douglas Gregor58ddb602010-08-23 23:00:57 +00005269 return CXAvailability_Available;
5270}
5271
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005272CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5273 if (clang_isDeclaration(cursor.kind))
5274 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5275
5276 return CXLanguage_Invalid;
5277}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005278
5279 /// \brief If the given cursor is the "templated" declaration
5280 /// descibing a class or function template, return the class or
5281 /// function template.
5282static Decl *maybeGetTemplateCursor(Decl *D) {
5283 if (!D)
5284 return 0;
5285
5286 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5287 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5288 return FunTmpl;
5289
5290 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5291 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5292 return ClassTmpl;
5293
5294 return D;
5295}
5296
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005297CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5298 if (clang_isDeclaration(cursor.kind)) {
5299 if (Decl *D = getCursorDecl(cursor)) {
5300 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005301 if (!DC)
5302 return clang_getNullCursor();
5303
5304 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5305 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005306 }
5307 }
5308
5309 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5310 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005311 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005312 }
5313
5314 return clang_getNullCursor();
5315}
5316
5317CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5318 if (clang_isDeclaration(cursor.kind)) {
5319 if (Decl *D = getCursorDecl(cursor)) {
5320 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005321 if (!DC)
5322 return clang_getNullCursor();
5323
5324 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5325 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005326 }
5327 }
5328
5329 // FIXME: Note that we can't easily compute the lexical context of a
5330 // statement or expression, so we return nothing.
5331 return clang_getNullCursor();
5332}
5333
Douglas Gregor9f592342010-10-01 20:25:15 +00005334void clang_getOverriddenCursors(CXCursor cursor,
5335 CXCursor **overridden,
5336 unsigned *num_overridden) {
5337 if (overridden)
5338 *overridden = 0;
5339 if (num_overridden)
5340 *num_overridden = 0;
5341 if (!overridden || !num_overridden)
5342 return;
5343
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005344 SmallVector<CXCursor, 8> Overridden;
5345 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005346
Ted Kremenek24077122011-11-14 23:51:37 +00005347 // Don't allocate memory if we have no overriden cursors.
5348 if (Overridden.size() == 0)
5349 return;
5350
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005351 *num_overridden = Overridden.size();
5352 *overridden = new CXCursor [Overridden.size()];
5353 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005354}
5355
5356void clang_disposeOverriddenCursors(CXCursor *overridden) {
5357 delete [] overridden;
5358}
5359
Douglas Gregorecdcb882010-10-20 22:00:55 +00005360CXFile clang_getIncludedFile(CXCursor cursor) {
5361 if (cursor.kind != CXCursor_InclusionDirective)
5362 return 0;
5363
5364 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5365 return (void *)ID->getFile();
5366}
5367
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005368} // end: extern "C"
5369
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005370
5371//===----------------------------------------------------------------------===//
5372// C++ AST instrospection.
5373//===----------------------------------------------------------------------===//
5374
5375extern "C" {
5376unsigned clang_CXXMethod_isStatic(CXCursor C) {
5377 if (!clang_isDeclaration(C.kind))
5378 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005379
5380 CXXMethodDecl *Method = 0;
5381 Decl *D = cxcursor::getCursorDecl(C);
5382 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5383 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5384 else
5385 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5386 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005387}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005388
Douglas Gregor211924b2011-05-12 15:17:24 +00005389unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5390 if (!clang_isDeclaration(C.kind))
5391 return 0;
5392
5393 CXXMethodDecl *Method = 0;
5394 Decl *D = cxcursor::getCursorDecl(C);
5395 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5396 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5397 else
5398 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5399 return (Method && Method->isVirtual()) ? 1 : 0;
5400}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005401} // end: extern "C"
5402
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005403//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005404// Attribute introspection.
5405//===----------------------------------------------------------------------===//
5406
5407extern "C" {
5408CXType clang_getIBOutletCollectionType(CXCursor C) {
5409 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005410 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005411
5412 IBOutletCollectionAttr *A =
5413 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5414
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005415 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005416}
5417} // end: extern "C"
5418
5419//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005420// Inspecting memory usage.
5421//===----------------------------------------------------------------------===//
5422
Ted Kremenekf7870022011-04-20 16:41:07 +00005423typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005424
Ted Kremenekf7870022011-04-20 16:41:07 +00005425static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5426 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005427 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005428 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005429 entries.push_back(entry);
5430}
5431
5432extern "C" {
5433
Ted Kremenekf7870022011-04-20 16:41:07 +00005434const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005435 const char *str = "";
5436 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005437 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005438 str = "ASTContext: expressions, declarations, and types";
5439 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005440 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005441 str = "ASTContext: identifiers";
5442 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005443 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005444 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005445 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005446 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005447 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005448 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005449 case CXTUResourceUsage_SourceManagerContentCache:
5450 str = "SourceManager: content cache allocator";
5451 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005452 case CXTUResourceUsage_AST_SideTables:
5453 str = "ASTContext: side tables";
5454 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005455 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5456 str = "SourceManager: malloc'ed memory buffers";
5457 break;
5458 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5459 str = "SourceManager: mmap'ed memory buffers";
5460 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005461 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5462 str = "ExternalASTSource: malloc'ed memory buffers";
5463 break;
5464 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5465 str = "ExternalASTSource: mmap'ed memory buffers";
5466 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005467 case CXTUResourceUsage_Preprocessor:
5468 str = "Preprocessor: malloc'ed memory";
5469 break;
5470 case CXTUResourceUsage_PreprocessingRecord:
5471 str = "Preprocessor: PreprocessingRecord";
5472 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005473 case CXTUResourceUsage_SourceManager_DataStructures:
5474 str = "SourceManager: data structures and tables";
5475 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005476 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5477 str = "Preprocessor: header search tables";
5478 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005479 }
5480 return str;
5481}
5482
Ted Kremenekf7870022011-04-20 16:41:07 +00005483CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005484 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005485 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005486 return usage;
5487 }
5488
5489 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5490 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5491 ASTContext &astContext = astUnit->getASTContext();
5492
5493 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005494 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005495 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005496
5497 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005498 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005499 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5500
5501 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005502 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005503 (unsigned long) astContext.Selectors.getTotalMemory());
5504
Ted Kremenekba29bd22011-04-28 04:53:38 +00005505 // How much memory is used by ASTContext's side tables?
5506 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5507 (unsigned long) astContext.getSideTableAllocatedMemory());
5508
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005509 // How much memory is used for caching global code completion results?
5510 unsigned long completionBytes = 0;
5511 if (GlobalCodeCompletionAllocator *completionAllocator =
5512 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005513 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005514 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005515 createCXTUResourceUsageEntry(*entries,
5516 CXTUResourceUsage_GlobalCompletionResults,
5517 completionBytes);
5518
5519 // How much memory is being used by SourceManager's content cache?
5520 createCXTUResourceUsageEntry(*entries,
5521 CXTUResourceUsage_SourceManagerContentCache,
5522 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005523
5524 // How much memory is being used by the MemoryBuffer's in SourceManager?
5525 const SourceManager::MemoryBufferSizes &srcBufs =
5526 astUnit->getSourceManager().getMemoryBufferSizes();
5527
5528 createCXTUResourceUsageEntry(*entries,
5529 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5530 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005531 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005532 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5533 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005534 createCXTUResourceUsageEntry(*entries,
5535 CXTUResourceUsage_SourceManager_DataStructures,
5536 (unsigned long) astContext.getSourceManager()
5537 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005538
5539 // How much memory is being used by the ExternalASTSource?
5540 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5541 const ExternalASTSource::MemoryBufferSizes &sizes =
5542 esrc->getMemoryBufferSizes();
5543
5544 createCXTUResourceUsageEntry(*entries,
5545 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5546 (unsigned long) sizes.malloc_bytes);
5547 createCXTUResourceUsageEntry(*entries,
5548 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5549 (unsigned long) sizes.mmap_bytes);
5550 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005551
5552 // How much memory is being used by the Preprocessor?
5553 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005554 createCXTUResourceUsageEntry(*entries,
5555 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005556 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005557
5558 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5559 createCXTUResourceUsageEntry(*entries,
5560 CXTUResourceUsage_PreprocessingRecord,
5561 pRec->getTotalMemory());
5562 }
5563
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005564 createCXTUResourceUsageEntry(*entries,
5565 CXTUResourceUsage_Preprocessor_HeaderSearch,
5566 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005567
Ted Kremenekf7870022011-04-20 16:41:07 +00005568 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005569 (unsigned) entries->size(),
5570 entries->size() ? &(*entries)[0] : 0 };
5571 entries.take();
5572 return usage;
5573}
5574
Ted Kremenekf7870022011-04-20 16:41:07 +00005575void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005576 if (usage.data)
5577 delete (MemUsageEntries*) usage.data;
5578}
5579
5580} // end extern "C"
5581
Douglas Gregor6df78732011-05-05 20:27:22 +00005582void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5583 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5584 for (unsigned I = 0; I != Usage.numEntries; ++I)
5585 fprintf(stderr, " %s: %lu\n",
5586 clang_getTUResourceUsageName(Usage.entries[I].kind),
5587 Usage.entries[I].amount);
5588
5589 clang_disposeCXTUResourceUsage(Usage);
5590}
5591
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005592//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005593// Misc. utility functions.
5594//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005595
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005596/// Default to using an 8 MB stack size on "safety" threads.
5597static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005598
5599namespace clang {
5600
5601bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005602 void (*Fn)(void*), void *UserData,
5603 unsigned Size) {
5604 if (!Size)
5605 Size = GetSafetyThreadStackSize();
5606 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005607 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5608 return CRC.RunSafely(Fn, UserData);
5609}
5610
5611unsigned GetSafetyThreadStackSize() {
5612 return SafetyStackThreadSize;
5613}
5614
5615void SetSafetyThreadStackSize(unsigned Value) {
5616 SafetyStackThreadSize = Value;
5617}
5618
5619}
5620
Ted Kremenek04bb7162010-01-22 22:44:15 +00005621extern "C" {
5622
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005623CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005624 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005625}
5626
5627} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005628