blob: a5b390a53a4754e6c507492d9f14d33cbde5ddc0 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Argyrios Kyrtzidise397bf12011-11-03 19:02:34 +000022#include "CursorVisitor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000023
Ted Kremenek04bb7162010-01-22 22:44:15 +000024#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000027#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000030#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000031#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000032#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000037#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000038#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000039#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000040#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000041#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000043#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000048#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000049
Steve Naroff50398192009-08-28 15:28:48 +000050using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000051using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000052using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000053using namespace clang::cxtu;
Steve Naroff50398192009-08-28 15:28:48 +000054
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000055CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000056 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
Ted Kremenek15322172011-11-10 08:43:12 +000061 D->Diagnostics = 0;
Ted Kremeneka60ed472010-11-16 08:15:36 +000062 return D;
63}
64
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000065cxtu::CXTUOwner::~CXTUOwner() {
66 if (TU)
67 clang_disposeTranslationUnit(TU);
68}
69
Ted Kremenekf0e23e82010-02-17 00:41:40 +000070/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000071/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072static RangeComparisonResult RangeCompare(SourceManager &SM,
73 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 SourceRange R2) {
75 assert(R1.isValid() && "First range is invalid?");
76 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000077 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000078 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000079 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeAfter;
83 return RangeOverlap;
84}
85
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000086/// \brief Determine if a source location falls within, before, or after a
87/// a given source range.
88static RangeComparisonResult LocationCompare(SourceManager &SM,
89 SourceLocation L, SourceRange R) {
90 assert(R.isValid() && "First range is invalid?");
91 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000092 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000093 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000094 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
95 return RangeBefore;
96 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
97 return RangeAfter;
98 return RangeOverlap;
99}
100
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000101/// \brief Translate a Clang source range into a CIndex source range.
102///
103/// Clang internally represents ranges where the end location points to the
104/// start of the token at the end. However, for external clients it is more
105/// useful to have a CXSourceRange be a proper half-open interval. This routine
106/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000107CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000108 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000109 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000113 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000114 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000116 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000117 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 }
119
120 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
121 R.getBegin().getRawEncoding(),
122 EndLoc.getRawEncoding() };
123 return Result;
124}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000125
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000128//===----------------------------------------------------------------------===//
129
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000130static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000131static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
132
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000135 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136}
137
Douglas Gregorb1373d02010-01-20 20:59:29 +0000138/// \brief Visit the given cursor and, if requested by the visitor,
139/// its children.
140///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141/// \param Cursor the cursor to visit.
142///
143/// \param CheckRegionOfInterest if true, then the caller already checked that
144/// this cursor is within the region of interest.
145///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146/// \returns true if the visitation should be aborted, false if it
147/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000149 if (clang_isInvalid(Cursor.kind))
150 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000151
Douglas Gregorb1373d02010-01-20 20:59:29 +0000152 if (clang_isDeclaration(Cursor.kind)) {
153 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000154 if (!D) {
155 assert(0 && "Invalid declaration cursor");
156 return true; // abort.
157 }
158
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000159 // Ignore implicit declarations, unless it's an objc method because
160 // currently we should report implicit methods for properties when indexing.
161 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162 return false;
163 }
164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 // If we have a range of interest, and this cursor doesn't intersect with it,
166 // we're done.
167 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000168 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000169 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170 return false;
171 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 switch (Visitor(Cursor, Parent, ClientData)) {
174 case CXChildVisit_Break:
175 return true;
176
177 case CXChildVisit_Continue:
178 return false;
179
180 case CXChildVisit_Recurse:
181 return VisitChildren(Cursor);
182 }
183
Douglas Gregorfd643772010-01-25 16:45:46 +0000184 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000185}
186
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000187static bool visitPreprocessedEntitiesInRange(SourceRange R,
188 PreprocessingRecord &PPRec,
189 CursorVisitor &Visitor) {
190 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
191 FileID FID;
192
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000193 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000194 // If the begin/end of the range lie in the same FileID, do the optimization
195 // where we skip preprocessed entities that do not come from the same FileID.
196 FID = SM.getFileID(R.getBegin());
197 if (FID != SM.getFileID(R.getEnd()))
198 FID = FileID();
199 }
200
201 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
202 Entities = PPRec.getPreprocessedEntitiesInRange(R);
203 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
204 PPRec, FID);
205}
206
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000207void CursorVisitor::visitFileRegion() {
208 if (RegionOfInterest.isInvalid())
209 return;
210
211 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
212 SourceManager &SM = Unit->getSourceManager();
213
214 std::pair<FileID, unsigned>
215 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
216 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
217
218 if (End.first != Begin.first) {
219 // If the end does not reside in the same file, try to recover by
220 // picking the end of the file of begin location.
221 End.first = Begin.first;
222 End.second = SM.getFileIDSize(Begin.first);
223 }
224
225 assert(Begin.first == End.first);
226 if (Begin.second > End.second)
227 return;
228
229 FileID File = Begin.first;
230 unsigned Offset = Begin.second;
231 unsigned Length = End.second - Begin.second;
232
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000233 if (!VisitDeclsOnly && !VisitPreprocessorLast)
234 if (visitPreprocessedEntitiesInRegion())
235 return; // visitation break.
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000236
237 visitDeclsFromFileRegion(File, Offset, Length);
238
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000239 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000240 visitPreprocessedEntitiesInRegion();
241}
242
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000243static bool isInLexicalContext(Decl *D, DeclContext *DC) {
244 if (!DC)
245 return false;
246
247 for (DeclContext *DeclDC = D->getLexicalDeclContext();
248 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
249 if (DeclDC == DC)
250 return true;
251 }
252 return false;
253}
254
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000255void CursorVisitor::visitDeclsFromFileRegion(FileID File,
256 unsigned Offset, unsigned Length) {
257 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
258 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000259 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000260
261 SmallVector<Decl *, 16> Decls;
262 Unit->findFileRegionDecls(File, Offset, Length, Decls);
263
264 // If we didn't find any file level decls for the file, try looking at the
265 // file that it was included from.
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +0000266 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000267 bool Invalid = false;
268 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
269 if (Invalid)
270 return;
271
272 SourceLocation Outer;
273 if (SLEntry.isFile())
274 Outer = SLEntry.getFile().getIncludeLoc();
275 else
276 Outer = SLEntry.getExpansion().getExpansionLocStart();
277 if (Outer.isInvalid())
278 return;
279
280 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
281 Length = 0;
282 Unit->findFileRegionDecls(File, Offset, Length, Decls);
283 }
284
285 assert(!Decls.empty());
286
287 bool VisitedAtLeastOnce = false;
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000288 DeclContext *CurDC = 0;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000289 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
290 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
291 Decl *D = *DIt;
Argyrios Kyrtzidised8bef42011-11-28 22:38:07 +0000292 if (D->getSourceRange().isInvalid())
293 continue;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000294
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000295 if (isInLexicalContext(D, CurDC))
296 continue;
297
298 CurDC = dyn_cast<DeclContext>(D);
299
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000300 // We handle forward decls via ObjCClassDecl.
301 if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
Douglas Gregor7723fec2011-12-15 20:29:51 +0000302 if (!InterD->isThisDeclarationADefinition())
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000303 continue;
304 }
305
Argyrios Kyrtzidise2079cf2011-11-16 08:58:54 +0000306 if (TagDecl *TD = dyn_cast<TagDecl>(D))
307 if (!TD->isFreeStanding())
308 continue;
309
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000310 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
311 if (CompRes == RangeBefore)
312 continue;
313 if (CompRes == RangeAfter)
314 break;
315
316 assert(CompRes == RangeOverlap);
317 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000318
319 if (isa<ObjCContainerDecl>(D)) {
320 FileDI_current = &DIt;
321 FileDE_current = DE;
322 } else {
323 FileDI_current = 0;
324 }
325
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000326 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000327 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000328 }
329
330 if (VisitedAtLeastOnce)
331 return;
332
333 // No Decls overlapped with the range. Move up the lexical context until there
334 // is a context that contains the range or we reach the translation unit
335 // level.
336 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
337 : (*(DIt-1))->getLexicalDeclContext();
338
339 while (DC && !DC->isTranslationUnit()) {
340 Decl *D = cast<Decl>(DC);
341 SourceRange CurDeclRange = D->getSourceRange();
342 if (CurDeclRange.isInvalid())
343 break;
344
345 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000346 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000347 break;
348 }
349
350 DC = D->getLexicalDeclContext();
351 }
352}
353
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000354bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000355 if (!AU->getPreprocessor().getPreprocessingRecord())
356 return false;
357
Douglas Gregor788f5a12010-03-20 00:41:21 +0000358 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000359 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000360 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000361
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000362 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000363 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000364 SourceLocation B = MappedRange.getBegin();
365 SourceLocation E = MappedRange.getEnd();
366
367 if (AU->isInPreambleFileID(B)) {
368 if (SM.isLoadedSourceLocation(E))
369 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
370 PPRec, *this);
371
372 // Beginning of range lies in the preamble but it also extends beyond
373 // it into the main file. Split the range into 2 parts, one covering
374 // the preamble and another covering the main file. This allows subsequent
375 // calls to visitPreprocessedEntitiesInRange to accept a source range that
376 // lies in the same FileID, allowing it to skip preprocessed entities that
377 // do not come from the same FileID.
378 bool breaked =
379 visitPreprocessedEntitiesInRange(
380 SourceRange(B, AU->getEndOfPreambleFileID()),
381 PPRec, *this);
382 if (breaked) return true;
383 return visitPreprocessedEntitiesInRange(
384 SourceRange(AU->getStartOfMainFileID(), E),
385 PPRec, *this);
386 }
387
388 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000389 }
390
Douglas Gregor788f5a12010-03-20 00:41:21 +0000391 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000392 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
393
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000394 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000395 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
396 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000397
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000398 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000399}
400
401template<typename InputIterator>
402bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000403 InputIterator Last,
404 PreprocessingRecord &PPRec,
405 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000406 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000407 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
408 continue;
409
410 PreprocessedEntity *PPE = *First;
411 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000412 if (Visit(MakeMacroExpansionCursor(ME, TU)))
413 return true;
414
415 continue;
416 }
417
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000418 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000419 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
420 return true;
421
422 continue;
423 }
424
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000425 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000426 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
427 return true;
428
429 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000430 }
431 }
432
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000433 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000434}
435
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000437///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438/// \returns true if the visitation should be aborted, false if it
439/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000440bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000441 if (clang_isReference(Cursor.kind) &&
442 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000443 // By definition, references have no children.
444 return false;
445 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000446
447 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000448 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000449 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000450
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451 if (clang_isDeclaration(Cursor.kind)) {
452 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000453 if (!D)
454 return false;
455
Ted Kremenek539311e2010-02-18 18:47:01 +0000456 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000458
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000459 if (clang_isStatement(Cursor.kind)) {
460 if (Stmt *S = getCursorStmt(Cursor))
461 return Visit(S);
462
463 return false;
464 }
465
466 if (clang_isExpression(Cursor.kind)) {
467 if (Expr *E = getCursorExpr(Cursor))
468 return Visit(E);
469
470 return false;
471 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000474 CXTranslationUnit tu = getCursorTU(Cursor);
475 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000476
477 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
478 for (unsigned I = 0; I != 2; ++I) {
479 if (VisitOrder[I]) {
480 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
481 RegionOfInterest.isInvalid()) {
482 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
483 TLEnd = CXXUnit->top_level_end();
484 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000485 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000486 return true;
487 }
488 } else if (VisitDeclContext(
489 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000490 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000491 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000492 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000493
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000494 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000495 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
496 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000498
Douglas Gregor7b691f332010-01-20 21:13:59 +0000499 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000501
Douglas Gregorc314aa42011-03-02 19:17:03 +0000502 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
503 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
504 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
505 return Visit(BaseTSInfo->getTypeLoc());
506 }
507 }
508 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000509
510 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
511 IBOutletCollectionAttr *A =
512 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
513 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
514 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
515 A->getInterfaceLoc(), TU));
516 }
517
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000519 return false;
520}
521
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000522bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000523 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
524 if (Visit(TSInfo->getTypeLoc()))
525 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000526
Ted Kremenek664cffd2010-07-22 11:30:19 +0000527 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000528 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000529
530 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000531}
532
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000533llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
534 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000535 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000536 if (Range.isInvalid())
537 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000538
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000539 switch (CompareRegionOfInterest(Range)) {
540 case RangeBefore:
541 // This declaration comes before the region of interest; skip it.
542 return llvm::Optional<bool>();
543
544 case RangeAfter:
545 // This declaration comes after the region of interest; we're done.
546 return false;
547
548 case RangeOverlap:
549 // This declaration overlaps the region of interest; visit it.
550 break;
551 }
552 }
553 return true;
554}
555
556bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
557 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
558
559 // FIXME: Eventually remove. This part of a hack to support proper
560 // iteration over all Decls contained lexically within an ObjC container.
561 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
562 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
563
564 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000565 Decl *D = *I;
566 if (D->getLexicalDeclContext() != DC)
567 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000568 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000569 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
570 if (!V.hasValue())
571 continue;
572 if (!V.getValue())
573 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000574 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000575 return true;
576 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000577 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000578}
579
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000580bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
581 llvm_unreachable("Translation units are visited directly by Visit()");
582 return false;
583}
584
Richard Smith162e1c12011-04-15 14:24:37 +0000585bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
586 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
587 return Visit(TSInfo->getTypeLoc());
588
589 return false;
590}
591
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000592bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
593 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
594 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000596 return false;
597}
598
599bool CursorVisitor::VisitTagDecl(TagDecl *D) {
600 return VisitDeclContext(D);
601}
602
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000603bool CursorVisitor::VisitClassTemplateSpecializationDecl(
604 ClassTemplateSpecializationDecl *D) {
605 bool ShouldVisitBody = false;
606 switch (D->getSpecializationKind()) {
607 case TSK_Undeclared:
608 case TSK_ImplicitInstantiation:
609 // Nothing to visit
610 return false;
611
612 case TSK_ExplicitInstantiationDeclaration:
613 case TSK_ExplicitInstantiationDefinition:
614 break;
615
616 case TSK_ExplicitSpecialization:
617 ShouldVisitBody = true;
618 break;
619 }
620
621 // Visit the template arguments used in the specialization.
622 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
623 TypeLoc TL = SpecType->getTypeLoc();
624 if (TemplateSpecializationTypeLoc *TSTLoc
625 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
626 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
627 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
628 return true;
629 }
630 }
631
632 if (ShouldVisitBody && VisitCXXRecordDecl(D))
633 return true;
634
635 return false;
636}
637
Douglas Gregor74dbe642010-08-31 19:31:58 +0000638bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
639 ClassTemplatePartialSpecializationDecl *D) {
640 // FIXME: Visit the "outer" template parameter lists on the TagDecl
641 // before visiting these template parameters.
642 if (VisitTemplateParameters(D->getTemplateParameters()))
643 return true;
644
645 // Visit the partial specialization arguments.
646 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
647 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
648 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
649 return true;
650
651 return VisitCXXRecordDecl(D);
652}
653
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000654bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000655 // Visit the default argument.
656 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
657 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
658 if (Visit(DefArg->getTypeLoc()))
659 return true;
660
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000661 return false;
662}
663
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000664bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
665 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000666 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000667 return false;
668}
669
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000670bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
671 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
672 if (Visit(TSInfo->getTypeLoc()))
673 return true;
674
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000675 // Visit the nested-name-specifier, if present.
676 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
677 if (VisitNestedNameSpecifierLoc(QualifierLoc))
678 return true;
679
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000680 return false;
681}
682
Douglas Gregora67e03f2010-09-09 21:42:20 +0000683/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000684static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
685 CXXCtorInitializer const * const *X
686 = static_cast<CXXCtorInitializer const * const *>(Xp);
687 CXXCtorInitializer const * const *Y
688 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000689
690 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
691 return -1;
692 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
693 return 1;
694 else
695 return 0;
696}
697
Douglas Gregorb1373d02010-01-20 20:59:29 +0000698bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000699 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
700 // Visit the function declaration's syntactic components in the order
701 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000702 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000703 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
704
705 // If we have a function declared directly (without the use of a typedef),
706 // visit just the return type. Otherwise, just visit the function's type
707 // now.
708 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
709 (!FTL && Visit(TL)))
710 return true;
711
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000712 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000713 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
714 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000715 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000716
717 // Visit the declaration name.
718 if (VisitDeclarationNameInfo(ND->getNameInfo()))
719 return true;
720
721 // FIXME: Visit explicitly-specified template arguments!
722
723 // Visit the function parameters, if we have a function type.
724 if (FTL && VisitFunctionTypeLoc(*FTL, true))
725 return true;
726
727 // FIXME: Attributes?
728 }
729
Sean Hunt10620eb2011-05-06 20:44:56 +0000730 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000731 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
732 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000733 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000734 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
735 IEnd = Constructor->init_end();
736 I != IEnd; ++I) {
737 if (!(*I)->isWritten())
738 continue;
739
740 WrittenInits.push_back(*I);
741 }
742
743 // Sort the initializers in source order
744 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000745 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000746
747 // Visit the initializers in source order
748 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000749 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000750 if (Init->isAnyMemberInitializer()) {
751 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000752 Init->getMemberLocation(), TU)))
753 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000754 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
755 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000756 return true;
757 }
758
759 // Visit the initializer value.
760 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000761 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000762 return true;
763 }
764 }
765
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000766 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000767 return true;
768 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000769
Douglas Gregorb1373d02010-01-20 20:59:29 +0000770 return false;
771}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000772
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000773bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
774 if (VisitDeclaratorDecl(D))
775 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000777 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000778 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780 return false;
781}
782
783bool CursorVisitor::VisitVarDecl(VarDecl *D) {
784 if (VisitDeclaratorDecl(D))
785 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000788 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000789
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000790 return false;
791}
792
Douglas Gregor84b51d72010-09-01 20:16:53 +0000793bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
794 if (VisitDeclaratorDecl(D))
795 return true;
796
797 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
798 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000799 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000800
801 return false;
802}
803
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000804bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
805 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
806 // before visiting these template parameters.
807 if (VisitTemplateParameters(D->getTemplateParameters()))
808 return true;
809
810 return VisitFunctionDecl(D->getTemplatedDecl());
811}
812
Douglas Gregor39d6f072010-08-31 19:02:00 +0000813bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
814 // FIXME: Visit the "outer" template parameter lists on the TagDecl
815 // before visiting these template parameters.
816 if (VisitTemplateParameters(D->getTemplateParameters()))
817 return true;
818
819 return VisitCXXRecordDecl(D->getTemplatedDecl());
820}
821
Douglas Gregor84b51d72010-09-01 20:16:53 +0000822bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
823 if (VisitTemplateParameters(D->getTemplateParameters()))
824 return true;
825
826 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
827 VisitTemplateArgumentLoc(D->getDefaultArgument()))
828 return true;
829
830 return false;
831}
832
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000833bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000834 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
835 if (Visit(TSInfo->getTypeLoc()))
836 return true;
837
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839 PEnd = ND->param_end();
840 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000841 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 return true;
843 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000844
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000845 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000846 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000847 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000848
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849 return false;
850}
851
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000852template <typename DeclIt>
853static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
854 SourceManager &SM, SourceLocation EndLoc,
855 SmallVectorImpl<Decl *> &Decls) {
856 DeclIt next = *DI_current;
857 while (++next != DE_current) {
858 Decl *D_next = *next;
859 if (!D_next)
860 break;
861 SourceLocation L = D_next->getLocStart();
862 if (!L.isValid())
863 break;
864 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
865 *DI_current = next;
866 Decls.push_back(D_next);
867 continue;
868 }
869 break;
870 }
871}
872
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000873namespace {
874 struct ContainerDeclsSort {
875 SourceManager &SM;
876 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
877 bool operator()(Decl *A, Decl *B) {
878 SourceLocation L_A = A->getLocStart();
879 SourceLocation L_B = B->getLocStart();
880 assert(L_A.isValid() && L_B.isValid());
881 return SM.isBeforeInTranslationUnit(L_A, L_B);
882 }
883 };
884}
885
Douglas Gregora59e3902010-01-21 23:27:09 +0000886bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000887 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
888 // an @implementation can lexically contain Decls that are not properly
889 // nested in the AST. When we identify such cases, we need to retrofit
890 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000891 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000892 return VisitDeclContext(D);
893
894 // Scan the Decls that immediately come after the container
895 // in the current DeclContext. If any fall within the
896 // container's lexical region, stash them into a vector
897 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000898 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000899 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000900 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000901 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000902 if (DI_current) {
903 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
904 DeclsInContainer);
905 } else {
906 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
907 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000908 }
909 }
910
911 // The common case.
912 if (DeclsInContainer.empty())
913 return VisitDeclContext(D);
914
915 // Get all the Decls in the DeclContext, and sort them with the
916 // additional ones we've collected. Then visit them.
917 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
918 I!=E; ++I) {
919 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000920 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
921 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000922 continue;
923 DeclsInContainer.push_back(subDecl);
924 }
925
926 // Now sort the Decls so that they appear in lexical order.
927 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
928 ContainerDeclsSort(SM));
929
930 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000931 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000932 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000933 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000934 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
935 if (!V.hasValue())
936 continue;
937 if (!V.getValue())
938 return false;
939 if (Visit(Cursor, true))
940 return true;
941 }
942 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000943}
944
Douglas Gregorb1373d02010-01-20 20:59:29 +0000945bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000946 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
947 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000948 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000950 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
951 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
952 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000953 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000954 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000955
Douglas Gregora59e3902010-01-21 23:27:09 +0000956 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000957}
958
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000959bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
960 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
961 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
962 E = PID->protocol_end(); I != E; ++I, ++PL)
963 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
964 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000965
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000966 return VisitObjCContainerDecl(PID);
967}
968
Ted Kremenek23173d72010-05-18 21:09:07 +0000969bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000970 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000971 return true;
972
Ted Kremenek23173d72010-05-18 21:09:07 +0000973 // FIXME: This implements a workaround with @property declarations also being
974 // installed in the DeclContext for the @interface. Eventually this code
975 // should be removed.
976 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
977 if (!CDecl || !CDecl->IsClassExtension())
978 return false;
979
980 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
981 if (!ID)
982 return false;
983
984 IdentifierInfo *PropertyId = PD->getIdentifier();
985 ObjCPropertyDecl *prevDecl =
986 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
987
988 if (!prevDecl)
989 return false;
990
991 // Visit synthesized methods since they will be skipped when visiting
992 // the @interface.
993 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000994 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000995 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000996 return true;
997
998 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000999 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001000 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001001 return true;
1002
1003 return false;
1004}
1005
Douglas Gregorb1373d02010-01-20 20:59:29 +00001006bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001007 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008 if (D->getSuperClass() &&
1009 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001010 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001011 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001012 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001014 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1015 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1016 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001017 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001018 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001019
Douglas Gregora59e3902010-01-21 23:27:09 +00001020 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001021}
1022
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001023bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1024 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001025}
1026
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001027bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001028 // 'ID' could be null when dealing with invalid code.
1029 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1030 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1031 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001032
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001033 return VisitObjCImplDecl(D);
1034}
1035
1036bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1037#if 0
1038 // Issue callbacks for super class.
1039 // FIXME: No source location information!
1040 if (D->getSuperClass() &&
1041 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043 TU)))
1044 return true;
1045#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001046
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001047 return VisitObjCImplDecl(D);
1048}
1049
1050bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1051 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1052 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1053 E = D->protocol_end();
1054 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001055 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001056 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001057
1058 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001059}
1060
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001062 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
Douglas Gregoraf764722011-12-14 17:12:03 +00001063 D->getNameLoc(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001064 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001065 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001066}
1067
Douglas Gregora4ffd852010-11-17 01:03:52 +00001068bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1069 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1070 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1071
1072 return false;
1073}
1074
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001075bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1076 return VisitDeclContext(D);
1077}
1078
Douglas Gregor69319002010-08-31 23:48:11 +00001079bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001081 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1082 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001083 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001084
1085 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1086 D->getTargetNameLoc(), TU));
1087}
1088
Douglas Gregor7e242562010-09-01 19:52:22 +00001089bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001091 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1092 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001093 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001094 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001095
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001096 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1097 return true;
1098
Douglas Gregor7e242562010-09-01 19:52:22 +00001099 return VisitDeclarationNameInfo(D->getNameInfo());
1100}
1101
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001102bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001103 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001104 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1105 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001107
1108 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1109 D->getIdentLocation(), TU));
1110}
1111
Douglas Gregor7e242562010-09-01 19:52:22 +00001112bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001113 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001114 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1115 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001116 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001117 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118
Douglas Gregor7e242562010-09-01 19:52:22 +00001119 return VisitDeclarationNameInfo(D->getNameInfo());
1120}
1121
1122bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1123 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001124 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001125 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1126 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001127 return true;
1128
Douglas Gregor7e242562010-09-01 19:52:22 +00001129 return false;
1130}
1131
Douglas Gregor01829d32010-08-31 14:41:23 +00001132bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1133 switch (Name.getName().getNameKind()) {
1134 case clang::DeclarationName::Identifier:
1135 case clang::DeclarationName::CXXLiteralOperatorName:
1136 case clang::DeclarationName::CXXOperatorName:
1137 case clang::DeclarationName::CXXUsingDirective:
1138 return false;
1139
1140 case clang::DeclarationName::CXXConstructorName:
1141 case clang::DeclarationName::CXXDestructorName:
1142 case clang::DeclarationName::CXXConversionFunctionName:
1143 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1144 return Visit(TSInfo->getTypeLoc());
1145 return false;
1146
1147 case clang::DeclarationName::ObjCZeroArgSelector:
1148 case clang::DeclarationName::ObjCOneArgSelector:
1149 case clang::DeclarationName::ObjCMultiArgSelector:
1150 // FIXME: Per-identifier location info?
1151 return false;
1152 }
1153
1154 return false;
1155}
1156
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001157bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1158 SourceRange Range) {
1159 // FIXME: This whole routine is a hack to work around the lack of proper
1160 // source information in nested-name-specifiers (PR5791). Since we do have
1161 // a beginning source location, we can visit the first component of the
1162 // nested-name-specifier, if it's a single-token component.
1163 if (!NNS)
1164 return false;
1165
1166 // Get the first component in the nested-name-specifier.
1167 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1168 NNS = Prefix;
1169
1170 switch (NNS->getKind()) {
1171 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001172 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1173 TU));
1174
Douglas Gregor14aba762011-02-24 02:36:08 +00001175 case NestedNameSpecifier::NamespaceAlias:
1176 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1177 Range.getBegin(), TU));
1178
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001179 case NestedNameSpecifier::TypeSpec: {
1180 // If the type has a form where we know that the beginning of the source
1181 // range matches up with a reference cursor. Visit the appropriate reference
1182 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001183 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001184 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1185 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1186 if (const TagType *Tag = dyn_cast<TagType>(T))
1187 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1188 if (const TemplateSpecializationType *TST
1189 = dyn_cast<TemplateSpecializationType>(T))
1190 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1191 break;
1192 }
1193
1194 case NestedNameSpecifier::TypeSpecWithTemplate:
1195 case NestedNameSpecifier::Global:
1196 case NestedNameSpecifier::Identifier:
1197 break;
1198 }
1199
1200 return false;
1201}
1202
Douglas Gregordc355712011-02-25 00:36:19 +00001203bool
1204CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001205 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001206 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1207 Qualifiers.push_back(Qualifier);
1208
1209 while (!Qualifiers.empty()) {
1210 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1211 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1212 switch (NNS->getKind()) {
1213 case NestedNameSpecifier::Namespace:
1214 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001215 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001216 TU)))
1217 return true;
1218
1219 break;
1220
1221 case NestedNameSpecifier::NamespaceAlias:
1222 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001223 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001224 TU)))
1225 return true;
1226
1227 break;
1228
1229 case NestedNameSpecifier::TypeSpec:
1230 case NestedNameSpecifier::TypeSpecWithTemplate:
1231 if (Visit(Q.getTypeLoc()))
1232 return true;
1233
1234 break;
1235
1236 case NestedNameSpecifier::Global:
1237 case NestedNameSpecifier::Identifier:
1238 break;
1239 }
1240 }
1241
1242 return false;
1243}
1244
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001245bool CursorVisitor::VisitTemplateParameters(
1246 const TemplateParameterList *Params) {
1247 if (!Params)
1248 return false;
1249
1250 for (TemplateParameterList::const_iterator P = Params->begin(),
1251 PEnd = Params->end();
1252 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001253 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001254 return true;
1255 }
1256
1257 return false;
1258}
1259
Douglas Gregor0b36e612010-08-31 20:37:03 +00001260bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1261 switch (Name.getKind()) {
1262 case TemplateName::Template:
1263 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1264
1265 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001266 // Visit the overloaded template set.
1267 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1268 return true;
1269
Douglas Gregor0b36e612010-08-31 20:37:03 +00001270 return false;
1271
1272 case TemplateName::DependentTemplate:
1273 // FIXME: Visit nested-name-specifier.
1274 return false;
1275
1276 case TemplateName::QualifiedTemplate:
1277 // FIXME: Visit nested-name-specifier.
1278 return Visit(MakeCursorTemplateRef(
1279 Name.getAsQualifiedTemplateName()->getDecl(),
1280 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001281
1282 case TemplateName::SubstTemplateTemplateParm:
1283 return Visit(MakeCursorTemplateRef(
1284 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1285 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001286
1287 case TemplateName::SubstTemplateTemplateParmPack:
1288 return Visit(MakeCursorTemplateRef(
1289 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1290 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001291 }
1292
1293 return false;
1294}
1295
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001296bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1297 switch (TAL.getArgument().getKind()) {
1298 case TemplateArgument::Null:
1299 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001300 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301 return false;
1302
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001303 case TemplateArgument::Type:
1304 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1305 return Visit(TSInfo->getTypeLoc());
1306 return false;
1307
1308 case TemplateArgument::Declaration:
1309 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001310 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001311 return false;
1312
1313 case TemplateArgument::Expression:
1314 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001315 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001316 return false;
1317
1318 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001319 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001320 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1321 return true;
1322
Douglas Gregora7fc9012011-01-05 18:58:31 +00001323 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001324 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001325 }
1326
1327 return false;
1328}
1329
Ted Kremeneka0536d82010-05-07 01:04:29 +00001330bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1331 return VisitDeclContext(D);
1332}
1333
Douglas Gregor01829d32010-08-31 14:41:23 +00001334bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1335 return Visit(TL.getUnqualifiedLoc());
1336}
1337
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001339 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340
1341 // Some builtin types (such as Objective-C's "id", "sel", and
1342 // "Class") have associated declarations. Create cursors for those.
1343 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001344 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001345
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001346 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001347 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001348 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001349#define BUILTIN_TYPE(Id, SingletonId)
1350#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1351#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1352#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1353#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1354#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001355 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001356
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001357 case BuiltinType::ObjCId:
1358 VisitType = Context.getObjCIdType();
1359 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001360
1361 case BuiltinType::ObjCClass:
1362 VisitType = Context.getObjCClassType();
1363 break;
1364
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001365 case BuiltinType::ObjCSel:
1366 VisitType = Context.getObjCSelType();
1367 break;
1368 }
1369
1370 if (!VisitType.isNull()) {
1371 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001372 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001373 TU));
1374 }
1375
1376 return false;
1377}
1378
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001379bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001380 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001381}
1382
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001383bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1384 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1385}
1386
1387bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001388 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001389 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001390
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001391 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1392}
1393
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001394bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001395 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001396}
1397
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001398bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1399 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1400 return true;
1401
John McCallc12c5bb2010-05-15 11:32:37 +00001402 return false;
1403}
1404
1405bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1406 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1407 return true;
1408
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1410 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1411 TU)))
1412 return true;
1413 }
1414
1415 return false;
1416}
1417
1418bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001419 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001420}
1421
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001422bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1423 return Visit(TL.getInnerLoc());
1424}
1425
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001426bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1427 return Visit(TL.getPointeeLoc());
1428}
1429
1430bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1431 return Visit(TL.getPointeeLoc());
1432}
1433
1434bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1435 return Visit(TL.getPointeeLoc());
1436}
1437
1438bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001439 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001440}
1441
1442bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001443 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001444}
1445
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001446bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1447 return Visit(TL.getModifiedLoc());
1448}
1449
Douglas Gregor01829d32010-08-31 14:41:23 +00001450bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1451 bool SkipResultType) {
1452 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001453 return true;
1454
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001456 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001457 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001458 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001459
1460 return false;
1461}
1462
1463bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1464 if (Visit(TL.getElementLoc()))
1465 return true;
1466
1467 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001468 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001469
1470 return false;
1471}
1472
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001473bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1474 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001475 // Visit the template name.
1476 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1477 TL.getTemplateNameLoc()))
1478 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001479
1480 // Visit the template arguments.
1481 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1482 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1483 return true;
1484
1485 return false;
1486}
1487
Douglas Gregor2332c112010-01-21 20:48:56 +00001488bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1489 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1490}
1491
1492bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1493 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1494 return Visit(TSInfo->getTypeLoc());
1495
1496 return false;
1497}
1498
Sean Huntca63c202011-05-24 22:41:36 +00001499bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1500 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1501 return Visit(TSInfo->getTypeLoc());
1502
1503 return false;
1504}
1505
Douglas Gregor2494dd02011-03-01 01:34:45 +00001506bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1507 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1508 return true;
1509
1510 return false;
1511}
1512
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001513bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1514 DependentTemplateSpecializationTypeLoc TL) {
1515 // Visit the nested-name-specifier, if there is one.
1516 if (TL.getQualifierLoc() &&
1517 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1518 return true;
1519
1520 // Visit the template arguments.
1521 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1522 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1523 return true;
1524
1525 return false;
1526}
1527
Douglas Gregor9e876872011-03-01 18:12:44 +00001528bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1529 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1530 return true;
1531
1532 return Visit(TL.getNamedTypeLoc());
1533}
1534
Douglas Gregor7536dd52010-12-20 02:24:11 +00001535bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1536 return Visit(TL.getPatternLoc());
1537}
1538
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001539bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1540 if (Expr *E = TL.getUnderlyingExpr())
1541 return Visit(MakeCXCursor(E, StmtParent, TU));
1542
1543 return false;
1544}
1545
1546bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1547 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1548}
1549
Eli Friedmanb001de72011-10-06 23:00:33 +00001550bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1551 return Visit(TL.getValueLoc());
1552}
1553
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001554#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1555bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1556 return Visit##PARENT##Loc(TL); \
1557}
1558
1559DEFAULT_TYPELOC_IMPL(Complex, Type)
1560DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1561DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1562DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1563DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1564DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1565DEFAULT_TYPELOC_IMPL(Vector, Type)
1566DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1567DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1568DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1569DEFAULT_TYPELOC_IMPL(Record, TagType)
1570DEFAULT_TYPELOC_IMPL(Enum, TagType)
1571DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1572DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1573DEFAULT_TYPELOC_IMPL(Auto, Type)
1574
Ted Kremenek3064ef92010-08-27 21:34:58 +00001575bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001576 // Visit the nested-name-specifier, if present.
1577 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1578 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1579 return true;
1580
John McCall5e1cdac2011-10-07 06:10:15 +00001581 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001582 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1583 E = D->bases_end(); I != E; ++I) {
1584 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1585 return true;
1586 }
1587 }
1588
1589 return VisitTagDecl(D);
1590}
1591
Ted Kremenek09dfa372010-02-18 05:46:33 +00001592bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001593 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1594 i != e; ++i)
1595 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001596 return true;
1597
1598 return false;
1599}
1600
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001601//===----------------------------------------------------------------------===//
1602// Data-recursive visitor methods.
1603//===----------------------------------------------------------------------===//
1604
Ted Kremenek28a71942010-11-13 00:36:47 +00001605namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001606#define DEF_JOB(NAME, DATA, KIND)\
1607class NAME : public VisitorJob {\
1608public:\
1609 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1610 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001611 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001612};
1613
1614DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1615DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001616DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001617DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001618DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001619 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001620DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001621#undef DEF_JOB
1622
1623class DeclVisit : public VisitorJob {
1624public:
1625 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1626 VisitorJob(parent, VisitorJob::DeclVisitKind,
1627 d, isFirst ? (void*) 1 : (void*) 0) {}
1628 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001629 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001630 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001631 Decl *get() const { return static_cast<Decl*>(data[0]); }
1632 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001633};
Ted Kremenek035dc412010-11-13 00:36:50 +00001634class TypeLocVisit : public VisitorJob {
1635public:
1636 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1637 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1638 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1639
1640 static bool classof(const VisitorJob *VJ) {
1641 return VJ->getKind() == TypeLocVisitKind;
1642 }
1643
Ted Kremenek82f3c502010-11-15 22:23:26 +00001644 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001645 QualType T = QualType::getFromOpaquePtr(data[0]);
1646 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001647 }
1648};
1649
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001650class LabelRefVisit : public VisitorJob {
1651public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001652 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1653 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001654 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001655
1656 static bool classof(const VisitorJob *VJ) {
1657 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1658 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001659 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001660 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001661 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001662};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001663
1664class NestedNameSpecifierLocVisit : public VisitorJob {
1665public:
1666 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1667 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1668 Qualifier.getNestedNameSpecifier(),
1669 Qualifier.getOpaqueData()) { }
1670
1671 static bool classof(const VisitorJob *VJ) {
1672 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1673 }
1674
1675 NestedNameSpecifierLoc get() const {
1676 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1677 data[1]);
1678 }
1679};
1680
Ted Kremenekf64d8032010-11-18 00:02:32 +00001681class DeclarationNameInfoVisit : public VisitorJob {
1682public:
1683 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1684 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1685 static bool classof(const VisitorJob *VJ) {
1686 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1687 }
1688 DeclarationNameInfo get() const {
1689 Stmt *S = static_cast<Stmt*>(data[0]);
1690 switch (S->getStmtClass()) {
1691 default:
1692 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001693 case clang::Stmt::MSDependentExistsStmtClass:
1694 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001695 case Stmt::CXXDependentScopeMemberExprClass:
1696 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1697 case Stmt::DependentScopeDeclRefExprClass:
1698 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1699 }
1700 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001701};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001702class MemberRefVisit : public VisitorJob {
1703public:
1704 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1705 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001706 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001707 static bool classof(const VisitorJob *VJ) {
1708 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1709 }
1710 FieldDecl *get() const {
1711 return static_cast<FieldDecl*>(data[0]);
1712 }
1713 SourceLocation getLoc() const {
1714 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1715 }
1716};
Ted Kremenek28a71942010-11-13 00:36:47 +00001717class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1718 VisitorWorkList &WL;
1719 CXCursor Parent;
1720public:
1721 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1722 : WL(wl), Parent(parent) {}
1723
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001724 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001725 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001726 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001727 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001728 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001729 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001730 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001731 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001732 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001733 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001734 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001735 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001736 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001737 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001738 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001739 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001740 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001741 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001742 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001743 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001744 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1745 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001746 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001747 void VisitIfStmt(IfStmt *If);
1748 void VisitInitListExpr(InitListExpr *IE);
1749 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001750 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001751 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001752 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1753 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001754 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001755 void VisitStmt(Stmt *S);
1756 void VisitSwitchStmt(SwitchStmt *S);
1757 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001758 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001759 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001760 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001761 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001762 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001763 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001764 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001765 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1766 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001767
Ted Kremenek28a71942010-11-13 00:36:47 +00001768private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001769 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001770 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001771 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001772 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001773 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001774 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001775 void AddTypeLoc(TypeSourceInfo *TI);
1776 void EnqueueChildren(Stmt *S);
1777};
1778} // end anonyous namespace
1779
Ted Kremenekf64d8032010-11-18 00:02:32 +00001780void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1781 // 'S' should always be non-null, since it comes from the
1782 // statement we are visiting.
1783 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1784}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001785
1786void
1787EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1788 if (Qualifier)
1789 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1790}
1791
Ted Kremenek28a71942010-11-13 00:36:47 +00001792void EnqueueVisitor::AddStmt(Stmt *S) {
1793 if (S)
1794 WL.push_back(StmtVisit(S, Parent));
1795}
Ted Kremenek035dc412010-11-13 00:36:50 +00001796void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001797 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001798 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001799}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001800void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001801 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001802 if (A)
1803 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001804 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001805}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001806void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1807 if (D)
1808 WL.push_back(MemberRefVisit(D, L, Parent));
1809}
Ted Kremenek28a71942010-11-13 00:36:47 +00001810void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1811 if (TI)
1812 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1813 }
1814void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001815 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001816 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001817 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001818 }
1819 if (size == WL.size())
1820 return;
1821 // Now reverse the entries we just added. This will match the DFS
1822 // ordering performed by the worklist.
1823 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1824 std::reverse(I, E);
1825}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001826void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1827 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1828}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001829void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1830 AddDecl(B->getBlockDecl());
1831}
Ted Kremenek28a71942010-11-13 00:36:47 +00001832void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1833 EnqueueChildren(E);
1834 AddTypeLoc(E->getTypeSourceInfo());
1835}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001836void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1837 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1838 E = S->body_rend(); I != E; ++I) {
1839 AddStmt(*I);
1840 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001841}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001842void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001843VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1844 AddStmt(S->getSubStmt());
1845 AddDeclarationNameInfo(S);
1846 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1847 AddNestedNameSpecifierLoc(QualifierLoc);
1848}
1849
1850void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001851VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1852 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1853 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001854 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1855 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001856 if (!E->isImplicitAccess())
1857 AddStmt(E->getBase());
1858}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001859void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1860 // Enqueue the initializer or constructor arguments.
1861 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1862 AddStmt(E->getConstructorArg(I-1));
1863 // Enqueue the array size, if any.
1864 AddStmt(E->getArraySize());
1865 // Enqueue the allocated type.
1866 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1867 // Enqueue the placement arguments.
1868 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1869 AddStmt(E->getPlacementArg(I-1));
1870}
Ted Kremenek28a71942010-11-13 00:36:47 +00001871void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001872 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1873 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001874 AddStmt(CE->getCallee());
1875 AddStmt(CE->getArg(0));
1876}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001877void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1878 // Visit the name of the type being destroyed.
1879 AddTypeLoc(E->getDestroyedTypeInfo());
1880 // Visit the scope type that looks disturbingly like the nested-name-specifier
1881 // but isn't.
1882 AddTypeLoc(E->getScopeTypeInfo());
1883 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001884 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1885 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001886 // Visit base expression.
1887 AddStmt(E->getBase());
1888}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001889void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1890 AddTypeLoc(E->getTypeSourceInfo());
1891}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001892void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1893 EnqueueChildren(E);
1894 AddTypeLoc(E->getTypeSourceInfo());
1895}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001896void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1897 EnqueueChildren(E);
1898 if (E->isTypeOperand())
1899 AddTypeLoc(E->getTypeOperandSourceInfo());
1900}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001901
1902void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1903 *E) {
1904 EnqueueChildren(E);
1905 AddTypeLoc(E->getTypeSourceInfo());
1906}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001907void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1908 EnqueueChildren(E);
1909 if (E->isTypeOperand())
1910 AddTypeLoc(E->getTypeOperandSourceInfo());
1911}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001912
1913void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1914 EnqueueChildren(S);
1915 AddDecl(S->getExceptionDecl());
1916}
1917
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001918void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001919 if (DR->hasExplicitTemplateArgs()) {
1920 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1921 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001922 WL.push_back(DeclRefExprParts(DR, Parent));
1923}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001924void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1925 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1926 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001927 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001928}
Ted Kremenek035dc412010-11-13 00:36:50 +00001929void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1930 unsigned size = WL.size();
1931 bool isFirst = true;
1932 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1933 D != DEnd; ++D) {
1934 AddDecl(*D, isFirst);
1935 isFirst = false;
1936 }
1937 if (size == WL.size())
1938 return;
1939 // Now reverse the entries we just added. This will match the DFS
1940 // ordering performed by the worklist.
1941 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1942 std::reverse(I, E);
1943}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001944void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1945 AddStmt(E->getInit());
1946 typedef DesignatedInitExpr::Designator Designator;
1947 for (DesignatedInitExpr::reverse_designators_iterator
1948 D = E->designators_rbegin(), DEnd = E->designators_rend();
1949 D != DEnd; ++D) {
1950 if (D->isFieldDesignator()) {
1951 if (FieldDecl *Field = D->getField())
1952 AddMemberRef(Field, D->getFieldLoc());
1953 continue;
1954 }
1955 if (D->isArrayDesignator()) {
1956 AddStmt(E->getArrayIndex(*D));
1957 continue;
1958 }
1959 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1960 AddStmt(E->getArrayRangeEnd(*D));
1961 AddStmt(E->getArrayRangeStart(*D));
1962 }
1963}
Ted Kremenek28a71942010-11-13 00:36:47 +00001964void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1965 EnqueueChildren(E);
1966 AddTypeLoc(E->getTypeInfoAsWritten());
1967}
1968void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1969 AddStmt(FS->getBody());
1970 AddStmt(FS->getInc());
1971 AddStmt(FS->getCond());
1972 AddDecl(FS->getConditionVariable());
1973 AddStmt(FS->getInit());
1974}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001975void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1976 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1977}
Ted Kremenek28a71942010-11-13 00:36:47 +00001978void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1979 AddStmt(If->getElse());
1980 AddStmt(If->getThen());
1981 AddStmt(If->getCond());
1982 AddDecl(If->getConditionVariable());
1983}
1984void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1985 // We care about the syntactic form of the initializer list, only.
1986 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1987 IE = Syntactic;
1988 EnqueueChildren(IE);
1989}
1990void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001991 WL.push_back(MemberExprParts(M, Parent));
1992
1993 // If the base of the member access expression is an implicit 'this', don't
1994 // visit it.
1995 // FIXME: If we ever want to show these implicit accesses, this will be
1996 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001997 if (!M->isImplicitAccess())
1998 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001999}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002000void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2001 AddTypeLoc(E->getEncodedTypeSourceInfo());
2002}
Ted Kremenek28a71942010-11-13 00:36:47 +00002003void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2004 EnqueueChildren(M);
2005 AddTypeLoc(M->getClassReceiverTypeInfo());
2006}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002007void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2008 // Visit the components of the offsetof expression.
2009 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2010 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2011 const OffsetOfNode &Node = E->getComponent(I-1);
2012 switch (Node.getKind()) {
2013 case OffsetOfNode::Array:
2014 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2015 break;
2016 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002017 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002018 break;
2019 case OffsetOfNode::Identifier:
2020 case OffsetOfNode::Base:
2021 continue;
2022 }
2023 }
2024 // Visit the type into which we're computing the offset.
2025 AddTypeLoc(E->getTypeSourceInfo());
2026}
Ted Kremenek28a71942010-11-13 00:36:47 +00002027void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002028 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002029 WL.push_back(OverloadExprParts(E, Parent));
2030}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002031void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2032 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002033 EnqueueChildren(E);
2034 if (E->isArgumentType())
2035 AddTypeLoc(E->getArgumentTypeInfo());
2036}
Ted Kremenek28a71942010-11-13 00:36:47 +00002037void EnqueueVisitor::VisitStmt(Stmt *S) {
2038 EnqueueChildren(S);
2039}
2040void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2041 AddStmt(S->getBody());
2042 AddStmt(S->getCond());
2043 AddDecl(S->getConditionVariable());
2044}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002045
Ted Kremenek28a71942010-11-13 00:36:47 +00002046void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2047 AddStmt(W->getBody());
2048 AddStmt(W->getCond());
2049 AddDecl(W->getConditionVariable());
2050}
John Wiegley21ff2e52011-04-28 00:16:57 +00002051
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002052void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2053 AddTypeLoc(E->getQueriedTypeSourceInfo());
2054}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002055
2056void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002057 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002058 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002059}
2060
John Wiegley21ff2e52011-04-28 00:16:57 +00002061void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2062 AddTypeLoc(E->getQueriedTypeSourceInfo());
2063}
2064
John Wiegley55262202011-04-25 06:54:41 +00002065void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2066 EnqueueChildren(E);
2067}
2068
Ted Kremenek28a71942010-11-13 00:36:47 +00002069void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2070 VisitOverloadExpr(U);
2071 if (!U->isImplicitAccess())
2072 AddStmt(U->getBase());
2073}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002074void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2075 AddStmt(E->getSubExpr());
2076 AddTypeLoc(E->getWrittenTypeInfo());
2077}
Douglas Gregor94d96292011-01-19 20:34:17 +00002078void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2079 WL.push_back(SizeOfPackExprParts(E, Parent));
2080}
John McCall4b9c2d22011-11-06 09:01:30 +00002081void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2082 // If the opaque value has a source expression, just transparently
2083 // visit that. This is useful for (e.g.) pseudo-object expressions.
2084 if (Expr *SourceExpr = E->getSourceExpr())
2085 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002086}
2087void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2088 // Treat the expression like its syntactic form.
2089 Visit(E->getSyntacticForm());
2090}
Ted Kremenek60458782010-11-12 21:34:16 +00002091
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002092void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002093 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002094}
2095
2096bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2097 if (RegionOfInterest.isValid()) {
2098 SourceRange Range = getRawCursorExtent(C);
2099 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2100 return false;
2101 }
2102 return true;
2103}
2104
2105bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2106 while (!WL.empty()) {
2107 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002108 VisitorJob LI = WL.back();
2109 WL.pop_back();
2110
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002111 // Set the Parent field, then back to its old value once we're done.
2112 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2113
2114 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002115 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002116 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002117 if (!D)
2118 continue;
2119
2120 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002121 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2122 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002123 return true;
2124
2125 continue;
2126 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002127 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002128 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002129 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2130 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2131 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2132 Arg != ArgEnd; ++Arg) {
2133 if (VisitTemplateArgumentLoc(*Arg))
2134 return true;
2135 }
2136 continue;
2137 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002138 case VisitorJob::TypeLocVisitKind: {
2139 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002140 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002141 return true;
2142 continue;
2143 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002144 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002145 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002146 if (LabelStmt *stmt = LS->getStmt()) {
2147 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2148 TU))) {
2149 return true;
2150 }
2151 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002152 continue;
2153 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002154
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002155 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2156 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2157 if (VisitNestedNameSpecifierLoc(V->get()))
2158 return true;
2159 continue;
2160 }
2161
Ted Kremenekf64d8032010-11-18 00:02:32 +00002162 case VisitorJob::DeclarationNameInfoVisitKind: {
2163 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2164 ->get()))
2165 return true;
2166 continue;
2167 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002168 case VisitorJob::MemberRefVisitKind: {
2169 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2170 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2171 return true;
2172 continue;
2173 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002174 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002175 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002176 if (!S)
2177 continue;
2178
Ted Kremenekf1107452010-11-12 18:26:56 +00002179 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002180 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002181 if (!IsInRegionOfInterest(Cursor))
2182 continue;
2183 switch (Visitor(Cursor, Parent, ClientData)) {
2184 case CXChildVisit_Break: return true;
2185 case CXChildVisit_Continue: break;
2186 case CXChildVisit_Recurse:
2187 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002188 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002189 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002190 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002191 }
2192 case VisitorJob::MemberExprPartsKind: {
2193 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002194 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002195
2196 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002197 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2198 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002199 return true;
2200
2201 // Visit the declaration name.
2202 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2203 return true;
2204
2205 // Visit the explicitly-specified template arguments, if any.
2206 if (M->hasExplicitTemplateArgs()) {
2207 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2208 *ArgEnd = Arg + M->getNumTemplateArgs();
2209 Arg != ArgEnd; ++Arg) {
2210 if (VisitTemplateArgumentLoc(*Arg))
2211 return true;
2212 }
2213 }
2214 continue;
2215 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002216 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002217 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002218 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002219 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2220 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002221 return true;
2222 // Visit declaration name.
2223 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2224 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002225 continue;
2226 }
Ted Kremenek60458782010-11-12 21:34:16 +00002227 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002228 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002229 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002230 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2231 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002232 return true;
2233 // Visit the declaration name.
2234 if (VisitDeclarationNameInfo(O->getNameInfo()))
2235 return true;
2236 // Visit the overloaded declaration reference.
2237 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2238 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002239 continue;
2240 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002241 case VisitorJob::SizeOfPackExprPartsKind: {
2242 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2243 NamedDecl *Pack = E->getPack();
2244 if (isa<TemplateTypeParmDecl>(Pack)) {
2245 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2246 E->getPackLoc(), TU)))
2247 return true;
2248
2249 continue;
2250 }
2251
2252 if (isa<TemplateTemplateParmDecl>(Pack)) {
2253 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2254 E->getPackLoc(), TU)))
2255 return true;
2256
2257 continue;
2258 }
2259
2260 // Non-type template parameter packs and function parameter packs are
2261 // treated like DeclRefExpr cursors.
2262 continue;
2263 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002264 }
2265 }
2266 return false;
2267}
2268
Ted Kremenekcdba6592010-11-18 00:42:18 +00002269bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002270 VisitorWorkList *WL = 0;
2271 if (!WorkListFreeList.empty()) {
2272 WL = WorkListFreeList.back();
2273 WL->clear();
2274 WorkListFreeList.pop_back();
2275 }
2276 else {
2277 WL = new VisitorWorkList();
2278 WorkListCache.push_back(WL);
2279 }
2280 EnqueueWorkList(*WL, S);
2281 bool result = RunVisitorWorkList(*WL);
2282 WorkListFreeList.push_back(WL);
2283 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002284}
2285
Francois Pichet48a8d142011-07-25 22:00:44 +00002286namespace {
2287typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2288RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2289 const DeclarationNameInfo &NI,
2290 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002291 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002292 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2293 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2294 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2295
2296 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2297
2298 RefNamePieces Pieces;
2299
2300 if (WantQualifier && QLoc.isValid())
2301 Pieces.push_back(QLoc);
2302
2303 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2304 Pieces.push_back(NI.getLoc());
2305
2306 if (WantTemplateArgs && TemplateArgs)
2307 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2308 TemplateArgs->RAngleLoc));
2309
2310 if (Kind == DeclarationName::CXXOperatorName) {
2311 Pieces.push_back(SourceLocation::getFromRawEncoding(
2312 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2313 Pieces.push_back(SourceLocation::getFromRawEncoding(
2314 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2315 }
2316
2317 if (WantSinglePiece) {
2318 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2319 Pieces.clear();
2320 Pieces.push_back(R);
2321 }
2322
2323 return Pieces;
2324}
2325}
2326
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002327//===----------------------------------------------------------------------===//
2328// Misc. API hooks.
2329//===----------------------------------------------------------------------===//
2330
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002331static llvm::sys::Mutex EnableMultithreadingMutex;
2332static bool EnabledMultithreading;
2333
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002334static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002335 // Write the result out to stderr avoiding errs() because raw_ostreams can
2336 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002337 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002338 ::abort();
2339}
2340
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002341extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002342CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2343 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002344 // Disable pretty stack trace functionality, which will otherwise be a very
2345 // poor citizen of the world and set up all sorts of signal handlers.
2346 llvm::DisablePrettyStackTrace = true;
2347
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002348 // We use crash recovery to make some of our APIs more reliable, implicitly
2349 // enable it.
2350 llvm::CrashRecoveryContext::Enable();
2351
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002352 // Enable support for multithreading in LLVM.
2353 {
2354 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2355 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002356 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002357 llvm::llvm_start_multithreaded();
2358 EnabledMultithreading = true;
2359 }
2360 }
2361
Douglas Gregora030b7c2010-01-22 20:35:53 +00002362 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002363 if (excludeDeclarationsFromPCH)
2364 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002365 if (displayDiagnostics)
2366 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002367 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002368}
2369
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002370void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002371 if (CIdx)
2372 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002373}
2374
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002375void clang_toggleCrashRecovery(unsigned isEnabled) {
2376 if (isEnabled)
2377 llvm::CrashRecoveryContext::Enable();
2378 else
2379 llvm::CrashRecoveryContext::Disable();
2380}
2381
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002382CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002383 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002384 if (!CIdx)
2385 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002386
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002387 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002388 FileSystemOptions FileSystemOpts;
2389 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002390
David Blaikied6471f72011-09-25 23:23:43 +00002391 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002392 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002393 CXXIdx->getOnlyLocalDecls(),
2394 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002395 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002396}
2397
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002398unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002399 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002400 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002401}
2402
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002403CXTranslationUnit
2404clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2405 const char *source_filename,
2406 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002407 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002408 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002409 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002410 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002411 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002412 return clang_parseTranslationUnit(CIdx, source_filename,
2413 command_line_args, num_command_line_args,
2414 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002415 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002416}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002417
2418struct ParseTranslationUnitInfo {
2419 CXIndex CIdx;
2420 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002421 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002422 int num_command_line_args;
2423 struct CXUnsavedFile *unsaved_files;
2424 unsigned num_unsaved_files;
2425 unsigned options;
2426 CXTranslationUnit result;
2427};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002428static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002429 ParseTranslationUnitInfo *PTUI =
2430 static_cast<ParseTranslationUnitInfo*>(UserData);
2431 CXIndex CIdx = PTUI->CIdx;
2432 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002433 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002434 int num_command_line_args = PTUI->num_command_line_args;
2435 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2436 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2437 unsigned options = PTUI->options;
2438 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002439
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002440 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002441 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002442
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002443 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2444
Douglas Gregor44c181a2010-07-23 00:33:23 +00002445 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002446 // FIXME: Add a flag for modules.
2447 TranslationUnitKind TUKind
2448 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002449 bool CacheCodeCompetionResults
2450 = options & CXTranslationUnit_CacheCompletionResults;
2451
Douglas Gregor5352ac02010-01-28 00:27:43 +00002452 // Configure the diagnostics.
2453 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002454 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002455 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2456 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
Ted Kremenek25a11e12011-03-22 01:15:24 +00002458 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002459 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2460 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002461 DiagCleanup(Diags.getPtr());
2462
2463 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2464 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2465
2466 // Recover resources if we crash before exiting this function.
2467 llvm::CrashRecoveryContextCleanupRegistrar<
2468 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2469
Douglas Gregor4db64a42010-01-23 00:14:00 +00002470 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002471 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002472 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002473 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002474 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2475 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002476 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002477
Ted Kremenek25a11e12011-03-22 01:15:24 +00002478 llvm::OwningPtr<std::vector<const char *> >
2479 Args(new std::vector<const char*>());
2480
2481 // Recover resources if we crash before exiting this method.
2482 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2483 ArgsCleanup(Args.get());
2484
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002485 // Since the Clang C library is primarily used by batch tools dealing with
2486 // (often very broken) source code, where spell-checking can have a
2487 // significant negative impact on performance (particularly when
2488 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002489 // Only do this if we haven't found a spell-checking-related argument.
2490 bool FoundSpellCheckingArgument = false;
2491 for (int I = 0; I != num_command_line_args; ++I) {
2492 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2493 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2494 FoundSpellCheckingArgument = true;
2495 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002496 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002497 }
2498 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002499 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002500
Ted Kremenek25a11e12011-03-22 01:15:24 +00002501 Args->insert(Args->end(), command_line_args,
2502 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002503
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002504 // The 'source_filename' argument is optional. If the caller does not
2505 // specify it then it is assumed that the source file is specified
2506 // in the actual argument list.
2507 // Put the source file after command_line_args otherwise if '-x' flag is
2508 // present it will be unused.
2509 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002510 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002511
Douglas Gregor44c181a2010-07-23 00:33:23 +00002512 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002513 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002514 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002515 Args->push_back("-Xclang");
2516 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002517 NestedMacroExpansions
2518 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002519 }
2520
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002521 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002522 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002523 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2524 /* vector::data() not portable */,
2525 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002526 Diags,
2527 CXXIdx->getClangResourcesPath(),
2528 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002529 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002530 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002531 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002532 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002533 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002534 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002535 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002536 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002537
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002538 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002539 // Make sure to check that 'Unit' is non-NULL.
2540 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2541 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2542 DEnd = Unit->stored_diag_end();
2543 D != DEnd; ++D) {
2544 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2545 CXString Msg = clang_formatDiagnostic(&Diag,
2546 clang_defaultDiagnosticDisplayOptions());
2547 fprintf(stderr, "%s\n", clang_getCString(Msg));
2548 clang_disposeString(Msg);
2549 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002550#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002551 // On Windows, force a flush, since there may be multiple copies of
2552 // stderr and stdout in the file system, all with different buffers
2553 // but writing to the same device.
2554 fflush(stderr);
2555#endif
2556 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002557 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002558
Ted Kremeneka60ed472010-11-16 08:15:36 +00002559 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002560}
2561CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2562 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002563 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002564 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002565 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002566 unsigned num_unsaved_files,
2567 unsigned options) {
2568 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002569 num_command_line_args, unsaved_files,
2570 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002571 llvm::CrashRecoveryContext CRC;
2572
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002573 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002574 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2575 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2576 fprintf(stderr, " 'command_line_args' : [");
2577 for (int i = 0; i != num_command_line_args; ++i) {
2578 if (i)
2579 fprintf(stderr, ", ");
2580 fprintf(stderr, "'%s'", command_line_args[i]);
2581 }
2582 fprintf(stderr, "],\n");
2583 fprintf(stderr, " 'unsaved_files' : [");
2584 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2585 if (i)
2586 fprintf(stderr, ", ");
2587 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2588 unsaved_files[i].Length);
2589 }
2590 fprintf(stderr, "],\n");
2591 fprintf(stderr, " 'options' : %d,\n", options);
2592 fprintf(stderr, "}\n");
2593
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002594 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002595 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2596 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002597 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002598
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002599 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002600}
2601
Douglas Gregor19998442010-08-13 15:35:05 +00002602unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2603 return CXSaveTranslationUnit_None;
2604}
2605
2606int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2607 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002608 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002609 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002610
Douglas Gregor39c411f2011-07-06 16:43:36 +00002611 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002612 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2613 PrintLibclangResourceUsage(TU);
2614 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002615}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002616
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002617void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002618 if (CTUnit) {
2619 // If the translation unit has been marked as unsafe to free, just discard
2620 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002621 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002622 return;
2623
Ted Kremeneka60ed472010-11-16 08:15:36 +00002624 delete static_cast<ASTUnit *>(CTUnit->TUData);
2625 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002626 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002627 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002628 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002629}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002630
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002631unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2632 return CXReparse_None;
2633}
2634
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002635struct ReparseTranslationUnitInfo {
2636 CXTranslationUnit TU;
2637 unsigned num_unsaved_files;
2638 struct CXUnsavedFile *unsaved_files;
2639 unsigned options;
2640 int result;
2641};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002642
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002643static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002644 ReparseTranslationUnitInfo *RTUI =
2645 static_cast<ReparseTranslationUnitInfo*>(UserData);
2646 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002647
2648 // Reset the associated diagnostics.
2649 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2650 TU->Diagnostics = 0;
2651
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002652 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2653 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2654 unsigned options = RTUI->options;
2655 (void) options;
2656 RTUI->result = 1;
2657
Douglas Gregorabc563f2010-07-19 21:46:24 +00002658 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002659 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002660
Ted Kremeneka60ed472010-11-16 08:15:36 +00002661 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002662 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002663
Ted Kremenek25a11e12011-03-22 01:15:24 +00002664 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2665 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2666
2667 // Recover resources if we crash before exiting this function.
2668 llvm::CrashRecoveryContextCleanupRegistrar<
2669 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2670
Douglas Gregorabc563f2010-07-19 21:46:24 +00002671 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002672 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002673 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002674 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002675 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2676 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002677 }
2678
Ted Kremenek4ee99262011-03-22 20:16:19 +00002679 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2680 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002681 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002682}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002683
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002684int clang_reparseTranslationUnit(CXTranslationUnit TU,
2685 unsigned num_unsaved_files,
2686 struct CXUnsavedFile *unsaved_files,
2687 unsigned options) {
2688 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2689 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002690
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002691 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002692 clang_reparseTranslationUnit_Impl(&RTUI);
2693 return RTUI.result;
2694 }
2695
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002696 llvm::CrashRecoveryContext CRC;
2697
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002698 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002699 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002700 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002701 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002702 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2703 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002704
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002705 return RTUI.result;
2706}
2707
Douglas Gregordf95a132010-08-09 20:45:32 +00002708
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002709CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002710 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002711 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002712
Ted Kremeneka60ed472010-11-16 08:15:36 +00002713 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002714 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002715}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002716
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002717CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002718 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002719 return Result;
2720}
2721
Ted Kremenekfb480492010-01-13 21:46:36 +00002722} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002723
Ted Kremenekfb480492010-01-13 21:46:36 +00002724//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002725// CXFile Operations.
2726//===----------------------------------------------------------------------===//
2727
2728extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002729CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002730 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002731 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002732
Steve Naroff88145032009-10-27 14:35:18 +00002733 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002734 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002735}
2736
2737time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002738 if (!SFile)
2739 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002740
Steve Naroff88145032009-10-27 14:35:18 +00002741 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2742 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002743}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002744
Douglas Gregorb9790342010-01-22 21:44:22 +00002745CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2746 if (!tu)
2747 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002748
Ted Kremeneka60ed472010-11-16 08:15:36 +00002749 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002750
Douglas Gregorb9790342010-01-22 21:44:22 +00002751 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002752 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002753}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002754
Douglas Gregordd3e5542011-05-04 00:14:37 +00002755unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2756 if (!tu || !file)
2757 return 0;
2758
2759 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2760 FileEntry *FEnt = static_cast<FileEntry *>(file);
2761 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2762 .isFileMultipleIncludeGuarded(FEnt);
2763}
2764
Ted Kremenekfb480492010-01-13 21:46:36 +00002765} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002766
Ted Kremenekfb480492010-01-13 21:46:36 +00002767//===----------------------------------------------------------------------===//
2768// CXCursor Operations.
2769//===----------------------------------------------------------------------===//
2770
Ted Kremenekfb480492010-01-13 21:46:36 +00002771static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002772 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002773 return getDeclFromExpr(CE->getSubExpr());
2774
Ted Kremenekfb480492010-01-13 21:46:36 +00002775 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2776 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002777 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2778 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002779 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2780 return ME->getMemberDecl();
2781 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2782 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002783 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002784 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002785 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2786 return getDeclFromExpr(POE->getSyntacticForm());
2787 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2788 if (Expr *Src = OVE->getSourceExpr())
2789 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002790
Ted Kremenekfb480492010-01-13 21:46:36 +00002791 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2792 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002793 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002794 if (!CE->isElidable())
2795 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002796 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2797 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002798
Douglas Gregordb1314e2010-10-01 21:11:22 +00002799 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2800 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002801 if (SubstNonTypeTemplateParmPackExpr *NTTP
2802 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2803 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002804 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2805 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2806 isa<ParmVarDecl>(SizeOfPack->getPack()))
2807 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002808
Ted Kremenekfb480492010-01-13 21:46:36 +00002809 return 0;
2810}
2811
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002812static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002813 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2814 return getLocationFromExpr(CE->getSubExpr());
2815
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002816 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2817 return /*FIXME:*/Msg->getLeftLoc();
2818 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2819 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002820 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2821 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002822 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2823 return Member->getMemberLoc();
2824 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2825 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002826 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2827 return SizeOfPack->getPackLoc();
2828
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002829 return E->getLocStart();
2830}
2831
Ted Kremenekfb480492010-01-13 21:46:36 +00002832extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002833
2834unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002835 CXCursorVisitor visitor,
2836 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002837 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2838 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002839 return CursorVis.VisitChildren(parent);
2840}
2841
David Chisnall3387c652010-11-03 14:12:26 +00002842#ifndef __has_feature
2843#define __has_feature(x) 0
2844#endif
2845#if __has_feature(blocks)
2846typedef enum CXChildVisitResult
2847 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2848
2849static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2850 CXClientData client_data) {
2851 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2852 return block(cursor, parent);
2853}
2854#else
2855// If we are compiled with a compiler that doesn't have native blocks support,
2856// define and call the block manually, so the
2857typedef struct _CXChildVisitResult
2858{
2859 void *isa;
2860 int flags;
2861 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002862 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2863 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002864} *CXCursorVisitorBlock;
2865
2866static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2867 CXClientData client_data) {
2868 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2869 return block->invoke(block, cursor, parent);
2870}
2871#endif
2872
2873
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002874unsigned clang_visitChildrenWithBlock(CXCursor parent,
2875 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002876 return clang_visitChildren(parent, visitWithBlock, block);
2877}
2878
Douglas Gregor78205d42010-01-20 21:45:58 +00002879static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00002880 if (!D)
2881 return createCXString("");
2882
2883 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002884 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002885 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002886 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2887 return createCXString(Property->getIdentifier()->getName());
2888
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002889 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002890 }
2891
Douglas Gregor78205d42010-01-20 21:45:58 +00002892 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002893 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002894
Douglas Gregor78205d42010-01-20 21:45:58 +00002895 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2896 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2897 // and returns different names. NamedDecl returns the class name and
2898 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002899 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002900
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002901 if (isa<UsingDirectiveDecl>(D))
2902 return createCXString("");
2903
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002904 llvm::SmallString<1024> S;
2905 llvm::raw_svector_ostream os(S);
2906 ND->printName(os);
2907
2908 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002909}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002910
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002911CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002912 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002913 return clang_getTranslationUnitSpelling(
2914 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002915
Steve Narofff334b4e2009-09-02 18:26:48 +00002916 if (clang_isReference(C.kind)) {
2917 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002918 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002919 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002920 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002921 }
2922 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002923 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002924 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002925 }
2926 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002927 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002928 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002929 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002930 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002931 case CXCursor_CXXBaseSpecifier: {
2932 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2933 return createCXString(B->getType().getAsString());
2934 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002935 case CXCursor_TypeRef: {
2936 TypeDecl *Type = getCursorTypeRef(C).first;
2937 assert(Type && "Missing type decl");
2938
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002939 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2940 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002941 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002942 case CXCursor_TemplateRef: {
2943 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002944 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002945
2946 return createCXString(Template->getNameAsString());
2947 }
Douglas Gregor69319002010-08-31 23:48:11 +00002948
2949 case CXCursor_NamespaceRef: {
2950 NamedDecl *NS = getCursorNamespaceRef(C).first;
2951 assert(NS && "Missing namespace decl");
2952
2953 return createCXString(NS->getNameAsString());
2954 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002955
Douglas Gregora67e03f2010-09-09 21:42:20 +00002956 case CXCursor_MemberRef: {
2957 FieldDecl *Field = getCursorMemberRef(C).first;
2958 assert(Field && "Missing member decl");
2959
2960 return createCXString(Field->getNameAsString());
2961 }
2962
Douglas Gregor36897b02010-09-10 00:22:18 +00002963 case CXCursor_LabelRef: {
2964 LabelStmt *Label = getCursorLabelRef(C).first;
2965 assert(Label && "Missing label");
2966
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002967 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002968 }
2969
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002970 case CXCursor_OverloadedDeclRef: {
2971 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2972 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2973 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2974 return createCXString(ND->getNameAsString());
2975 return createCXString("");
2976 }
2977 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2978 return createCXString(E->getName().getAsString());
2979 OverloadedTemplateStorage *Ovl
2980 = Storage.get<OverloadedTemplateStorage*>();
2981 if (Ovl->size() == 0)
2982 return createCXString("");
2983 return createCXString((*Ovl->begin())->getNameAsString());
2984 }
2985
Daniel Dunbaracca7252009-11-30 20:42:49 +00002986 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002987 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002988 }
2989 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002990
2991 if (clang_isExpression(C.kind)) {
2992 Decl *D = getDeclFromExpr(getCursorExpr(C));
2993 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002994 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002995 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002996 }
2997
Douglas Gregor36897b02010-09-10 00:22:18 +00002998 if (clang_isStatement(C.kind)) {
2999 Stmt *S = getCursorStmt(C);
3000 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003001 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003002
3003 return createCXString("");
3004 }
3005
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003006 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003007 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003008 ->getNameStart());
3009
Douglas Gregor572feb22010-03-18 18:04:21 +00003010 if (C.kind == CXCursor_MacroDefinition)
3011 return createCXString(getCursorMacroDefinition(C)->getName()
3012 ->getNameStart());
3013
Douglas Gregorecdcb882010-10-20 22:00:55 +00003014 if (C.kind == CXCursor_InclusionDirective)
3015 return createCXString(getCursorInclusionDirective(C)->getFileName());
3016
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003017 if (clang_isDeclaration(C.kind))
3018 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003019
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003020 if (C.kind == CXCursor_AnnotateAttr) {
3021 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3022 return createCXString(AA->getAnnotation());
3023 }
3024
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003025 if (C.kind == CXCursor_AsmLabelAttr) {
3026 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3027 return createCXString(AA->getLabel());
3028 }
3029
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003030 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003031}
3032
Douglas Gregor358559d2010-10-02 22:49:11 +00003033CXString clang_getCursorDisplayName(CXCursor C) {
3034 if (!clang_isDeclaration(C.kind))
3035 return clang_getCursorSpelling(C);
3036
3037 Decl *D = getCursorDecl(C);
3038 if (!D)
3039 return createCXString("");
3040
Douglas Gregor30c42402011-09-27 22:38:19 +00003041 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003042 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3043 D = FunTmpl->getTemplatedDecl();
3044
3045 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3046 llvm::SmallString<64> Str;
3047 llvm::raw_svector_ostream OS(Str);
3048 OS << Function->getNameAsString();
3049 if (Function->getPrimaryTemplate())
3050 OS << "<>";
3051 OS << "(";
3052 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3053 if (I)
3054 OS << ", ";
3055 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3056 }
3057
3058 if (Function->isVariadic()) {
3059 if (Function->getNumParams())
3060 OS << ", ";
3061 OS << "...";
3062 }
3063 OS << ")";
3064 return createCXString(OS.str());
3065 }
3066
3067 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3068 llvm::SmallString<64> Str;
3069 llvm::raw_svector_ostream OS(Str);
3070 OS << ClassTemplate->getNameAsString();
3071 OS << "<";
3072 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3073 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3074 if (I)
3075 OS << ", ";
3076
3077 NamedDecl *Param = Params->getParam(I);
3078 if (Param->getIdentifier()) {
3079 OS << Param->getIdentifier()->getName();
3080 continue;
3081 }
3082
3083 // There is no parameter name, which makes this tricky. Try to come up
3084 // with something useful that isn't too long.
3085 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3086 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3087 else if (NonTypeTemplateParmDecl *NTTP
3088 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3089 OS << NTTP->getType().getAsString(Policy);
3090 else
3091 OS << "template<...> class";
3092 }
3093
3094 OS << ">";
3095 return createCXString(OS.str());
3096 }
3097
3098 if (ClassTemplateSpecializationDecl *ClassSpec
3099 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3100 // If the type was explicitly written, use that.
3101 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3102 return createCXString(TSInfo->getType().getAsString(Policy));
3103
3104 llvm::SmallString<64> Str;
3105 llvm::raw_svector_ostream OS(Str);
3106 OS << ClassSpec->getNameAsString();
3107 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003108 ClassSpec->getTemplateArgs().data(),
3109 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003110 Policy);
3111 return createCXString(OS.str());
3112 }
3113
3114 return clang_getCursorSpelling(C);
3115}
3116
Ted Kremeneke68fff62010-02-17 00:41:32 +00003117CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003118 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003119 case CXCursor_FunctionDecl:
3120 return createCXString("FunctionDecl");
3121 case CXCursor_TypedefDecl:
3122 return createCXString("TypedefDecl");
3123 case CXCursor_EnumDecl:
3124 return createCXString("EnumDecl");
3125 case CXCursor_EnumConstantDecl:
3126 return createCXString("EnumConstantDecl");
3127 case CXCursor_StructDecl:
3128 return createCXString("StructDecl");
3129 case CXCursor_UnionDecl:
3130 return createCXString("UnionDecl");
3131 case CXCursor_ClassDecl:
3132 return createCXString("ClassDecl");
3133 case CXCursor_FieldDecl:
3134 return createCXString("FieldDecl");
3135 case CXCursor_VarDecl:
3136 return createCXString("VarDecl");
3137 case CXCursor_ParmDecl:
3138 return createCXString("ParmDecl");
3139 case CXCursor_ObjCInterfaceDecl:
3140 return createCXString("ObjCInterfaceDecl");
3141 case CXCursor_ObjCCategoryDecl:
3142 return createCXString("ObjCCategoryDecl");
3143 case CXCursor_ObjCProtocolDecl:
3144 return createCXString("ObjCProtocolDecl");
3145 case CXCursor_ObjCPropertyDecl:
3146 return createCXString("ObjCPropertyDecl");
3147 case CXCursor_ObjCIvarDecl:
3148 return createCXString("ObjCIvarDecl");
3149 case CXCursor_ObjCInstanceMethodDecl:
3150 return createCXString("ObjCInstanceMethodDecl");
3151 case CXCursor_ObjCClassMethodDecl:
3152 return createCXString("ObjCClassMethodDecl");
3153 case CXCursor_ObjCImplementationDecl:
3154 return createCXString("ObjCImplementationDecl");
3155 case CXCursor_ObjCCategoryImplDecl:
3156 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003157 case CXCursor_CXXMethod:
3158 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003159 case CXCursor_UnexposedDecl:
3160 return createCXString("UnexposedDecl");
3161 case CXCursor_ObjCSuperClassRef:
3162 return createCXString("ObjCSuperClassRef");
3163 case CXCursor_ObjCProtocolRef:
3164 return createCXString("ObjCProtocolRef");
3165 case CXCursor_ObjCClassRef:
3166 return createCXString("ObjCClassRef");
3167 case CXCursor_TypeRef:
3168 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003169 case CXCursor_TemplateRef:
3170 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003171 case CXCursor_NamespaceRef:
3172 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003173 case CXCursor_MemberRef:
3174 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003175 case CXCursor_LabelRef:
3176 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003177 case CXCursor_OverloadedDeclRef:
3178 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003179 case CXCursor_IntegerLiteral:
3180 return createCXString("IntegerLiteral");
3181 case CXCursor_FloatingLiteral:
3182 return createCXString("FloatingLiteral");
3183 case CXCursor_ImaginaryLiteral:
3184 return createCXString("ImaginaryLiteral");
3185 case CXCursor_StringLiteral:
3186 return createCXString("StringLiteral");
3187 case CXCursor_CharacterLiteral:
3188 return createCXString("CharacterLiteral");
3189 case CXCursor_ParenExpr:
3190 return createCXString("ParenExpr");
3191 case CXCursor_UnaryOperator:
3192 return createCXString("UnaryOperator");
3193 case CXCursor_ArraySubscriptExpr:
3194 return createCXString("ArraySubscriptExpr");
3195 case CXCursor_BinaryOperator:
3196 return createCXString("BinaryOperator");
3197 case CXCursor_CompoundAssignOperator:
3198 return createCXString("CompoundAssignOperator");
3199 case CXCursor_ConditionalOperator:
3200 return createCXString("ConditionalOperator");
3201 case CXCursor_CStyleCastExpr:
3202 return createCXString("CStyleCastExpr");
3203 case CXCursor_CompoundLiteralExpr:
3204 return createCXString("CompoundLiteralExpr");
3205 case CXCursor_InitListExpr:
3206 return createCXString("InitListExpr");
3207 case CXCursor_AddrLabelExpr:
3208 return createCXString("AddrLabelExpr");
3209 case CXCursor_StmtExpr:
3210 return createCXString("StmtExpr");
3211 case CXCursor_GenericSelectionExpr:
3212 return createCXString("GenericSelectionExpr");
3213 case CXCursor_GNUNullExpr:
3214 return createCXString("GNUNullExpr");
3215 case CXCursor_CXXStaticCastExpr:
3216 return createCXString("CXXStaticCastExpr");
3217 case CXCursor_CXXDynamicCastExpr:
3218 return createCXString("CXXDynamicCastExpr");
3219 case CXCursor_CXXReinterpretCastExpr:
3220 return createCXString("CXXReinterpretCastExpr");
3221 case CXCursor_CXXConstCastExpr:
3222 return createCXString("CXXConstCastExpr");
3223 case CXCursor_CXXFunctionalCastExpr:
3224 return createCXString("CXXFunctionalCastExpr");
3225 case CXCursor_CXXTypeidExpr:
3226 return createCXString("CXXTypeidExpr");
3227 case CXCursor_CXXBoolLiteralExpr:
3228 return createCXString("CXXBoolLiteralExpr");
3229 case CXCursor_CXXNullPtrLiteralExpr:
3230 return createCXString("CXXNullPtrLiteralExpr");
3231 case CXCursor_CXXThisExpr:
3232 return createCXString("CXXThisExpr");
3233 case CXCursor_CXXThrowExpr:
3234 return createCXString("CXXThrowExpr");
3235 case CXCursor_CXXNewExpr:
3236 return createCXString("CXXNewExpr");
3237 case CXCursor_CXXDeleteExpr:
3238 return createCXString("CXXDeleteExpr");
3239 case CXCursor_UnaryExpr:
3240 return createCXString("UnaryExpr");
3241 case CXCursor_ObjCStringLiteral:
3242 return createCXString("ObjCStringLiteral");
3243 case CXCursor_ObjCEncodeExpr:
3244 return createCXString("ObjCEncodeExpr");
3245 case CXCursor_ObjCSelectorExpr:
3246 return createCXString("ObjCSelectorExpr");
3247 case CXCursor_ObjCProtocolExpr:
3248 return createCXString("ObjCProtocolExpr");
3249 case CXCursor_ObjCBridgedCastExpr:
3250 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003251 case CXCursor_BlockExpr:
3252 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003253 case CXCursor_PackExpansionExpr:
3254 return createCXString("PackExpansionExpr");
3255 case CXCursor_SizeOfPackExpr:
3256 return createCXString("SizeOfPackExpr");
3257 case CXCursor_UnexposedExpr:
3258 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003259 case CXCursor_DeclRefExpr:
3260 return createCXString("DeclRefExpr");
3261 case CXCursor_MemberRefExpr:
3262 return createCXString("MemberRefExpr");
3263 case CXCursor_CallExpr:
3264 return createCXString("CallExpr");
3265 case CXCursor_ObjCMessageExpr:
3266 return createCXString("ObjCMessageExpr");
3267 case CXCursor_UnexposedStmt:
3268 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003269 case CXCursor_DeclStmt:
3270 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003271 case CXCursor_LabelStmt:
3272 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003273 case CXCursor_CompoundStmt:
3274 return createCXString("CompoundStmt");
3275 case CXCursor_CaseStmt:
3276 return createCXString("CaseStmt");
3277 case CXCursor_DefaultStmt:
3278 return createCXString("DefaultStmt");
3279 case CXCursor_IfStmt:
3280 return createCXString("IfStmt");
3281 case CXCursor_SwitchStmt:
3282 return createCXString("SwitchStmt");
3283 case CXCursor_WhileStmt:
3284 return createCXString("WhileStmt");
3285 case CXCursor_DoStmt:
3286 return createCXString("DoStmt");
3287 case CXCursor_ForStmt:
3288 return createCXString("ForStmt");
3289 case CXCursor_GotoStmt:
3290 return createCXString("GotoStmt");
3291 case CXCursor_IndirectGotoStmt:
3292 return createCXString("IndirectGotoStmt");
3293 case CXCursor_ContinueStmt:
3294 return createCXString("ContinueStmt");
3295 case CXCursor_BreakStmt:
3296 return createCXString("BreakStmt");
3297 case CXCursor_ReturnStmt:
3298 return createCXString("ReturnStmt");
3299 case CXCursor_AsmStmt:
3300 return createCXString("AsmStmt");
3301 case CXCursor_ObjCAtTryStmt:
3302 return createCXString("ObjCAtTryStmt");
3303 case CXCursor_ObjCAtCatchStmt:
3304 return createCXString("ObjCAtCatchStmt");
3305 case CXCursor_ObjCAtFinallyStmt:
3306 return createCXString("ObjCAtFinallyStmt");
3307 case CXCursor_ObjCAtThrowStmt:
3308 return createCXString("ObjCAtThrowStmt");
3309 case CXCursor_ObjCAtSynchronizedStmt:
3310 return createCXString("ObjCAtSynchronizedStmt");
3311 case CXCursor_ObjCAutoreleasePoolStmt:
3312 return createCXString("ObjCAutoreleasePoolStmt");
3313 case CXCursor_ObjCForCollectionStmt:
3314 return createCXString("ObjCForCollectionStmt");
3315 case CXCursor_CXXCatchStmt:
3316 return createCXString("CXXCatchStmt");
3317 case CXCursor_CXXTryStmt:
3318 return createCXString("CXXTryStmt");
3319 case CXCursor_CXXForRangeStmt:
3320 return createCXString("CXXForRangeStmt");
3321 case CXCursor_SEHTryStmt:
3322 return createCXString("SEHTryStmt");
3323 case CXCursor_SEHExceptStmt:
3324 return createCXString("SEHExceptStmt");
3325 case CXCursor_SEHFinallyStmt:
3326 return createCXString("SEHFinallyStmt");
3327 case CXCursor_NullStmt:
3328 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003329 case CXCursor_InvalidFile:
3330 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003331 case CXCursor_InvalidCode:
3332 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003333 case CXCursor_NoDeclFound:
3334 return createCXString("NoDeclFound");
3335 case CXCursor_NotImplemented:
3336 return createCXString("NotImplemented");
3337 case CXCursor_TranslationUnit:
3338 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003339 case CXCursor_UnexposedAttr:
3340 return createCXString("UnexposedAttr");
3341 case CXCursor_IBActionAttr:
3342 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003343 case CXCursor_IBOutletAttr:
3344 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003345 case CXCursor_IBOutletCollectionAttr:
3346 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003347 case CXCursor_CXXFinalAttr:
3348 return createCXString("attribute(final)");
3349 case CXCursor_CXXOverrideAttr:
3350 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003351 case CXCursor_AnnotateAttr:
3352 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003353 case CXCursor_AsmLabelAttr:
3354 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003355 case CXCursor_PreprocessingDirective:
3356 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003357 case CXCursor_MacroDefinition:
3358 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003359 case CXCursor_MacroExpansion:
3360 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003361 case CXCursor_InclusionDirective:
3362 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003363 case CXCursor_Namespace:
3364 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003365 case CXCursor_LinkageSpec:
3366 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003367 case CXCursor_CXXBaseSpecifier:
3368 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003369 case CXCursor_Constructor:
3370 return createCXString("CXXConstructor");
3371 case CXCursor_Destructor:
3372 return createCXString("CXXDestructor");
3373 case CXCursor_ConversionFunction:
3374 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003375 case CXCursor_TemplateTypeParameter:
3376 return createCXString("TemplateTypeParameter");
3377 case CXCursor_NonTypeTemplateParameter:
3378 return createCXString("NonTypeTemplateParameter");
3379 case CXCursor_TemplateTemplateParameter:
3380 return createCXString("TemplateTemplateParameter");
3381 case CXCursor_FunctionTemplate:
3382 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003383 case CXCursor_ClassTemplate:
3384 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003385 case CXCursor_ClassTemplatePartialSpecialization:
3386 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003387 case CXCursor_NamespaceAlias:
3388 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003389 case CXCursor_UsingDirective:
3390 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003391 case CXCursor_UsingDeclaration:
3392 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003393 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003394 return createCXString("TypeAliasDecl");
3395 case CXCursor_ObjCSynthesizeDecl:
3396 return createCXString("ObjCSynthesizeDecl");
3397 case CXCursor_ObjCDynamicDecl:
3398 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003399 case CXCursor_CXXAccessSpecifier:
3400 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003401 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003402
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003403 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003404 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003405}
Steve Naroff89922f82009-08-31 00:59:03 +00003406
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003407struct GetCursorData {
3408 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003409 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003410 CXCursor &BestCursor;
3411
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003412 GetCursorData(SourceManager &SM,
3413 SourceLocation tokenBegin, CXCursor &outputCursor)
3414 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3415 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3416 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003417};
3418
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003419static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3420 CXCursor parent,
3421 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003422 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3423 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003424
3425 // If we point inside a macro argument we should provide info of what the
3426 // token is so use the actual cursor, don't replace it with a macro expansion
3427 // cursor.
3428 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3429 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003430
3431 if (clang_isDeclaration(cursor.kind)) {
3432 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003433 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003434 if (MD->isImplicit())
3435 return CXChildVisit_Break;
3436 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003437
3438 if (clang_isExpression(cursor.kind) &&
3439 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003440 if (Decl *D = getCursorDecl(*BestCursor)) {
3441 // Avoid having the cursor of an expression replace the declaration cursor
3442 // when the expression source range overlaps the declaration range.
3443 // This can happen for C++ constructor expressions whose range generally
3444 // include the variable declaration, e.g.:
3445 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3446 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3447 D->getLocation() == Data->TokenBeginLoc)
3448 return CXChildVisit_Break;
3449 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003450 }
3451
Douglas Gregor93798e22010-11-05 21:11:19 +00003452 // If our current best cursor is the construction of a temporary object,
3453 // don't replace that cursor with a type reference, because we want
3454 // clang_getCursor() to point at the constructor.
3455 if (clang_isExpression(BestCursor->kind) &&
3456 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003457 cursor.kind == CXCursor_TypeRef) {
3458 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3459 // as having the actual point on the type reference.
3460 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003461 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003462 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003463
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003464 *BestCursor = cursor;
3465 return CXChildVisit_Recurse;
3466}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003467
Douglas Gregorb9790342010-01-22 21:44:22 +00003468CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3469 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003470 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003471
Ted Kremeneka60ed472010-11-16 08:15:36 +00003472 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003473 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3474
Ted Kremeneka297de22010-01-25 22:34:44 +00003475 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003476 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003477
Douglas Gregor40749ee2010-11-03 00:35:38 +00003478 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003479 if (Logging) {
3480 CXFile SearchFile;
3481 unsigned SearchLine, SearchColumn;
3482 CXFile ResultFile;
3483 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003484 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3485 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003486 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3487
Chandler Carruth20174222011-08-31 16:53:37 +00003488 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3489 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3490 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003491 SearchFileName = clang_getFileName(SearchFile);
3492 ResultFileName = clang_getFileName(ResultFile);
3493 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003494 USR = clang_getCursorUSR(Result);
3495 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003496 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3497 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003498 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3499 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003500 clang_disposeString(SearchFileName);
3501 clang_disposeString(ResultFileName);
3502 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003503 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003504
3505 CXCursor Definition = clang_getCursorDefinition(Result);
3506 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3507 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3508 CXString DefinitionKindSpelling
3509 = clang_getCursorKindSpelling(Definition.kind);
3510 CXFile DefinitionFile;
3511 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003512 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3513 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003514 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3515 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3516 clang_getCString(DefinitionKindSpelling),
3517 clang_getCString(DefinitionFileName),
3518 DefinitionLine, DefinitionColumn);
3519 clang_disposeString(DefinitionFileName);
3520 clang_disposeString(DefinitionKindSpelling);
3521 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003522 }
3523
Ted Kremeneke68fff62010-02-17 00:41:32 +00003524 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003525}
3526
Ted Kremenek73885552009-11-17 19:28:59 +00003527CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003528 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003529}
3530
3531unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003532 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003533}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003534
Douglas Gregor9ce55842010-11-20 00:09:34 +00003535unsigned clang_hashCursor(CXCursor C) {
3536 unsigned Index = 0;
3537 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3538 Index = 1;
3539
3540 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3541 std::make_pair(C.kind, C.data[Index]));
3542}
3543
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003544unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003545 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3546}
3547
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003548unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003549 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3550}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003551
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003552unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003553 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3554}
3555
Douglas Gregor97b98722010-01-19 23:20:36 +00003556unsigned clang_isExpression(enum CXCursorKind K) {
3557 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3558}
3559
3560unsigned clang_isStatement(enum CXCursorKind K) {
3561 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3562}
3563
Douglas Gregor8be80e12011-07-06 03:00:34 +00003564unsigned clang_isAttribute(enum CXCursorKind K) {
3565 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3566}
3567
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003568unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3569 return K == CXCursor_TranslationUnit;
3570}
3571
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003572unsigned clang_isPreprocessing(enum CXCursorKind K) {
3573 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3574}
3575
Ted Kremenekad6eff62010-03-08 21:17:29 +00003576unsigned clang_isUnexposed(enum CXCursorKind K) {
3577 switch (K) {
3578 case CXCursor_UnexposedDecl:
3579 case CXCursor_UnexposedExpr:
3580 case CXCursor_UnexposedStmt:
3581 case CXCursor_UnexposedAttr:
3582 return true;
3583 default:
3584 return false;
3585 }
3586}
3587
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003588CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003589 return C.kind;
3590}
3591
Douglas Gregor98258af2010-01-18 22:46:11 +00003592CXSourceLocation clang_getCursorLocation(CXCursor C) {
3593 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003594 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003595 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003596 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3597 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003598 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003599 }
3600
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003601 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003602 std::pair<ObjCProtocolDecl *, SourceLocation> P
3603 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003604 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003605 }
3606
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003607 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003608 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3609 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003610 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003611 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003612
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003613 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003614 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003615 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003616 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003617
3618 case CXCursor_TemplateRef: {
3619 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3620 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3621 }
3622
Douglas Gregor69319002010-08-31 23:48:11 +00003623 case CXCursor_NamespaceRef: {
3624 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3625 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3626 }
3627
Douglas Gregora67e03f2010-09-09 21:42:20 +00003628 case CXCursor_MemberRef: {
3629 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3630 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3631 }
3632
Ted Kremenek3064ef92010-08-27 21:34:58 +00003633 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003634 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3635 if (!BaseSpec)
3636 return clang_getNullLocation();
3637
3638 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3639 return cxloc::translateSourceLocation(getCursorContext(C),
3640 TSInfo->getTypeLoc().getBeginLoc());
3641
3642 return cxloc::translateSourceLocation(getCursorContext(C),
3643 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003644 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003645
Douglas Gregor36897b02010-09-10 00:22:18 +00003646 case CXCursor_LabelRef: {
3647 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3648 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3649 }
3650
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003651 case CXCursor_OverloadedDeclRef:
3652 return cxloc::translateSourceLocation(getCursorContext(C),
3653 getCursorOverloadedDeclRef(C).second);
3654
Douglas Gregorf46034a2010-01-18 23:41:10 +00003655 default:
3656 // FIXME: Need a way to enumerate all non-reference cases.
3657 llvm_unreachable("Missed a reference kind");
3658 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003659 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003660
3661 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003662 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003663 getLocationFromExpr(getCursorExpr(C)));
3664
Douglas Gregor36897b02010-09-10 00:22:18 +00003665 if (clang_isStatement(C.kind))
3666 return cxloc::translateSourceLocation(getCursorContext(C),
3667 getCursorStmt(C)->getLocStart());
3668
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003669 if (C.kind == CXCursor_PreprocessingDirective) {
3670 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3671 return cxloc::translateSourceLocation(getCursorContext(C), L);
3672 }
Douglas Gregor48072312010-03-18 15:23:44 +00003673
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003674 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003675 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003676 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003677 return cxloc::translateSourceLocation(getCursorContext(C), L);
3678 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003679
3680 if (C.kind == CXCursor_MacroDefinition) {
3681 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3682 return cxloc::translateSourceLocation(getCursorContext(C), L);
3683 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003684
3685 if (C.kind == CXCursor_InclusionDirective) {
3686 SourceLocation L
3687 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3688 return cxloc::translateSourceLocation(getCursorContext(C), L);
3689 }
3690
Ted Kremenek9a700d22010-05-12 06:16:13 +00003691 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003692 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003693
Douglas Gregorf46034a2010-01-18 23:41:10 +00003694 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003695 if (!D)
3696 return clang_getNullLocation();
3697
Douglas Gregorf46034a2010-01-18 23:41:10 +00003698 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003699 // FIXME: Multiple variables declared in a single declaration
3700 // currently lack the information needed to correctly determine their
3701 // ranges when accounting for the type-specifier. We use context
3702 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3703 // and if so, whether it is the first decl.
3704 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3705 if (!cxcursor::isFirstInDeclGroup(C))
3706 Loc = VD->getLocation();
3707 }
3708
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003709 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003710}
Douglas Gregora7bde202010-01-19 00:34:46 +00003711
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003712} // end extern "C"
3713
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003714CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3715 assert(TU);
3716
3717 // Guard against an invalid SourceLocation, or we may assert in one
3718 // of the following calls.
3719 if (SLoc.isInvalid())
3720 return clang_getNullCursor();
3721
3722 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3723
3724 // Translate the given source location to make it point at the beginning of
3725 // the token under the cursor.
3726 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3727 CXXUnit->getASTContext().getLangOptions());
3728
3729 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3730 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003731 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003732 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3733 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003734 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003735 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003736 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003737 }
3738
3739 return Result;
3740}
3741
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003742static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003743 if (clang_isReference(C.kind)) {
3744 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003745 case CXCursor_ObjCSuperClassRef:
3746 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003747
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003748 case CXCursor_ObjCProtocolRef:
3749 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003750
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003751 case CXCursor_ObjCClassRef:
3752 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003753
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003754 case CXCursor_TypeRef:
3755 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003756
3757 case CXCursor_TemplateRef:
3758 return getCursorTemplateRef(C).second;
3759
Douglas Gregor69319002010-08-31 23:48:11 +00003760 case CXCursor_NamespaceRef:
3761 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003762
3763 case CXCursor_MemberRef:
3764 return getCursorMemberRef(C).second;
3765
Ted Kremenek3064ef92010-08-27 21:34:58 +00003766 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003767 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003768
Douglas Gregor36897b02010-09-10 00:22:18 +00003769 case CXCursor_LabelRef:
3770 return getCursorLabelRef(C).second;
3771
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003772 case CXCursor_OverloadedDeclRef:
3773 return getCursorOverloadedDeclRef(C).second;
3774
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003775 default:
3776 // FIXME: Need a way to enumerate all non-reference cases.
3777 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003778 }
3779 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003780
3781 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003782 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003783
3784 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003785 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003786
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003787 if (clang_isAttribute(C.kind))
3788 return getCursorAttr(C)->getRange();
3789
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003790 if (C.kind == CXCursor_PreprocessingDirective)
3791 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003792
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003793 if (C.kind == CXCursor_MacroExpansion) {
3794 ASTUnit *TU = getCursorASTUnit(C);
3795 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3796 return TU->mapRangeFromPreamble(Range);
3797 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003798
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003799 if (C.kind == CXCursor_MacroDefinition) {
3800 ASTUnit *TU = getCursorASTUnit(C);
3801 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3802 return TU->mapRangeFromPreamble(Range);
3803 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003804
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003805 if (C.kind == CXCursor_InclusionDirective) {
3806 ASTUnit *TU = getCursorASTUnit(C);
3807 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3808 return TU->mapRangeFromPreamble(Range);
3809 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003810
Ted Kremenek007a7c92010-11-01 23:26:51 +00003811 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3812 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003813 if (!D)
3814 return SourceRange();
3815
Ted Kremenek007a7c92010-11-01 23:26:51 +00003816 SourceRange R = D->getSourceRange();
3817 // FIXME: Multiple variables declared in a single declaration
3818 // currently lack the information needed to correctly determine their
3819 // ranges when accounting for the type-specifier. We use context
3820 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3821 // and if so, whether it is the first decl.
3822 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3823 if (!cxcursor::isFirstInDeclGroup(C))
3824 R.setBegin(VD->getLocation());
3825 }
3826 return R;
3827 }
Douglas Gregor66537982010-11-17 17:14:07 +00003828 return SourceRange();
3829}
3830
3831/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3832/// the decl-specifier-seq for declarations.
3833static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3834 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3835 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003836 if (!D)
3837 return SourceRange();
3838
Douglas Gregor66537982010-11-17 17:14:07 +00003839 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003840
Douglas Gregor2494dd02011-03-01 01:34:45 +00003841 // Adjust the start of the location for declarations preceded by
3842 // declaration specifiers.
3843 SourceLocation StartLoc;
3844 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3845 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3846 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3847 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3848 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3849 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3850 }
3851
3852 if (StartLoc.isValid() && R.getBegin().isValid() &&
3853 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3854 R.setBegin(StartLoc);
3855
3856 // FIXME: Multiple variables declared in a single declaration
3857 // currently lack the information needed to correctly determine their
3858 // ranges when accounting for the type-specifier. We use context
3859 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3860 // and if so, whether it is the first decl.
3861 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3862 if (!cxcursor::isFirstInDeclGroup(C))
3863 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003864 }
3865
3866 return R;
3867 }
3868
3869 return getRawCursorExtent(C);
3870}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003871
3872extern "C" {
3873
3874CXSourceRange clang_getCursorExtent(CXCursor C) {
3875 SourceRange R = getRawCursorExtent(C);
3876 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003877 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003878
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003879 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003880}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003881
3882CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003883 if (clang_isInvalid(C.kind))
3884 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003885
Ted Kremeneka60ed472010-11-16 08:15:36 +00003886 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003887 if (clang_isDeclaration(C.kind)) {
3888 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003889 if (!D)
3890 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003891 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003892 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003893 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003894 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003895 if (ObjCForwardProtocolDecl *Protocols
3896 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003897 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003898 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003899 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3900 return MakeCXCursor(Property, tu);
3901
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003902 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003903 }
3904
Douglas Gregor97b98722010-01-19 23:20:36 +00003905 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003906 Expr *E = getCursorExpr(C);
3907 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003908 if (D) {
3909 CXCursor declCursor = MakeCXCursor(D, tu);
3910 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3911 declCursor);
3912 return declCursor;
3913 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003914
3915 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003916 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003917
Douglas Gregor97b98722010-01-19 23:20:36 +00003918 return clang_getNullCursor();
3919 }
3920
Douglas Gregor36897b02010-09-10 00:22:18 +00003921 if (clang_isStatement(C.kind)) {
3922 Stmt *S = getCursorStmt(C);
3923 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003924 if (LabelDecl *label = Goto->getLabel())
3925 if (LabelStmt *labelS = label->getStmt())
3926 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003927
3928 return clang_getNullCursor();
3929 }
3930
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003931 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003932 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003933 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003934 }
3935
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003936 if (!clang_isReference(C.kind))
3937 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003938
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003939 switch (C.kind) {
3940 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003941 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003942
3943 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003944 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003945
Douglas Gregor7723fec2011-12-15 20:29:51 +00003946 case CXCursor_ObjCClassRef: {
3947 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3948 if (ObjCInterfaceDecl *Def = Class->getDefinition())
3949 return MakeCXCursor(Def, tu);
3950
3951 return MakeCXCursor(Class, tu);
3952 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003953
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003954 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003955 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003956
3957 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003958 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003959
Douglas Gregor69319002010-08-31 23:48:11 +00003960 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003961 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003962
Douglas Gregora67e03f2010-09-09 21:42:20 +00003963 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003964 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003965
Ted Kremenek3064ef92010-08-27 21:34:58 +00003966 case CXCursor_CXXBaseSpecifier: {
3967 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3968 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003969 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003970 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003971
Douglas Gregor36897b02010-09-10 00:22:18 +00003972 case CXCursor_LabelRef:
3973 // FIXME: We end up faking the "parent" declaration here because we
3974 // don't want to make CXCursor larger.
3975 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003976 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3977 .getTranslationUnitDecl(),
3978 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003979
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003980 case CXCursor_OverloadedDeclRef:
3981 return C;
3982
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003983 default:
3984 // We would prefer to enumerate all non-reference cursor kinds here.
3985 llvm_unreachable("Unhandled reference cursor kind");
3986 break;
3987 }
3988 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003989
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003990 return clang_getNullCursor();
3991}
3992
Douglas Gregorb6998662010-01-19 19:34:47 +00003993CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003994 if (clang_isInvalid(C.kind))
3995 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003996
Ted Kremeneka60ed472010-11-16 08:15:36 +00003997 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003998
Douglas Gregorb6998662010-01-19 19:34:47 +00003999 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004000 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004001 C = clang_getCursorReferenced(C);
4002 WasReference = true;
4003 }
4004
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004005 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004006 return clang_getCursorReferenced(C);
4007
Douglas Gregorb6998662010-01-19 19:34:47 +00004008 if (!clang_isDeclaration(C.kind))
4009 return clang_getNullCursor();
4010
4011 Decl *D = getCursorDecl(C);
4012 if (!D)
4013 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004014
Douglas Gregorb6998662010-01-19 19:34:47 +00004015 switch (D->getKind()) {
4016 // Declaration kinds that don't really separate the notions of
4017 // declaration and definition.
4018 case Decl::Namespace:
4019 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004020 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004021 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004022 case Decl::TemplateTypeParm:
4023 case Decl::EnumConstant:
4024 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004025 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004026 case Decl::ObjCIvar:
4027 case Decl::ObjCAtDefsField:
4028 case Decl::ImplicitParam:
4029 case Decl::ParmVar:
4030 case Decl::NonTypeTemplateParm:
4031 case Decl::TemplateTemplateParm:
4032 case Decl::ObjCCategoryImpl:
4033 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004034 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004035 case Decl::LinkageSpec:
4036 case Decl::ObjCPropertyImpl:
4037 case Decl::FileScopeAsm:
4038 case Decl::StaticAssert:
4039 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004040 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004041 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004042 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004043 return C;
4044
4045 // Declaration kinds that don't make any sense here, but are
4046 // nonetheless harmless.
4047 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004048 break;
4049
4050 // Declaration kinds for which the definition is not resolvable.
4051 case Decl::UnresolvedUsingTypename:
4052 case Decl::UnresolvedUsingValue:
4053 break;
4054
4055 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004056 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004057 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004058
4059 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004060 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004061
4062 case Decl::Enum:
4063 case Decl::Record:
4064 case Decl::CXXRecord:
4065 case Decl::ClassTemplateSpecialization:
4066 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004067 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004068 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004069 return clang_getNullCursor();
4070
4071 case Decl::Function:
4072 case Decl::CXXMethod:
4073 case Decl::CXXConstructor:
4074 case Decl::CXXDestructor:
4075 case Decl::CXXConversion: {
4076 const FunctionDecl *Def = 0;
4077 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004078 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004079 return clang_getNullCursor();
4080 }
4081
4082 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004083 // Ask the variable if it has a definition.
4084 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004085 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004086 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004087 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004088
Douglas Gregorb6998662010-01-19 19:34:47 +00004089 case Decl::FunctionTemplate: {
4090 const FunctionDecl *Def = 0;
4091 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004092 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004093 return clang_getNullCursor();
4094 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004095
Douglas Gregorb6998662010-01-19 19:34:47 +00004096 case Decl::ClassTemplate: {
4097 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004098 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004099 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004100 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004101 return clang_getNullCursor();
4102 }
4103
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004104 case Decl::Using:
4105 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004106 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004107
4108 case Decl::UsingShadow:
4109 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004110 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004111 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004112
4113 case Decl::ObjCMethod: {
4114 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4115 if (Method->isThisDeclarationADefinition())
4116 return C;
4117
4118 // Dig out the method definition in the associated
4119 // @implementation, if we have it.
4120 // FIXME: The ASTs should make finding the definition easier.
4121 if (ObjCInterfaceDecl *Class
4122 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4123 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4124 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4125 Method->isInstanceMethod()))
4126 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004127 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004128
4129 return clang_getNullCursor();
4130 }
4131
4132 case Decl::ObjCCategory:
4133 if (ObjCCategoryImplDecl *Impl
4134 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004135 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004136 return clang_getNullCursor();
4137
4138 case Decl::ObjCProtocol:
4139 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4140 return C;
4141 return clang_getNullCursor();
4142
4143 case Decl::ObjCInterface:
4144 // There are two notions of a "definition" for an Objective-C
4145 // class: the interface and its implementation. When we resolved a
4146 // reference to an Objective-C class, produce the @interface as
4147 // the definition; when we were provided with the interface,
4148 // produce the @implementation as the definition.
4149 if (WasReference) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00004150 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(D)->getDefinition())
4151 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004152 } else if (ObjCImplementationDecl *Impl
4153 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004154 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004155 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004156
Douglas Gregorb6998662010-01-19 19:34:47 +00004157 case Decl::ObjCProperty:
4158 // FIXME: We don't really know where to find the
4159 // ObjCPropertyImplDecls that implement this property.
4160 return clang_getNullCursor();
4161
4162 case Decl::ObjCCompatibleAlias:
4163 if (ObjCInterfaceDecl *Class
4164 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004165 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4166 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004167
Douglas Gregorb6998662010-01-19 19:34:47 +00004168 return clang_getNullCursor();
4169
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004170 case Decl::ObjCForwardProtocol:
4171 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004172 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004173
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004174 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004175 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004176 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004177
4178 case Decl::Friend:
4179 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004180 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004181 return clang_getNullCursor();
4182
4183 case Decl::FriendTemplate:
4184 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004185 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004186 return clang_getNullCursor();
4187 }
4188
4189 return clang_getNullCursor();
4190}
4191
4192unsigned clang_isCursorDefinition(CXCursor C) {
4193 if (!clang_isDeclaration(C.kind))
4194 return 0;
4195
4196 return clang_getCursorDefinition(C) == C;
4197}
4198
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004199CXCursor clang_getCanonicalCursor(CXCursor C) {
4200 if (!clang_isDeclaration(C.kind))
4201 return C;
4202
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004203 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004204 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4205 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4206 return MakeCXCursor(CatD, getCursorTU(C));
4207
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004208 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4209 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4210 return MakeCXCursor(IFD, getCursorTU(C));
4211
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004212 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004213 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004214
4215 return C;
4216}
4217
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004218unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004219 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004220 return 0;
4221
4222 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4223 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4224 return E->getNumDecls();
4225
4226 if (OverloadedTemplateStorage *S
4227 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4228 return S->size();
4229
4230 Decl *D = Storage.get<Decl*>();
4231 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004232 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004233 if (isa<ObjCClassDecl>(D))
4234 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004235 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4236 return Protocols->protocol_size();
4237
4238 return 0;
4239}
4240
4241CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004242 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004243 return clang_getNullCursor();
4244
4245 if (index >= clang_getNumOverloadedDecls(cursor))
4246 return clang_getNullCursor();
4247
Ted Kremeneka60ed472010-11-16 08:15:36 +00004248 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004249 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4250 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004251 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004252
4253 if (OverloadedTemplateStorage *S
4254 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004255 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004256
4257 Decl *D = Storage.get<Decl*>();
4258 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4259 // FIXME: This is, unfortunately, linear time.
4260 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4261 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004262 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004263 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004264 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004265 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004266 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004267 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004268
4269 return clang_getNullCursor();
4270}
4271
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004272void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004273 const char **startBuf,
4274 const char **endBuf,
4275 unsigned *startLine,
4276 unsigned *startColumn,
4277 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004278 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004279 assert(getCursorDecl(C) && "CXCursor has null decl");
4280 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004281 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4282 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004283
Steve Naroff4ade6d62009-09-23 17:52:52 +00004284 SourceManager &SM = FD->getASTContext().getSourceManager();
4285 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4286 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4287 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4288 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4289 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4290 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4291}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004292
Douglas Gregor430d7a12011-07-25 17:48:11 +00004293
4294CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4295 unsigned PieceIndex) {
4296 RefNamePieces Pieces;
4297
4298 switch (C.kind) {
4299 case CXCursor_MemberRefExpr:
4300 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4301 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4302 E->getQualifierLoc().getSourceRange());
4303 break;
4304
4305 case CXCursor_DeclRefExpr:
4306 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4307 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4308 E->getQualifierLoc().getSourceRange(),
4309 E->getExplicitTemplateArgsOpt());
4310 break;
4311
4312 case CXCursor_CallExpr:
4313 if (CXXOperatorCallExpr *OCE =
4314 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4315 Expr *Callee = OCE->getCallee();
4316 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4317 Callee = ICE->getSubExpr();
4318
4319 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4320 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4321 DRE->getQualifierLoc().getSourceRange());
4322 }
4323 break;
4324
4325 default:
4326 break;
4327 }
4328
4329 if (Pieces.empty()) {
4330 if (PieceIndex == 0)
4331 return clang_getCursorExtent(C);
4332 } else if (PieceIndex < Pieces.size()) {
4333 SourceRange R = Pieces[PieceIndex];
4334 if (R.isValid())
4335 return cxloc::translateSourceRange(getCursorContext(C), R);
4336 }
4337
4338 return clang_getNullRange();
4339}
4340
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004341void clang_enableStackTraces(void) {
4342 llvm::sys::PrintStackTraceOnErrorSignal();
4343}
4344
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004345void clang_executeOnThread(void (*fn)(void*), void *user_data,
4346 unsigned stack_size) {
4347 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4348}
4349
Ted Kremenekfb480492010-01-13 21:46:36 +00004350} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004351
Ted Kremenekfb480492010-01-13 21:46:36 +00004352//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004353// Token-based Operations.
4354//===----------------------------------------------------------------------===//
4355
4356/* CXToken layout:
4357 * int_data[0]: a CXTokenKind
4358 * int_data[1]: starting token location
4359 * int_data[2]: token length
4360 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004361 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004362 * otherwise unused.
4363 */
4364extern "C" {
4365
4366CXTokenKind clang_getTokenKind(CXToken CXTok) {
4367 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4368}
4369
4370CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4371 switch (clang_getTokenKind(CXTok)) {
4372 case CXToken_Identifier:
4373 case CXToken_Keyword:
4374 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004375 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4376 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004377
4378 case CXToken_Literal: {
4379 // We have stashed the starting pointer in the ptr_data field. Use it.
4380 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004381 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004382 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004383
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004384 case CXToken_Punctuation:
4385 case CXToken_Comment:
4386 break;
4387 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004388
4389 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004390 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004391 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004392 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004393 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004394
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004395 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4396 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004397 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004398 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004399 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004400 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4401 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004402 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004403
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004404 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004405}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004406
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004407CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004408 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004409 if (!CXXUnit)
4410 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004411
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004412 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4413 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4414}
4415
4416CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004417 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004418 if (!CXXUnit)
4419 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004420
4421 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004422 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4423}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004424
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004425static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4426 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004427 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4428 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004429 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004430 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004431 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004432
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004433 // Cannot tokenize across files.
4434 if (BeginLocInfo.first != EndLocInfo.first)
4435 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004436
4437 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004438 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004439 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004440 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004441 if (Invalid)
4442 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004443
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004444 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4445 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004446 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004447 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004448
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004449 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004450 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004451 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004452 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004453 do {
4454 // Lex the next token
4455 Lex.LexFromRawLexer(Tok);
4456 if (Tok.is(tok::eof))
4457 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004458
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004459 // Initialize the CXToken.
4460 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004461
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004462 // - Common fields
4463 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4464 CXTok.int_data[2] = Tok.getLength();
4465 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004466
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004467 // - Kind-specific fields
4468 if (Tok.isLiteral()) {
4469 CXTok.int_data[0] = CXToken_Literal;
4470 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004471 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004472 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004473 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004474 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004475
David Chisnall096428b2010-10-13 21:44:48 +00004476 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004477 CXTok.int_data[0] = CXToken_Keyword;
4478 }
4479 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004480 CXTok.int_data[0] = Tok.is(tok::identifier)
4481 ? CXToken_Identifier
4482 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004483 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004484 CXTok.ptr_data = II;
4485 } else if (Tok.is(tok::comment)) {
4486 CXTok.int_data[0] = CXToken_Comment;
4487 CXTok.ptr_data = 0;
4488 } else {
4489 CXTok.int_data[0] = CXToken_Punctuation;
4490 CXTok.ptr_data = 0;
4491 }
4492 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004493 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004494 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004495}
4496
4497void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4498 CXToken **Tokens, unsigned *NumTokens) {
4499 if (Tokens)
4500 *Tokens = 0;
4501 if (NumTokens)
4502 *NumTokens = 0;
4503
4504 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4505 if (!CXXUnit || !Tokens || !NumTokens)
4506 return;
4507
4508 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4509
4510 SourceRange R = cxloc::translateCXSourceRange(Range);
4511 if (R.isInvalid())
4512 return;
4513
4514 SmallVector<CXToken, 32> CXTokens;
4515 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004516
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004517 if (CXTokens.empty())
4518 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004519
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004520 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4521 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4522 *NumTokens = CXTokens.size();
4523}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004524
Ted Kremenek6db61092010-05-05 00:55:15 +00004525void clang_disposeTokens(CXTranslationUnit TU,
4526 CXToken *Tokens, unsigned NumTokens) {
4527 free(Tokens);
4528}
4529
4530} // end: extern "C"
4531
4532//===----------------------------------------------------------------------===//
4533// Token annotation APIs.
4534//===----------------------------------------------------------------------===//
4535
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004536typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004537static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4538 CXCursor parent,
4539 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004540namespace {
4541class AnnotateTokensWorker {
4542 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004543 CXToken *Tokens;
4544 CXCursor *Cursors;
4545 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004546 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004547 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004548 CursorVisitor AnnotateVis;
4549 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004550 bool HasContextSensitiveKeywords;
4551
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004552 bool MoreTokens() const { return TokIdx < NumTokens; }
4553 unsigned NextToken() const { return TokIdx; }
4554 void AdvanceToken() { ++TokIdx; }
4555 SourceLocation GetTokenLoc(unsigned tokI) {
4556 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4557 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004558 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004559 return Tokens[tokI].int_data[3] != 0;
4560 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004561 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004562 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4563 }
4564
4565 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004566 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4567 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004568
Ted Kremenek6db61092010-05-05 00:55:15 +00004569public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004570 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004571 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004572 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004573 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004574 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004575 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004576 AnnotateTokensVisitor, this,
4577 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004578 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004579 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004580 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4581 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004582
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004583 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004584 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004585 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004586
4587 /// \brief Determine whether the annotator saw any cursors that have
4588 /// context-sensitive keywords.
4589 bool hasContextSensitiveKeywords() const {
4590 return HasContextSensitiveKeywords;
4591 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004592};
4593}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004594
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004595void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004596 // Walk the AST within the region of interest, annotating tokens
4597 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004598 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004599
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004600 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4601 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004602 if (Pos != Annotated.end() &&
4603 (clang_isInvalid(Cursors[I].kind) ||
4604 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004605 Cursors[I] = Pos->second;
4606 }
4607
4608 // Finish up annotating any tokens left.
4609 if (!MoreTokens())
4610 return;
4611
4612 const CXCursor &C = clang_getNullCursor();
4613 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004614 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4615 continue;
4616
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004617 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4618 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004619 }
4620}
4621
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004622/// \brief It annotates and advances tokens with a cursor until the comparison
4623//// between the cursor location and the source range is the same as
4624/// \arg compResult.
4625///
4626/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4627/// Pass RangeOverlap to annotate tokens inside a range.
4628void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4629 RangeComparisonResult compResult,
4630 SourceRange range) {
4631 while (MoreTokens()) {
4632 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004633 if (isFunctionMacroToken(I))
4634 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004635
4636 SourceLocation TokLoc = GetTokenLoc(I);
4637 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4638 Cursors[I] = updateC;
4639 AdvanceToken();
4640 continue;
4641 }
4642 break;
4643 }
4644}
4645
4646/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004647void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4648 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004649 RangeComparisonResult compResult,
4650 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004651 assert(MoreTokens());
4652 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004653 "Should be called only for macro arg tokens");
4654
4655 // This works differently than annotateAndAdvanceTokens; because expanded
4656 // macro arguments can have arbitrary translation-unit source order, we do not
4657 // advance the token index one by one until a token fails the range test.
4658 // We only advance once past all of the macro arg tokens if all of them
4659 // pass the range test. If one of them fails we keep the token index pointing
4660 // at the start of the macro arg tokens so that the failing token will be
4661 // annotated by a subsequent annotation try.
4662
4663 bool atLeastOneCompFail = false;
4664
4665 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004666 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4667 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004668 if (TokLoc.isFileID())
4669 continue; // not macro arg token, it's parens or comma.
4670 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4671 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4672 Cursors[I] = updateC;
4673 } else
4674 atLeastOneCompFail = true;
4675 }
4676
4677 if (!atLeastOneCompFail)
4678 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4679}
4680
Ted Kremenek6db61092010-05-05 00:55:15 +00004681enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004682AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004683 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004684 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004685 if (cursorRange.isInvalid())
4686 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004687
4688 if (!HasContextSensitiveKeywords) {
4689 // Objective-C properties can have context-sensitive keywords.
4690 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4691 if (ObjCPropertyDecl *Property
4692 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4693 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4694 }
4695 // Objective-C methods can have context-sensitive keywords.
4696 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4697 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4698 if (ObjCMethodDecl *Method
4699 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4700 if (Method->getObjCDeclQualifier())
4701 HasContextSensitiveKeywords = true;
4702 else {
4703 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4704 PEnd = Method->param_end();
4705 P != PEnd; ++P) {
4706 if ((*P)->getObjCDeclQualifier()) {
4707 HasContextSensitiveKeywords = true;
4708 break;
4709 }
4710 }
4711 }
4712 }
4713 }
4714 // C++ methods can have context-sensitive keywords.
4715 else if (cursor.kind == CXCursor_CXXMethod) {
4716 if (CXXMethodDecl *Method
4717 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4718 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4719 HasContextSensitiveKeywords = true;
4720 }
4721 }
4722 // C++ classes can have context-sensitive keywords.
4723 else if (cursor.kind == CXCursor_StructDecl ||
4724 cursor.kind == CXCursor_ClassDecl ||
4725 cursor.kind == CXCursor_ClassTemplate ||
4726 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4727 if (Decl *D = getCursorDecl(cursor))
4728 if (D->hasAttr<FinalAttr>())
4729 HasContextSensitiveKeywords = true;
4730 }
4731 }
4732
Douglas Gregor4419b672010-10-21 06:10:04 +00004733 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004734 // For macro expansions, just note where the beginning of the macro
4735 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004736 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004737 Annotated[Loc.int_data] = cursor;
4738 return CXChildVisit_Recurse;
4739 }
4740
Douglas Gregor4419b672010-10-21 06:10:04 +00004741 // Items in the preprocessing record are kept separate from items in
4742 // declarations, so we keep a separate token index.
4743 unsigned SavedTokIdx = TokIdx;
4744 TokIdx = PreprocessingTokIdx;
4745
4746 // Skip tokens up until we catch up to the beginning of the preprocessing
4747 // entry.
4748 while (MoreTokens()) {
4749 const unsigned I = NextToken();
4750 SourceLocation TokLoc = GetTokenLoc(I);
4751 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4752 case RangeBefore:
4753 AdvanceToken();
4754 continue;
4755 case RangeAfter:
4756 case RangeOverlap:
4757 break;
4758 }
4759 break;
4760 }
4761
4762 // Look at all of the tokens within this range.
4763 while (MoreTokens()) {
4764 const unsigned I = NextToken();
4765 SourceLocation TokLoc = GetTokenLoc(I);
4766 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4767 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004768 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004769 case RangeAfter:
4770 break;
4771 case RangeOverlap:
4772 Cursors[I] = cursor;
4773 AdvanceToken();
4774 continue;
4775 }
4776 break;
4777 }
4778
4779 // Save the preprocessing token index; restore the non-preprocessing
4780 // token index.
4781 PreprocessingTokIdx = TokIdx;
4782 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004783 return CXChildVisit_Recurse;
4784 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004785
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004786 if (cursorRange.isInvalid())
4787 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004788
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004789 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4790
Ted Kremeneka333c662010-05-12 05:29:33 +00004791 // Adjust the annotated range based specific declarations.
4792 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4793 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004794 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004795
4796 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004797 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004798 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4799 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004800 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004801 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4802 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004803 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004804
4805 if (StartLoc.isValid() && L.isValid() &&
4806 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4807 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004808 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004809
Ted Kremenek3f404602010-08-14 01:14:06 +00004810 // If the location of the cursor occurs within a macro instantiation, record
4811 // the spelling location of the cursor in our annotation map. We can then
4812 // paper over the token labelings during a post-processing step to try and
4813 // get cursor mappings for tokens that are the *arguments* of a macro
4814 // instantiation.
4815 if (L.isMacroID()) {
4816 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4817 // Only invalidate the old annotation if it isn't part of a preprocessing
4818 // directive. Here we assume that the default construction of CXCursor
4819 // results in CXCursor.kind being an initialized value (i.e., 0). If
4820 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004821
Ted Kremenek3f404602010-08-14 01:14:06 +00004822 CXCursor &oldC = Annotated[rawEncoding];
4823 if (!clang_isPreprocessing(oldC.kind))
4824 oldC = cursor;
4825 }
4826
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004827 const enum CXCursorKind K = clang_getCursorKind(parent);
4828 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004829 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4830 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004831
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004832 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004833
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004834 // Avoid having the cursor of an expression "overwrite" the annotation of the
4835 // variable declaration that it belongs to.
4836 // This can happen for C++ constructor expressions whose range generally
4837 // include the variable declaration, e.g.:
4838 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4839 if (clang_isExpression(cursorK)) {
4840 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004841 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004842 const unsigned I = NextToken();
4843 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4844 E->getLocStart() == D->getLocation() &&
4845 E->getLocStart() == GetTokenLoc(I)) {
4846 Cursors[I] = updateC;
4847 AdvanceToken();
4848 }
4849 }
4850 }
4851
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004852 // Visit children to get their cursor information.
4853 const unsigned BeforeChildren = NextToken();
4854 VisitChildren(cursor);
4855 const unsigned AfterChildren = NextToken();
4856
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004857 // Scan the tokens that are at the end of the cursor, but are not captured
4858 // but the child cursors.
4859 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004860
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004861 // Scan the tokens that are at the beginning of the cursor, but are not
4862 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004863 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4864 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4865 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004866
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004867 Cursors[I] = cursor;
4868 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004869
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004870 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004871}
4872
Ted Kremenek6db61092010-05-05 00:55:15 +00004873static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4874 CXCursor parent,
4875 CXClientData client_data) {
4876 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4877}
4878
Ted Kremenek6628a612011-03-18 22:51:30 +00004879namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004880
4881/// \brief Uses the macro expansions in the preprocessing record to find
4882/// and mark tokens that are macro arguments. This info is used by the
4883/// AnnotateTokensWorker.
4884class MarkMacroArgTokensVisitor {
4885 SourceManager &SM;
4886 CXToken *Tokens;
4887 unsigned NumTokens;
4888 unsigned CurIdx;
4889
4890public:
4891 MarkMacroArgTokensVisitor(SourceManager &SM,
4892 CXToken *tokens, unsigned numTokens)
4893 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4894
4895 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4896 if (cursor.kind != CXCursor_MacroExpansion)
4897 return CXChildVisit_Continue;
4898
4899 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4900 if (macroRange.getBegin() == macroRange.getEnd())
4901 return CXChildVisit_Continue; // it's not a function macro.
4902
4903 for (; CurIdx < NumTokens; ++CurIdx) {
4904 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4905 macroRange.getBegin()))
4906 break;
4907 }
4908
4909 if (CurIdx == NumTokens)
4910 return CXChildVisit_Break;
4911
4912 for (; CurIdx < NumTokens; ++CurIdx) {
4913 SourceLocation tokLoc = getTokenLoc(CurIdx);
4914 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4915 break;
4916
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004917 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004918 }
4919
4920 if (CurIdx == NumTokens)
4921 return CXChildVisit_Break;
4922
4923 return CXChildVisit_Continue;
4924 }
4925
4926private:
4927 SourceLocation getTokenLoc(unsigned tokI) {
4928 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4929 }
4930
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004931 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004932 // The third field is reserved and currently not used. Use it here
4933 // to mark macro arg expanded tokens with their expanded locations.
4934 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4935 }
4936};
4937
4938} // end anonymous namespace
4939
4940static CXChildVisitResult
4941MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4942 CXClientData client_data) {
4943 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4944 parent);
4945}
4946
4947namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004948 struct clang_annotateTokens_Data {
4949 CXTranslationUnit TU;
4950 ASTUnit *CXXUnit;
4951 CXToken *Tokens;
4952 unsigned NumTokens;
4953 CXCursor *Cursors;
4954 };
4955}
4956
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004957static void annotatePreprocessorTokens(CXTranslationUnit TU,
4958 SourceRange RegionOfInterest,
4959 AnnotateTokensData &Annotated) {
4960 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4961
4962 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4963 std::pair<FileID, unsigned> BeginLocInfo
4964 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4965 std::pair<FileID, unsigned> EndLocInfo
4966 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4967
4968 if (BeginLocInfo.first != EndLocInfo.first)
4969 return;
4970
4971 StringRef Buffer;
4972 bool Invalid = false;
4973 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4974 if (Buffer.empty() || Invalid)
4975 return;
4976
4977 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4978 CXXUnit->getASTContext().getLangOptions(),
4979 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4980 Buffer.end());
4981 Lex.SetCommentRetentionState(true);
4982
4983 // Lex tokens in raw mode until we hit the end of the range, to avoid
4984 // entering #includes or expanding macros.
4985 while (true) {
4986 Token Tok;
4987 Lex.LexFromRawLexer(Tok);
4988
4989 reprocess:
4990 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4991 // We have found a preprocessing directive. Gobble it up so that we
4992 // don't see it while preprocessing these tokens later, but keep track
4993 // of all of the token locations inside this preprocessing directive so
4994 // that we can annotate them appropriately.
4995 //
4996 // FIXME: Some simple tests here could identify macro definitions and
4997 // #undefs, to provide specific cursor kinds for those.
4998 SmallVector<SourceLocation, 32> Locations;
4999 do {
5000 Locations.push_back(Tok.getLocation());
5001 Lex.LexFromRawLexer(Tok);
5002 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5003
5004 using namespace cxcursor;
5005 CXCursor Cursor
5006 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5007 Locations.back()),
5008 TU);
5009 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5010 Annotated[Locations[I].getRawEncoding()] = Cursor;
5011 }
5012
5013 if (Tok.isAtStartOfLine())
5014 goto reprocess;
5015
5016 continue;
5017 }
5018
5019 if (Tok.is(tok::eof))
5020 break;
5021 }
5022}
5023
Ted Kremenekab979612010-11-11 08:05:23 +00005024// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005025static void clang_annotateTokensImpl(void *UserData) {
5026 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5027 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5028 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5029 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5030 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5031
5032 // Determine the region of interest, which contains all of the tokens.
5033 SourceRange RegionOfInterest;
5034 RegionOfInterest.setBegin(
5035 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5036 RegionOfInterest.setEnd(
5037 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5038 Tokens[NumTokens-1])));
5039
5040 // A mapping from the source locations found when re-lexing or traversing the
5041 // region of interest to the corresponding cursors.
5042 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005043
Ted Kremenek6628a612011-03-18 22:51:30 +00005044 // Relex the tokens within the source range to look for preprocessing
5045 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005046 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005047
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005048 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5049 // Search and mark tokens that are macro argument expansions.
5050 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5051 Tokens, NumTokens);
5052 CursorVisitor MacroArgMarker(TU,
5053 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005054 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005055 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005056 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005057 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5058 }
5059
Ted Kremenek6628a612011-03-18 22:51:30 +00005060 // Annotate all of the source locations in the region of interest that map to
5061 // a specific cursor.
5062 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5063 TU, RegionOfInterest);
5064
5065 // FIXME: We use a ridiculous stack size here because the data-recursion
5066 // algorithm uses a large stack frame than the non-data recursive version,
5067 // and AnnotationTokensWorker currently transforms the data-recursion
5068 // algorithm back into a traditional recursion by explicitly calling
5069 // VisitChildren(). We will need to remove this explicit recursive call.
5070 W.AnnotateTokens();
5071
5072 // If we ran into any entities that involve context-sensitive keywords,
5073 // take another pass through the tokens to mark them as such.
5074 if (W.hasContextSensitiveKeywords()) {
5075 for (unsigned I = 0; I != NumTokens; ++I) {
5076 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5077 continue;
5078
5079 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5080 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5081 if (ObjCPropertyDecl *Property
5082 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5083 if (Property->getPropertyAttributesAsWritten() != 0 &&
5084 llvm::StringSwitch<bool>(II->getName())
5085 .Case("readonly", true)
5086 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005087 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005088 .Case("readwrite", true)
5089 .Case("retain", true)
5090 .Case("copy", true)
5091 .Case("nonatomic", true)
5092 .Case("atomic", true)
5093 .Case("getter", true)
5094 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005095 .Case("strong", true)
5096 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005097 .Default(false))
5098 Tokens[I].int_data[0] = CXToken_Keyword;
5099 }
5100 continue;
5101 }
5102
5103 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5104 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5105 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5106 if (llvm::StringSwitch<bool>(II->getName())
5107 .Case("in", true)
5108 .Case("out", true)
5109 .Case("inout", true)
5110 .Case("oneway", true)
5111 .Case("bycopy", true)
5112 .Case("byref", true)
5113 .Default(false))
5114 Tokens[I].int_data[0] = CXToken_Keyword;
5115 continue;
5116 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005117
5118 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5119 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5120 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005121 continue;
5122 }
5123 }
5124 }
Ted Kremenekab979612010-11-11 08:05:23 +00005125}
5126
Ted Kremenek6db61092010-05-05 00:55:15 +00005127extern "C" {
5128
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005129void clang_annotateTokens(CXTranslationUnit TU,
5130 CXToken *Tokens, unsigned NumTokens,
5131 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005132
5133 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005134 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005135
Douglas Gregor4419b672010-10-21 06:10:04 +00005136 // Any token we don't specifically annotate will have a NULL cursor.
5137 CXCursor C = clang_getNullCursor();
5138 for (unsigned I = 0; I != NumTokens; ++I)
5139 Cursors[I] = C;
5140
Ted Kremeneka60ed472010-11-16 08:15:36 +00005141 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005142 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005143 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005144
Douglas Gregorbdf60622010-03-05 21:16:25 +00005145 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005146
5147 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005148 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005149 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005150 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005151 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5152 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005153}
Ted Kremenek6628a612011-03-18 22:51:30 +00005154
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005155} // end: extern "C"
5156
5157//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005158// Operations for querying linkage of a cursor.
5159//===----------------------------------------------------------------------===//
5160
5161extern "C" {
5162CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005163 if (!clang_isDeclaration(cursor.kind))
5164 return CXLinkage_Invalid;
5165
Ted Kremenek16b42592010-03-03 06:36:57 +00005166 Decl *D = cxcursor::getCursorDecl(cursor);
5167 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5168 switch (ND->getLinkage()) {
5169 case NoLinkage: return CXLinkage_NoLinkage;
5170 case InternalLinkage: return CXLinkage_Internal;
5171 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5172 case ExternalLinkage: return CXLinkage_External;
5173 };
5174
5175 return CXLinkage_Invalid;
5176}
5177} // end: extern "C"
5178
5179//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005180// Operations for querying language of a cursor.
5181//===----------------------------------------------------------------------===//
5182
5183static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005184 if (!D)
5185 return CXLanguage_C;
5186
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005187 switch (D->getKind()) {
5188 default:
5189 break;
5190 case Decl::ImplicitParam:
5191 case Decl::ObjCAtDefsField:
5192 case Decl::ObjCCategory:
5193 case Decl::ObjCCategoryImpl:
5194 case Decl::ObjCClass:
5195 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005196 case Decl::ObjCForwardProtocol:
5197 case Decl::ObjCImplementation:
5198 case Decl::ObjCInterface:
5199 case Decl::ObjCIvar:
5200 case Decl::ObjCMethod:
5201 case Decl::ObjCProperty:
5202 case Decl::ObjCPropertyImpl:
5203 case Decl::ObjCProtocol:
5204 return CXLanguage_ObjC;
5205 case Decl::CXXConstructor:
5206 case Decl::CXXConversion:
5207 case Decl::CXXDestructor:
5208 case Decl::CXXMethod:
5209 case Decl::CXXRecord:
5210 case Decl::ClassTemplate:
5211 case Decl::ClassTemplatePartialSpecialization:
5212 case Decl::ClassTemplateSpecialization:
5213 case Decl::Friend:
5214 case Decl::FriendTemplate:
5215 case Decl::FunctionTemplate:
5216 case Decl::LinkageSpec:
5217 case Decl::Namespace:
5218 case Decl::NamespaceAlias:
5219 case Decl::NonTypeTemplateParm:
5220 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005221 case Decl::TemplateTemplateParm:
5222 case Decl::TemplateTypeParm:
5223 case Decl::UnresolvedUsingTypename:
5224 case Decl::UnresolvedUsingValue:
5225 case Decl::Using:
5226 case Decl::UsingDirective:
5227 case Decl::UsingShadow:
5228 return CXLanguage_CPlusPlus;
5229 }
5230
5231 return CXLanguage_C;
5232}
5233
5234extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005235
5236enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5237 if (clang_isDeclaration(cursor.kind))
5238 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005239 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005240 return CXAvailability_Available;
5241
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005242 switch (D->getAvailability()) {
5243 case AR_Available:
5244 case AR_NotYetIntroduced:
5245 return CXAvailability_Available;
5246
5247 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005248 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005249
5250 case AR_Unavailable:
5251 return CXAvailability_NotAvailable;
5252 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005253 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005254
Douglas Gregor58ddb602010-08-23 23:00:57 +00005255 return CXAvailability_Available;
5256}
5257
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005258CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5259 if (clang_isDeclaration(cursor.kind))
5260 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5261
5262 return CXLanguage_Invalid;
5263}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005264
5265 /// \brief If the given cursor is the "templated" declaration
5266 /// descibing a class or function template, return the class or
5267 /// function template.
5268static Decl *maybeGetTemplateCursor(Decl *D) {
5269 if (!D)
5270 return 0;
5271
5272 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5273 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5274 return FunTmpl;
5275
5276 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5277 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5278 return ClassTmpl;
5279
5280 return D;
5281}
5282
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005283CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5284 if (clang_isDeclaration(cursor.kind)) {
5285 if (Decl *D = getCursorDecl(cursor)) {
5286 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005287 if (!DC)
5288 return clang_getNullCursor();
5289
5290 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5291 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005292 }
5293 }
5294
5295 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5296 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005297 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005298 }
5299
5300 return clang_getNullCursor();
5301}
5302
5303CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5304 if (clang_isDeclaration(cursor.kind)) {
5305 if (Decl *D = getCursorDecl(cursor)) {
5306 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005307 if (!DC)
5308 return clang_getNullCursor();
5309
5310 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5311 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005312 }
5313 }
5314
5315 // FIXME: Note that we can't easily compute the lexical context of a
5316 // statement or expression, so we return nothing.
5317 return clang_getNullCursor();
5318}
5319
Douglas Gregor9f592342010-10-01 20:25:15 +00005320void clang_getOverriddenCursors(CXCursor cursor,
5321 CXCursor **overridden,
5322 unsigned *num_overridden) {
5323 if (overridden)
5324 *overridden = 0;
5325 if (num_overridden)
5326 *num_overridden = 0;
5327 if (!overridden || !num_overridden)
5328 return;
5329
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005330 SmallVector<CXCursor, 8> Overridden;
5331 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005332
Ted Kremenek24077122011-11-14 23:51:37 +00005333 // Don't allocate memory if we have no overriden cursors.
5334 if (Overridden.size() == 0)
5335 return;
5336
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005337 *num_overridden = Overridden.size();
5338 *overridden = new CXCursor [Overridden.size()];
5339 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005340}
5341
5342void clang_disposeOverriddenCursors(CXCursor *overridden) {
5343 delete [] overridden;
5344}
5345
Douglas Gregorecdcb882010-10-20 22:00:55 +00005346CXFile clang_getIncludedFile(CXCursor cursor) {
5347 if (cursor.kind != CXCursor_InclusionDirective)
5348 return 0;
5349
5350 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5351 return (void *)ID->getFile();
5352}
5353
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005354} // end: extern "C"
5355
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005356
5357//===----------------------------------------------------------------------===//
5358// C++ AST instrospection.
5359//===----------------------------------------------------------------------===//
5360
5361extern "C" {
5362unsigned clang_CXXMethod_isStatic(CXCursor C) {
5363 if (!clang_isDeclaration(C.kind))
5364 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005365
5366 CXXMethodDecl *Method = 0;
5367 Decl *D = cxcursor::getCursorDecl(C);
5368 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5369 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5370 else
5371 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5372 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005373}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005374
Douglas Gregor211924b2011-05-12 15:17:24 +00005375unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5376 if (!clang_isDeclaration(C.kind))
5377 return 0;
5378
5379 CXXMethodDecl *Method = 0;
5380 Decl *D = cxcursor::getCursorDecl(C);
5381 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5382 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5383 else
5384 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5385 return (Method && Method->isVirtual()) ? 1 : 0;
5386}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005387} // end: extern "C"
5388
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005389//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005390// Attribute introspection.
5391//===----------------------------------------------------------------------===//
5392
5393extern "C" {
5394CXType clang_getIBOutletCollectionType(CXCursor C) {
5395 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005396 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005397
5398 IBOutletCollectionAttr *A =
5399 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5400
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005401 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005402}
5403} // end: extern "C"
5404
5405//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005406// Inspecting memory usage.
5407//===----------------------------------------------------------------------===//
5408
Ted Kremenekf7870022011-04-20 16:41:07 +00005409typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005410
Ted Kremenekf7870022011-04-20 16:41:07 +00005411static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5412 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005413 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005414 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005415 entries.push_back(entry);
5416}
5417
5418extern "C" {
5419
Ted Kremenekf7870022011-04-20 16:41:07 +00005420const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005421 const char *str = "";
5422 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005423 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005424 str = "ASTContext: expressions, declarations, and types";
5425 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005426 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005427 str = "ASTContext: identifiers";
5428 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005429 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005430 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005431 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005432 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005433 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005434 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005435 case CXTUResourceUsage_SourceManagerContentCache:
5436 str = "SourceManager: content cache allocator";
5437 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005438 case CXTUResourceUsage_AST_SideTables:
5439 str = "ASTContext: side tables";
5440 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005441 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5442 str = "SourceManager: malloc'ed memory buffers";
5443 break;
5444 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5445 str = "SourceManager: mmap'ed memory buffers";
5446 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005447 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5448 str = "ExternalASTSource: malloc'ed memory buffers";
5449 break;
5450 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5451 str = "ExternalASTSource: mmap'ed memory buffers";
5452 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005453 case CXTUResourceUsage_Preprocessor:
5454 str = "Preprocessor: malloc'ed memory";
5455 break;
5456 case CXTUResourceUsage_PreprocessingRecord:
5457 str = "Preprocessor: PreprocessingRecord";
5458 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005459 case CXTUResourceUsage_SourceManager_DataStructures:
5460 str = "SourceManager: data structures and tables";
5461 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005462 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5463 str = "Preprocessor: header search tables";
5464 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005465 }
5466 return str;
5467}
5468
Ted Kremenekf7870022011-04-20 16:41:07 +00005469CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005470 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005471 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005472 return usage;
5473 }
5474
5475 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5476 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5477 ASTContext &astContext = astUnit->getASTContext();
5478
5479 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005480 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005481 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005482
5483 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005484 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005485 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5486
5487 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005488 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005489 (unsigned long) astContext.Selectors.getTotalMemory());
5490
Ted Kremenekba29bd22011-04-28 04:53:38 +00005491 // How much memory is used by ASTContext's side tables?
5492 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5493 (unsigned long) astContext.getSideTableAllocatedMemory());
5494
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005495 // How much memory is used for caching global code completion results?
5496 unsigned long completionBytes = 0;
5497 if (GlobalCodeCompletionAllocator *completionAllocator =
5498 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005499 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005500 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005501 createCXTUResourceUsageEntry(*entries,
5502 CXTUResourceUsage_GlobalCompletionResults,
5503 completionBytes);
5504
5505 // How much memory is being used by SourceManager's content cache?
5506 createCXTUResourceUsageEntry(*entries,
5507 CXTUResourceUsage_SourceManagerContentCache,
5508 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005509
5510 // How much memory is being used by the MemoryBuffer's in SourceManager?
5511 const SourceManager::MemoryBufferSizes &srcBufs =
5512 astUnit->getSourceManager().getMemoryBufferSizes();
5513
5514 createCXTUResourceUsageEntry(*entries,
5515 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5516 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005517 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005518 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5519 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005520 createCXTUResourceUsageEntry(*entries,
5521 CXTUResourceUsage_SourceManager_DataStructures,
5522 (unsigned long) astContext.getSourceManager()
5523 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005524
5525 // How much memory is being used by the ExternalASTSource?
5526 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5527 const ExternalASTSource::MemoryBufferSizes &sizes =
5528 esrc->getMemoryBufferSizes();
5529
5530 createCXTUResourceUsageEntry(*entries,
5531 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5532 (unsigned long) sizes.malloc_bytes);
5533 createCXTUResourceUsageEntry(*entries,
5534 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5535 (unsigned long) sizes.mmap_bytes);
5536 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005537
5538 // How much memory is being used by the Preprocessor?
5539 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005540 createCXTUResourceUsageEntry(*entries,
5541 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005542 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005543
5544 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5545 createCXTUResourceUsageEntry(*entries,
5546 CXTUResourceUsage_PreprocessingRecord,
5547 pRec->getTotalMemory());
5548 }
5549
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005550 createCXTUResourceUsageEntry(*entries,
5551 CXTUResourceUsage_Preprocessor_HeaderSearch,
5552 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005553
Ted Kremenekf7870022011-04-20 16:41:07 +00005554 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005555 (unsigned) entries->size(),
5556 entries->size() ? &(*entries)[0] : 0 };
5557 entries.take();
5558 return usage;
5559}
5560
Ted Kremenekf7870022011-04-20 16:41:07 +00005561void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005562 if (usage.data)
5563 delete (MemUsageEntries*) usage.data;
5564}
5565
5566} // end extern "C"
5567
Douglas Gregor6df78732011-05-05 20:27:22 +00005568void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5569 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5570 for (unsigned I = 0; I != Usage.numEntries; ++I)
5571 fprintf(stderr, " %s: %lu\n",
5572 clang_getTUResourceUsageName(Usage.entries[I].kind),
5573 Usage.entries[I].amount);
5574
5575 clang_disposeCXTUResourceUsage(Usage);
5576}
5577
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005578//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005579// Misc. utility functions.
5580//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005581
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005582/// Default to using an 8 MB stack size on "safety" threads.
5583static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005584
5585namespace clang {
5586
5587bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005588 void (*Fn)(void*), void *UserData,
5589 unsigned Size) {
5590 if (!Size)
5591 Size = GetSafetyThreadStackSize();
5592 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005593 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5594 return CRC.RunSafely(Fn, UserData);
5595}
5596
5597unsigned GetSafetyThreadStackSize() {
5598 return SafetyStackThreadSize;
5599}
5600
5601void SetSafetyThreadStackSize(unsigned Value) {
5602 SafetyStackThreadSize = Value;
5603}
5604
5605}
5606
Ted Kremenek04bb7162010-01-22 22:44:15 +00005607extern "C" {
5608
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005609CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005610 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005611}
5612
5613} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005614