blob: fe4e373e8ac5b9d8335240aedad94ede0f20e7ed [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
David Blaikie7530c032012-01-17 06:56:22 +0000184 llvm_unreachable("Invalid CXChildVisitResult!");
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.
Argyrios Kyrtzidisacca4112011-12-21 16:56:38 +0000196 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
197 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000198 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 Kyrtzidise2079cf2011-11-16 08:58:54 +0000300 if (TagDecl *TD = dyn_cast<TagDecl>(D))
301 if (!TD->isFreeStanding())
302 continue;
303
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000304 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
305 if (CompRes == RangeBefore)
306 continue;
307 if (CompRes == RangeAfter)
308 break;
309
310 assert(CompRes == RangeOverlap);
311 VisitedAtLeastOnce = true;
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000312
313 if (isa<ObjCContainerDecl>(D)) {
314 FileDI_current = &DIt;
315 FileDE_current = DE;
316 } else {
317 FileDI_current = 0;
318 }
319
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000320 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000321 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000322 }
323
324 if (VisitedAtLeastOnce)
325 return;
326
327 // No Decls overlapped with the range. Move up the lexical context until there
328 // is a context that contains the range or we reach the translation unit
329 // level.
330 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
331 : (*(DIt-1))->getLexicalDeclContext();
332
333 while (DC && !DC->isTranslationUnit()) {
334 Decl *D = cast<Decl>(DC);
335 SourceRange CurDeclRange = D->getSourceRange();
336 if (CurDeclRange.isInvalid())
337 break;
338
339 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000340 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000341 break;
342 }
343
344 DC = D->getLexicalDeclContext();
345 }
346}
347
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000348bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Argyrios Kyrtzidisb49e7282011-11-29 03:14:11 +0000349 if (!AU->getPreprocessor().getPreprocessingRecord())
350 return false;
351
Douglas Gregor788f5a12010-03-20 00:41:21 +0000352 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000353 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000354 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000355
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000356 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000357 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000358 SourceLocation B = MappedRange.getBegin();
359 SourceLocation E = MappedRange.getEnd();
360
361 if (AU->isInPreambleFileID(B)) {
362 if (SM.isLoadedSourceLocation(E))
363 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
364 PPRec, *this);
365
366 // Beginning of range lies in the preamble but it also extends beyond
367 // it into the main file. Split the range into 2 parts, one covering
368 // the preamble and another covering the main file. This allows subsequent
369 // calls to visitPreprocessedEntitiesInRange to accept a source range that
370 // lies in the same FileID, allowing it to skip preprocessed entities that
371 // do not come from the same FileID.
372 bool breaked =
373 visitPreprocessedEntitiesInRange(
374 SourceRange(B, AU->getEndOfPreambleFileID()),
375 PPRec, *this);
376 if (breaked) return true;
377 return visitPreprocessedEntitiesInRange(
378 SourceRange(AU->getStartOfMainFileID(), E),
379 PPRec, *this);
380 }
381
382 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000383 }
384
Douglas Gregor788f5a12010-03-20 00:41:21 +0000385 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000386 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
387
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000388 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000389 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
390 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000391
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000392 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000393}
394
395template<typename InputIterator>
396bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000397 InputIterator Last,
398 PreprocessingRecord &PPRec,
399 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000400 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000401 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
402 continue;
403
404 PreprocessedEntity *PPE = *First;
405 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000406 if (Visit(MakeMacroExpansionCursor(ME, TU)))
407 return true;
408
409 continue;
410 }
411
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000412 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000413 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
414 return true;
415
416 continue;
417 }
418
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000419 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000420 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
421 return true;
422
423 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000424 }
425 }
426
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000427 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000428}
429
Douglas Gregorb1373d02010-01-20 20:59:29 +0000430/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000431///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432/// \returns true if the visitation should be aborted, false if it
433/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000434bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000435 if (clang_isReference(Cursor.kind) &&
436 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000437 // By definition, references have no children.
438 return false;
439 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000440
441 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000443 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000444
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 if (clang_isDeclaration(Cursor.kind)) {
446 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000447 if (!D)
448 return false;
449
Ted Kremenek539311e2010-02-18 18:47:01 +0000450 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000452
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000453 if (clang_isStatement(Cursor.kind)) {
454 if (Stmt *S = getCursorStmt(Cursor))
455 return Visit(S);
456
457 return false;
458 }
459
460 if (clang_isExpression(Cursor.kind)) {
461 if (Expr *E = getCursorExpr(Cursor))
462 return Visit(E);
463
464 return false;
465 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000468 CXTranslationUnit tu = getCursorTU(Cursor);
469 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000470
471 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
472 for (unsigned I = 0; I != 2; ++I) {
473 if (VisitOrder[I]) {
474 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
475 RegionOfInterest.isInvalid()) {
476 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
477 TLEnd = CXXUnit->top_level_end();
478 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000479 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000480 return true;
481 }
482 } else if (VisitDeclContext(
483 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000484 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000485 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000486 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000487
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000488 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000489 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
490 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000492
Douglas Gregor7b691f332010-01-20 21:13:59 +0000493 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495
Douglas Gregorc314aa42011-03-02 19:17:03 +0000496 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
497 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
498 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
499 return Visit(BaseTSInfo->getTypeLoc());
500 }
501 }
502 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000503
504 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
505 IBOutletCollectionAttr *A =
506 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
507 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
508 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
509 A->getInterfaceLoc(), TU));
510 }
511
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 return false;
514}
515
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000516bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000517 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
518 if (Visit(TSInfo->getTypeLoc()))
519 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000520
Ted Kremenek664cffd2010-07-22 11:30:19 +0000521 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000522 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000523
524 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000525}
526
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000527llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
528 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000529 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000530 if (Range.isInvalid())
531 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000532
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000533 switch (CompareRegionOfInterest(Range)) {
534 case RangeBefore:
535 // This declaration comes before the region of interest; skip it.
536 return llvm::Optional<bool>();
537
538 case RangeAfter:
539 // This declaration comes after the region of interest; we're done.
540 return false;
541
542 case RangeOverlap:
543 // This declaration overlaps the region of interest; visit it.
544 break;
545 }
546 }
547 return true;
548}
549
550bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
551 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
552
553 // FIXME: Eventually remove. This part of a hack to support proper
554 // iteration over all Decls contained lexically within an ObjC container.
555 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
556 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
557
558 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000559 Decl *D = *I;
560 if (D->getLexicalDeclContext() != DC)
561 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000562 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000563 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
564 if (!V.hasValue())
565 continue;
566 if (!V.getValue())
567 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000568 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000569 return true;
570 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000572}
573
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000574bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
575 llvm_unreachable("Translation units are visited directly by Visit()");
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000576}
577
Richard Smith162e1c12011-04-15 14:24:37 +0000578bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
579 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
580 return Visit(TSInfo->getTypeLoc());
581
582 return false;
583}
584
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000585bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
586 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
587 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000588
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000589 return false;
590}
591
592bool CursorVisitor::VisitTagDecl(TagDecl *D) {
593 return VisitDeclContext(D);
594}
595
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000596bool CursorVisitor::VisitClassTemplateSpecializationDecl(
597 ClassTemplateSpecializationDecl *D) {
598 bool ShouldVisitBody = false;
599 switch (D->getSpecializationKind()) {
600 case TSK_Undeclared:
601 case TSK_ImplicitInstantiation:
602 // Nothing to visit
603 return false;
604
605 case TSK_ExplicitInstantiationDeclaration:
606 case TSK_ExplicitInstantiationDefinition:
607 break;
608
609 case TSK_ExplicitSpecialization:
610 ShouldVisitBody = true;
611 break;
612 }
613
614 // Visit the template arguments used in the specialization.
615 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
616 TypeLoc TL = SpecType->getTypeLoc();
617 if (TemplateSpecializationTypeLoc *TSTLoc
618 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
619 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
620 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
621 return true;
622 }
623 }
624
625 if (ShouldVisitBody && VisitCXXRecordDecl(D))
626 return true;
627
628 return false;
629}
630
Douglas Gregor74dbe642010-08-31 19:31:58 +0000631bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
632 ClassTemplatePartialSpecializationDecl *D) {
633 // FIXME: Visit the "outer" template parameter lists on the TagDecl
634 // before visiting these template parameters.
635 if (VisitTemplateParameters(D->getTemplateParameters()))
636 return true;
637
638 // Visit the partial specialization arguments.
639 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
640 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
641 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
642 return true;
643
644 return VisitCXXRecordDecl(D);
645}
646
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000647bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000648 // Visit the default argument.
649 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
650 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
651 if (Visit(DefArg->getTypeLoc()))
652 return true;
653
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000654 return false;
655}
656
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000657bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
658 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000659 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000660 return false;
661}
662
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000663bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
664 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
665 if (Visit(TSInfo->getTypeLoc()))
666 return true;
667
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000668 // Visit the nested-name-specifier, if present.
669 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
670 if (VisitNestedNameSpecifierLoc(QualifierLoc))
671 return true;
672
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000673 return false;
674}
675
Douglas Gregora67e03f2010-09-09 21:42:20 +0000676/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000677static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
678 CXXCtorInitializer const * const *X
679 = static_cast<CXXCtorInitializer const * const *>(Xp);
680 CXXCtorInitializer const * const *Y
681 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000682
683 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
684 return -1;
685 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
686 return 1;
687 else
688 return 0;
689}
690
Douglas Gregorb1373d02010-01-20 20:59:29 +0000691bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000692 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
693 // Visit the function declaration's syntactic components in the order
694 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000695 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000696 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
697
698 // If we have a function declared directly (without the use of a typedef),
699 // visit just the return type. Otherwise, just visit the function's type
700 // now.
701 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
702 (!FTL && Visit(TL)))
703 return true;
704
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000705 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000706 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
707 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000708 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000709
710 // Visit the declaration name.
711 if (VisitDeclarationNameInfo(ND->getNameInfo()))
712 return true;
713
714 // FIXME: Visit explicitly-specified template arguments!
715
716 // Visit the function parameters, if we have a function type.
717 if (FTL && VisitFunctionTypeLoc(*FTL, true))
718 return true;
719
720 // FIXME: Attributes?
721 }
722
Sean Hunt10620eb2011-05-06 20:44:56 +0000723 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000724 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
725 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000726 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000727 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
728 IEnd = Constructor->init_end();
729 I != IEnd; ++I) {
730 if (!(*I)->isWritten())
731 continue;
732
733 WrittenInits.push_back(*I);
734 }
735
736 // Sort the initializers in source order
737 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000738 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000739
740 // Visit the initializers in source order
741 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000742 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000743 if (Init->isAnyMemberInitializer()) {
744 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000745 Init->getMemberLocation(), TU)))
746 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000747 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
748 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000749 return true;
750 }
751
752 // Visit the initializer value.
753 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000754 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000755 return true;
756 }
757 }
758
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000759 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000760 return true;
761 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000762
Douglas Gregorb1373d02010-01-20 20:59:29 +0000763 return false;
764}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000765
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000766bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
767 if (VisitDeclaratorDecl(D))
768 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000771 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000772
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000773 return false;
774}
775
776bool CursorVisitor::VisitVarDecl(VarDecl *D) {
777 if (VisitDeclaratorDecl(D))
778 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000781 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000783 return false;
784}
785
Douglas Gregor84b51d72010-09-01 20:16:53 +0000786bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
787 if (VisitDeclaratorDecl(D))
788 return true;
789
790 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
791 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000792 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000793
794 return false;
795}
796
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000797bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
798 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
799 // before visiting these template parameters.
800 if (VisitTemplateParameters(D->getTemplateParameters()))
801 return true;
802
803 return VisitFunctionDecl(D->getTemplatedDecl());
804}
805
Douglas Gregor39d6f072010-08-31 19:02:00 +0000806bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
807 // FIXME: Visit the "outer" template parameter lists on the TagDecl
808 // before visiting these template parameters.
809 if (VisitTemplateParameters(D->getTemplateParameters()))
810 return true;
811
812 return VisitCXXRecordDecl(D->getTemplatedDecl());
813}
814
Douglas Gregor84b51d72010-09-01 20:16:53 +0000815bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
816 if (VisitTemplateParameters(D->getTemplateParameters()))
817 return true;
818
819 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
820 VisitTemplateArgumentLoc(D->getDefaultArgument()))
821 return true;
822
823 return false;
824}
825
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000826bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000827 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
828 if (Visit(TSInfo->getTypeLoc()))
829 return true;
830
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832 PEnd = ND->param_end();
833 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000834 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000835 return true;
836 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000837
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000838 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000839 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 return false;
843}
844
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000845template <typename DeclIt>
846static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
847 SourceManager &SM, SourceLocation EndLoc,
848 SmallVectorImpl<Decl *> &Decls) {
849 DeclIt next = *DI_current;
850 while (++next != DE_current) {
851 Decl *D_next = *next;
852 if (!D_next)
853 break;
854 SourceLocation L = D_next->getLocStart();
855 if (!L.isValid())
856 break;
857 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
858 *DI_current = next;
859 Decls.push_back(D_next);
860 continue;
861 }
862 break;
863 }
864}
865
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000866namespace {
867 struct ContainerDeclsSort {
868 SourceManager &SM;
869 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
870 bool operator()(Decl *A, Decl *B) {
871 SourceLocation L_A = A->getLocStart();
872 SourceLocation L_B = B->getLocStart();
873 assert(L_A.isValid() && L_B.isValid());
874 return SM.isBeforeInTranslationUnit(L_A, L_B);
875 }
876 };
877}
878
Douglas Gregora59e3902010-01-21 23:27:09 +0000879bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000880 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
881 // an @implementation can lexically contain Decls that are not properly
882 // nested in the AST. When we identify such cases, we need to retrofit
883 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000884 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000885 return VisitDeclContext(D);
886
887 // Scan the Decls that immediately come after the container
888 // in the current DeclContext. If any fall within the
889 // container's lexical region, stash them into a vector
890 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000891 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000892 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000893 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000894 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000895 if (DI_current) {
896 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
897 DeclsInContainer);
898 } else {
899 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
900 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000901 }
902 }
903
904 // The common case.
905 if (DeclsInContainer.empty())
906 return VisitDeclContext(D);
907
908 // Get all the Decls in the DeclContext, and sort them with the
909 // additional ones we've collected. Then visit them.
910 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
911 I!=E; ++I) {
912 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000913 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
914 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000915 continue;
916 DeclsInContainer.push_back(subDecl);
917 }
918
919 // Now sort the Decls so that they appear in lexical order.
920 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
921 ContainerDeclsSort(SM));
922
923 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000924 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000925 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000926 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000927 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
928 if (!V.hasValue())
929 continue;
930 if (!V.getValue())
931 return false;
932 if (Visit(Cursor, true))
933 return true;
934 }
935 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000936}
937
Douglas Gregorb1373d02010-01-20 20:59:29 +0000938bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000939 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
940 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000943 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
944 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
945 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000946 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregora59e3902010-01-21 23:27:09 +0000949 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000950}
951
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000952bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000953 if (!PID->isThisDeclarationADefinition())
954 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
955
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000956 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
957 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
958 E = PID->protocol_end(); I != E; ++I, ++PL)
959 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
960 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000961
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000962 return VisitObjCContainerDecl(PID);
963}
964
Ted Kremenek23173d72010-05-18 21:09:07 +0000965bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000966 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000967 return true;
968
Ted Kremenek23173d72010-05-18 21:09:07 +0000969 // FIXME: This implements a workaround with @property declarations also being
970 // installed in the DeclContext for the @interface. Eventually this code
971 // should be removed.
972 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
973 if (!CDecl || !CDecl->IsClassExtension())
974 return false;
975
976 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
977 if (!ID)
978 return false;
979
980 IdentifierInfo *PropertyId = PD->getIdentifier();
981 ObjCPropertyDecl *prevDecl =
982 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
983
984 if (!prevDecl)
985 return false;
986
987 // Visit synthesized methods since they will be skipped when visiting
988 // the @interface.
989 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000990 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000991 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000992 return true;
993
994 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000995 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000996 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000997 return true;
998
999 return false;
1000}
1001
Douglas Gregorb1373d02010-01-20 20:59:29 +00001002bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001003 if (!D->isThisDeclarationADefinition()) {
1004 // Forward declaration is treated like a reference.
1005 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1006 }
1007
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001008 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009 if (D->getSuperClass() &&
1010 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001011 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001012 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001015 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1016 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1017 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001018 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001019 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001020
Douglas Gregora59e3902010-01-21 23:27:09 +00001021 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001022}
1023
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001024bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1025 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001026}
1027
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001029 // 'ID' could be null when dealing with invalid code.
1030 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1031 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1032 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001034 return VisitObjCImplDecl(D);
1035}
1036
1037bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1038#if 0
1039 // Issue callbacks for super class.
1040 // FIXME: No source location information!
1041 if (D->getSuperClass() &&
1042 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001044 TU)))
1045 return true;
1046#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001048 return VisitObjCImplDecl(D);
1049}
1050
Douglas Gregora4ffd852010-11-17 01:03:52 +00001051bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1052 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1053 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1054
1055 return false;
1056}
1057
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001058bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1059 return VisitDeclContext(D);
1060}
1061
Douglas Gregor69319002010-08-31 23:48:11 +00001062bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001063 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001064 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1065 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001066 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001067
1068 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1069 D->getTargetNameLoc(), TU));
1070}
1071
Douglas Gregor7e242562010-09-01 19:52:22 +00001072bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001073 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001074 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1075 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001076 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001077 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001078
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001079 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1080 return true;
1081
Douglas Gregor7e242562010-09-01 19:52:22 +00001082 return VisitDeclarationNameInfo(D->getNameInfo());
1083}
1084
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001085bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001087 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1088 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001089 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001090
1091 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1092 D->getIdentLocation(), TU));
1093}
1094
Douglas Gregor7e242562010-09-01 19:52:22 +00001095bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001097 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1098 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001099 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001100 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001101
Douglas Gregor7e242562010-09-01 19:52:22 +00001102 return VisitDeclarationNameInfo(D->getNameInfo());
1103}
1104
1105bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1106 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001107 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001108 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1109 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 return true;
1111
Douglas Gregor7e242562010-09-01 19:52:22 +00001112 return false;
1113}
1114
Douglas Gregor01829d32010-08-31 14:41:23 +00001115bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1116 switch (Name.getName().getNameKind()) {
1117 case clang::DeclarationName::Identifier:
1118 case clang::DeclarationName::CXXLiteralOperatorName:
1119 case clang::DeclarationName::CXXOperatorName:
1120 case clang::DeclarationName::CXXUsingDirective:
1121 return false;
1122
1123 case clang::DeclarationName::CXXConstructorName:
1124 case clang::DeclarationName::CXXDestructorName:
1125 case clang::DeclarationName::CXXConversionFunctionName:
1126 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1127 return Visit(TSInfo->getTypeLoc());
1128 return false;
1129
1130 case clang::DeclarationName::ObjCZeroArgSelector:
1131 case clang::DeclarationName::ObjCOneArgSelector:
1132 case clang::DeclarationName::ObjCMultiArgSelector:
1133 // FIXME: Per-identifier location info?
1134 return false;
1135 }
David Blaikie7530c032012-01-17 06:56:22 +00001136
1137 llvm_unreachable("Invalid DeclarationName::Kind!");
Douglas Gregor01829d32010-08-31 14:41:23 +00001138}
1139
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001140bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1141 SourceRange Range) {
1142 // FIXME: This whole routine is a hack to work around the lack of proper
1143 // source information in nested-name-specifiers (PR5791). Since we do have
1144 // a beginning source location, we can visit the first component of the
1145 // nested-name-specifier, if it's a single-token component.
1146 if (!NNS)
1147 return false;
1148
1149 // Get the first component in the nested-name-specifier.
1150 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1151 NNS = Prefix;
1152
1153 switch (NNS->getKind()) {
1154 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001155 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1156 TU));
1157
Douglas Gregor14aba762011-02-24 02:36:08 +00001158 case NestedNameSpecifier::NamespaceAlias:
1159 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1160 Range.getBegin(), TU));
1161
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001162 case NestedNameSpecifier::TypeSpec: {
1163 // If the type has a form where we know that the beginning of the source
1164 // range matches up with a reference cursor. Visit the appropriate reference
1165 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001166 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001167 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1168 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1169 if (const TagType *Tag = dyn_cast<TagType>(T))
1170 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1171 if (const TemplateSpecializationType *TST
1172 = dyn_cast<TemplateSpecializationType>(T))
1173 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1174 break;
1175 }
1176
1177 case NestedNameSpecifier::TypeSpecWithTemplate:
1178 case NestedNameSpecifier::Global:
1179 case NestedNameSpecifier::Identifier:
1180 break;
1181 }
1182
1183 return false;
1184}
1185
Douglas Gregordc355712011-02-25 00:36:19 +00001186bool
1187CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001188 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001189 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1190 Qualifiers.push_back(Qualifier);
1191
1192 while (!Qualifiers.empty()) {
1193 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1194 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1195 switch (NNS->getKind()) {
1196 case NestedNameSpecifier::Namespace:
1197 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001198 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001199 TU)))
1200 return true;
1201
1202 break;
1203
1204 case NestedNameSpecifier::NamespaceAlias:
1205 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001206 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001207 TU)))
1208 return true;
1209
1210 break;
1211
1212 case NestedNameSpecifier::TypeSpec:
1213 case NestedNameSpecifier::TypeSpecWithTemplate:
1214 if (Visit(Q.getTypeLoc()))
1215 return true;
1216
1217 break;
1218
1219 case NestedNameSpecifier::Global:
1220 case NestedNameSpecifier::Identifier:
1221 break;
1222 }
1223 }
1224
1225 return false;
1226}
1227
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001228bool CursorVisitor::VisitTemplateParameters(
1229 const TemplateParameterList *Params) {
1230 if (!Params)
1231 return false;
1232
1233 for (TemplateParameterList::const_iterator P = Params->begin(),
1234 PEnd = Params->end();
1235 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001236 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001237 return true;
1238 }
1239
1240 return false;
1241}
1242
Douglas Gregor0b36e612010-08-31 20:37:03 +00001243bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1244 switch (Name.getKind()) {
1245 case TemplateName::Template:
1246 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1247
1248 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001249 // Visit the overloaded template set.
1250 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1251 return true;
1252
Douglas Gregor0b36e612010-08-31 20:37:03 +00001253 return false;
1254
1255 case TemplateName::DependentTemplate:
1256 // FIXME: Visit nested-name-specifier.
1257 return false;
1258
1259 case TemplateName::QualifiedTemplate:
1260 // FIXME: Visit nested-name-specifier.
1261 return Visit(MakeCursorTemplateRef(
1262 Name.getAsQualifiedTemplateName()->getDecl(),
1263 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001264
1265 case TemplateName::SubstTemplateTemplateParm:
1266 return Visit(MakeCursorTemplateRef(
1267 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1268 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001269
1270 case TemplateName::SubstTemplateTemplateParmPack:
1271 return Visit(MakeCursorTemplateRef(
1272 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1273 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001274 }
David Blaikie7530c032012-01-17 06:56:22 +00001275
1276 llvm_unreachable("Invalid TemplateName::Kind!");
Douglas Gregor0b36e612010-08-31 20:37:03 +00001277}
1278
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001279bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1280 switch (TAL.getArgument().getKind()) {
1281 case TemplateArgument::Null:
1282 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001283 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001284 return false;
1285
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001286 case TemplateArgument::Type:
1287 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1288 return Visit(TSInfo->getTypeLoc());
1289 return false;
1290
1291 case TemplateArgument::Declaration:
1292 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001293 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001294 return false;
1295
1296 case TemplateArgument::Expression:
1297 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001298 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001299 return false;
1300
1301 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001302 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001303 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1304 return true;
1305
Douglas Gregora7fc9012011-01-05 18:58:31 +00001306 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001307 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001308 }
David Blaikie7530c032012-01-17 06:56:22 +00001309
1310 llvm_unreachable("Invalid TemplateArgument::Kind!");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001311}
1312
Ted Kremeneka0536d82010-05-07 01:04:29 +00001313bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1314 return VisitDeclContext(D);
1315}
1316
Douglas Gregor01829d32010-08-31 14:41:23 +00001317bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1318 return Visit(TL.getUnqualifiedLoc());
1319}
1320
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001321bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001322 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323
1324 // Some builtin types (such as Objective-C's "id", "sel", and
1325 // "Class") have associated declarations. Create cursors for those.
1326 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001327 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001328
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001329 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001330 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001331 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001332#define BUILTIN_TYPE(Id, SingletonId)
1333#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1334#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1335#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1336#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1337#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001339
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001340 case BuiltinType::ObjCId:
1341 VisitType = Context.getObjCIdType();
1342 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001343
1344 case BuiltinType::ObjCClass:
1345 VisitType = Context.getObjCClassType();
1346 break;
1347
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348 case BuiltinType::ObjCSel:
1349 VisitType = Context.getObjCSelType();
1350 break;
1351 }
1352
1353 if (!VisitType.isNull()) {
1354 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001355 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001356 TU));
1357 }
1358
1359 return false;
1360}
1361
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001362bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001363 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001364}
1365
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001366bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1367 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1368}
1369
1370bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001371 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001372 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001373
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001374 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1375}
1376
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001377bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001378 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001379}
1380
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1382 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1383 return true;
1384
John McCallc12c5bb2010-05-15 11:32:37 +00001385 return false;
1386}
1387
1388bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1389 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1390 return true;
1391
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1393 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1394 TU)))
1395 return true;
1396 }
1397
1398 return false;
1399}
1400
1401bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001402 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001403}
1404
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001405bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1406 return Visit(TL.getInnerLoc());
1407}
1408
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1410 return Visit(TL.getPointeeLoc());
1411}
1412
1413bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1414 return Visit(TL.getPointeeLoc());
1415}
1416
1417bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1418 return Visit(TL.getPointeeLoc());
1419}
1420
1421bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001422 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423}
1424
1425bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001426 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001427}
1428
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001429bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1430 return Visit(TL.getModifiedLoc());
1431}
1432
Douglas Gregor01829d32010-08-31 14:41:23 +00001433bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1434 bool SkipResultType) {
1435 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001436 return true;
1437
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001438 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001439 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001440 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001441 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001442
1443 return false;
1444}
1445
1446bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1447 if (Visit(TL.getElementLoc()))
1448 return true;
1449
1450 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001451 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001452
1453 return false;
1454}
1455
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001456bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1457 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001458 // Visit the template name.
1459 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1460 TL.getTemplateNameLoc()))
1461 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001462
1463 // Visit the template arguments.
1464 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1465 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1466 return true;
1467
1468 return false;
1469}
1470
Douglas Gregor2332c112010-01-21 20:48:56 +00001471bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1472 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1473}
1474
1475bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1476 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1477 return Visit(TSInfo->getTypeLoc());
1478
1479 return false;
1480}
1481
Sean Huntca63c202011-05-24 22:41:36 +00001482bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1483 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1484 return Visit(TSInfo->getTypeLoc());
1485
1486 return false;
1487}
1488
Douglas Gregor2494dd02011-03-01 01:34:45 +00001489bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1490 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1491 return true;
1492
1493 return false;
1494}
1495
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001496bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1497 DependentTemplateSpecializationTypeLoc TL) {
1498 // Visit the nested-name-specifier, if there is one.
1499 if (TL.getQualifierLoc() &&
1500 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1501 return true;
1502
1503 // Visit the template arguments.
1504 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1505 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1506 return true;
1507
1508 return false;
1509}
1510
Douglas Gregor9e876872011-03-01 18:12:44 +00001511bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1512 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1513 return true;
1514
1515 return Visit(TL.getNamedTypeLoc());
1516}
1517
Douglas Gregor7536dd52010-12-20 02:24:11 +00001518bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1519 return Visit(TL.getPatternLoc());
1520}
1521
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001522bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1523 if (Expr *E = TL.getUnderlyingExpr())
1524 return Visit(MakeCXCursor(E, StmtParent, TU));
1525
1526 return false;
1527}
1528
1529bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1530 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1531}
1532
Eli Friedmanb001de72011-10-06 23:00:33 +00001533bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1534 return Visit(TL.getValueLoc());
1535}
1536
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001537#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1538bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1539 return Visit##PARENT##Loc(TL); \
1540}
1541
1542DEFAULT_TYPELOC_IMPL(Complex, Type)
1543DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1544DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1545DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1546DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1547DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1548DEFAULT_TYPELOC_IMPL(Vector, Type)
1549DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1550DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1551DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1552DEFAULT_TYPELOC_IMPL(Record, TagType)
1553DEFAULT_TYPELOC_IMPL(Enum, TagType)
1554DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1555DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1556DEFAULT_TYPELOC_IMPL(Auto, Type)
1557
Ted Kremenek3064ef92010-08-27 21:34:58 +00001558bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001559 // Visit the nested-name-specifier, if present.
1560 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1561 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1562 return true;
1563
John McCall5e1cdac2011-10-07 06:10:15 +00001564 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001565 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1566 E = D->bases_end(); I != E; ++I) {
1567 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1568 return true;
1569 }
1570 }
1571
1572 return VisitTagDecl(D);
1573}
1574
Ted Kremenek09dfa372010-02-18 05:46:33 +00001575bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001576 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1577 i != e; ++i)
1578 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001579 return true;
1580
1581 return false;
1582}
1583
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001584//===----------------------------------------------------------------------===//
1585// Data-recursive visitor methods.
1586//===----------------------------------------------------------------------===//
1587
Ted Kremenek28a71942010-11-13 00:36:47 +00001588namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001589#define DEF_JOB(NAME, DATA, KIND)\
1590class NAME : public VisitorJob {\
1591public:\
1592 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1593 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001594 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001595};
1596
1597DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1598DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001599DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001600DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001601DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001602 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001603DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001604#undef DEF_JOB
1605
1606class DeclVisit : public VisitorJob {
1607public:
1608 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1609 VisitorJob(parent, VisitorJob::DeclVisitKind,
1610 d, isFirst ? (void*) 1 : (void*) 0) {}
1611 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001612 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001613 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001614 Decl *get() const { return static_cast<Decl*>(data[0]); }
1615 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001616};
Ted Kremenek035dc412010-11-13 00:36:50 +00001617class TypeLocVisit : public VisitorJob {
1618public:
1619 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1620 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1621 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1622
1623 static bool classof(const VisitorJob *VJ) {
1624 return VJ->getKind() == TypeLocVisitKind;
1625 }
1626
Ted Kremenek82f3c502010-11-15 22:23:26 +00001627 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001628 QualType T = QualType::getFromOpaquePtr(data[0]);
1629 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001630 }
1631};
1632
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001633class LabelRefVisit : public VisitorJob {
1634public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001635 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1636 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001637 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001638
1639 static bool classof(const VisitorJob *VJ) {
1640 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1641 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001642 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001643 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001644 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001645};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001646
1647class NestedNameSpecifierLocVisit : public VisitorJob {
1648public:
1649 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1650 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1651 Qualifier.getNestedNameSpecifier(),
1652 Qualifier.getOpaqueData()) { }
1653
1654 static bool classof(const VisitorJob *VJ) {
1655 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1656 }
1657
1658 NestedNameSpecifierLoc get() const {
1659 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1660 data[1]);
1661 }
1662};
1663
Ted Kremenekf64d8032010-11-18 00:02:32 +00001664class DeclarationNameInfoVisit : public VisitorJob {
1665public:
1666 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1667 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1668 static bool classof(const VisitorJob *VJ) {
1669 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1670 }
1671 DeclarationNameInfo get() const {
1672 Stmt *S = static_cast<Stmt*>(data[0]);
1673 switch (S->getStmtClass()) {
1674 default:
1675 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001676 case clang::Stmt::MSDependentExistsStmtClass:
1677 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001678 case Stmt::CXXDependentScopeMemberExprClass:
1679 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1680 case Stmt::DependentScopeDeclRefExprClass:
1681 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1682 }
1683 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001684};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001685class MemberRefVisit : public VisitorJob {
1686public:
1687 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1688 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001689 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001690 static bool classof(const VisitorJob *VJ) {
1691 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1692 }
1693 FieldDecl *get() const {
1694 return static_cast<FieldDecl*>(data[0]);
1695 }
1696 SourceLocation getLoc() const {
1697 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1698 }
1699};
Ted Kremenek28a71942010-11-13 00:36:47 +00001700class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1701 VisitorWorkList &WL;
1702 CXCursor Parent;
1703public:
1704 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1705 : WL(wl), Parent(parent) {}
1706
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001707 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001708 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001709 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001710 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001711 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001712 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001713 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001714 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001715 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001716 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001717 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001718 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001719 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001720 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001721 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001722 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001723 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001724 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001725 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001726 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001727 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1728 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001729 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001730 void VisitIfStmt(IfStmt *If);
1731 void VisitInitListExpr(InitListExpr *IE);
1732 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001733 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001734 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001735 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1736 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001737 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001738 void VisitStmt(Stmt *S);
1739 void VisitSwitchStmt(SwitchStmt *S);
1740 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001741 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001742 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001743 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001744 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001745 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001746 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001747 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001748 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1749 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001750
Ted Kremenek28a71942010-11-13 00:36:47 +00001751private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001752 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001753 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001754 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001755 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001756 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001757 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001758 void AddTypeLoc(TypeSourceInfo *TI);
1759 void EnqueueChildren(Stmt *S);
1760};
1761} // end anonyous namespace
1762
Ted Kremenekf64d8032010-11-18 00:02:32 +00001763void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1764 // 'S' should always be non-null, since it comes from the
1765 // statement we are visiting.
1766 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1767}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001768
1769void
1770EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1771 if (Qualifier)
1772 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1773}
1774
Ted Kremenek28a71942010-11-13 00:36:47 +00001775void EnqueueVisitor::AddStmt(Stmt *S) {
1776 if (S)
1777 WL.push_back(StmtVisit(S, Parent));
1778}
Ted Kremenek035dc412010-11-13 00:36:50 +00001779void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001780 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001781 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001782}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001783void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001784 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001785 if (A)
1786 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001787 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001788}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001789void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1790 if (D)
1791 WL.push_back(MemberRefVisit(D, L, Parent));
1792}
Ted Kremenek28a71942010-11-13 00:36:47 +00001793void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1794 if (TI)
1795 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1796 }
1797void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001798 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001799 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001800 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001801 }
1802 if (size == WL.size())
1803 return;
1804 // Now reverse the entries we just added. This will match the DFS
1805 // ordering performed by the worklist.
1806 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1807 std::reverse(I, E);
1808}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001809void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1810 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1811}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001812void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1813 AddDecl(B->getBlockDecl());
1814}
Ted Kremenek28a71942010-11-13 00:36:47 +00001815void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1816 EnqueueChildren(E);
1817 AddTypeLoc(E->getTypeSourceInfo());
1818}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001819void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1820 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1821 E = S->body_rend(); I != E; ++I) {
1822 AddStmt(*I);
1823 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001824}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001825void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001826VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1827 AddStmt(S->getSubStmt());
1828 AddDeclarationNameInfo(S);
1829 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1830 AddNestedNameSpecifierLoc(QualifierLoc);
1831}
1832
1833void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001834VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1835 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1836 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001837 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1838 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001839 if (!E->isImplicitAccess())
1840 AddStmt(E->getBase());
1841}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001842void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1843 // Enqueue the initializer or constructor arguments.
1844 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1845 AddStmt(E->getConstructorArg(I-1));
1846 // Enqueue the array size, if any.
1847 AddStmt(E->getArraySize());
1848 // Enqueue the allocated type.
1849 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1850 // Enqueue the placement arguments.
1851 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1852 AddStmt(E->getPlacementArg(I-1));
1853}
Ted Kremenek28a71942010-11-13 00:36:47 +00001854void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001855 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1856 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001857 AddStmt(CE->getCallee());
1858 AddStmt(CE->getArg(0));
1859}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001860void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1861 // Visit the name of the type being destroyed.
1862 AddTypeLoc(E->getDestroyedTypeInfo());
1863 // Visit the scope type that looks disturbingly like the nested-name-specifier
1864 // but isn't.
1865 AddTypeLoc(E->getScopeTypeInfo());
1866 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001867 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1868 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001869 // Visit base expression.
1870 AddStmt(E->getBase());
1871}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001872void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1873 AddTypeLoc(E->getTypeSourceInfo());
1874}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001875void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1876 EnqueueChildren(E);
1877 AddTypeLoc(E->getTypeSourceInfo());
1878}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001879void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1880 EnqueueChildren(E);
1881 if (E->isTypeOperand())
1882 AddTypeLoc(E->getTypeOperandSourceInfo());
1883}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001884
1885void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1886 *E) {
1887 EnqueueChildren(E);
1888 AddTypeLoc(E->getTypeSourceInfo());
1889}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001890void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1891 EnqueueChildren(E);
1892 if (E->isTypeOperand())
1893 AddTypeLoc(E->getTypeOperandSourceInfo());
1894}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001895
1896void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1897 EnqueueChildren(S);
1898 AddDecl(S->getExceptionDecl());
1899}
1900
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001901void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001902 if (DR->hasExplicitTemplateArgs()) {
1903 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1904 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001905 WL.push_back(DeclRefExprParts(DR, Parent));
1906}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001907void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1908 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1909 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001910 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001911}
Ted Kremenek035dc412010-11-13 00:36:50 +00001912void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1913 unsigned size = WL.size();
1914 bool isFirst = true;
1915 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1916 D != DEnd; ++D) {
1917 AddDecl(*D, isFirst);
1918 isFirst = false;
1919 }
1920 if (size == WL.size())
1921 return;
1922 // Now reverse the entries we just added. This will match the DFS
1923 // ordering performed by the worklist.
1924 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1925 std::reverse(I, E);
1926}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001927void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1928 AddStmt(E->getInit());
1929 typedef DesignatedInitExpr::Designator Designator;
1930 for (DesignatedInitExpr::reverse_designators_iterator
1931 D = E->designators_rbegin(), DEnd = E->designators_rend();
1932 D != DEnd; ++D) {
1933 if (D->isFieldDesignator()) {
1934 if (FieldDecl *Field = D->getField())
1935 AddMemberRef(Field, D->getFieldLoc());
1936 continue;
1937 }
1938 if (D->isArrayDesignator()) {
1939 AddStmt(E->getArrayIndex(*D));
1940 continue;
1941 }
1942 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1943 AddStmt(E->getArrayRangeEnd(*D));
1944 AddStmt(E->getArrayRangeStart(*D));
1945 }
1946}
Ted Kremenek28a71942010-11-13 00:36:47 +00001947void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1948 EnqueueChildren(E);
1949 AddTypeLoc(E->getTypeInfoAsWritten());
1950}
1951void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1952 AddStmt(FS->getBody());
1953 AddStmt(FS->getInc());
1954 AddStmt(FS->getCond());
1955 AddDecl(FS->getConditionVariable());
1956 AddStmt(FS->getInit());
1957}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001958void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1959 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1960}
Ted Kremenek28a71942010-11-13 00:36:47 +00001961void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1962 AddStmt(If->getElse());
1963 AddStmt(If->getThen());
1964 AddStmt(If->getCond());
1965 AddDecl(If->getConditionVariable());
1966}
1967void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1968 // We care about the syntactic form of the initializer list, only.
1969 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1970 IE = Syntactic;
1971 EnqueueChildren(IE);
1972}
1973void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001974 WL.push_back(MemberExprParts(M, Parent));
1975
1976 // If the base of the member access expression is an implicit 'this', don't
1977 // visit it.
1978 // FIXME: If we ever want to show these implicit accesses, this will be
1979 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001980 if (!M->isImplicitAccess())
1981 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001982}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001983void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1984 AddTypeLoc(E->getEncodedTypeSourceInfo());
1985}
Ted Kremenek28a71942010-11-13 00:36:47 +00001986void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1987 EnqueueChildren(M);
1988 AddTypeLoc(M->getClassReceiverTypeInfo());
1989}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001990void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1991 // Visit the components of the offsetof expression.
1992 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1993 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1994 const OffsetOfNode &Node = E->getComponent(I-1);
1995 switch (Node.getKind()) {
1996 case OffsetOfNode::Array:
1997 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1998 break;
1999 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002000 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002001 break;
2002 case OffsetOfNode::Identifier:
2003 case OffsetOfNode::Base:
2004 continue;
2005 }
2006 }
2007 // Visit the type into which we're computing the offset.
2008 AddTypeLoc(E->getTypeSourceInfo());
2009}
Ted Kremenek28a71942010-11-13 00:36:47 +00002010void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002011 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002012 WL.push_back(OverloadExprParts(E, Parent));
2013}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002014void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2015 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002016 EnqueueChildren(E);
2017 if (E->isArgumentType())
2018 AddTypeLoc(E->getArgumentTypeInfo());
2019}
Ted Kremenek28a71942010-11-13 00:36:47 +00002020void EnqueueVisitor::VisitStmt(Stmt *S) {
2021 EnqueueChildren(S);
2022}
2023void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2024 AddStmt(S->getBody());
2025 AddStmt(S->getCond());
2026 AddDecl(S->getConditionVariable());
2027}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002028
Ted Kremenek28a71942010-11-13 00:36:47 +00002029void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2030 AddStmt(W->getBody());
2031 AddStmt(W->getCond());
2032 AddDecl(W->getConditionVariable());
2033}
John Wiegley21ff2e52011-04-28 00:16:57 +00002034
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002035void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2036 AddTypeLoc(E->getQueriedTypeSourceInfo());
2037}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002038
2039void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002040 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002041 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002042}
2043
John Wiegley21ff2e52011-04-28 00:16:57 +00002044void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2045 AddTypeLoc(E->getQueriedTypeSourceInfo());
2046}
2047
John Wiegley55262202011-04-25 06:54:41 +00002048void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2049 EnqueueChildren(E);
2050}
2051
Ted Kremenek28a71942010-11-13 00:36:47 +00002052void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2053 VisitOverloadExpr(U);
2054 if (!U->isImplicitAccess())
2055 AddStmt(U->getBase());
2056}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002057void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2058 AddStmt(E->getSubExpr());
2059 AddTypeLoc(E->getWrittenTypeInfo());
2060}
Douglas Gregor94d96292011-01-19 20:34:17 +00002061void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2062 WL.push_back(SizeOfPackExprParts(E, Parent));
2063}
John McCall4b9c2d22011-11-06 09:01:30 +00002064void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2065 // If the opaque value has a source expression, just transparently
2066 // visit that. This is useful for (e.g.) pseudo-object expressions.
2067 if (Expr *SourceExpr = E->getSourceExpr())
2068 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002069}
2070void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2071 // Treat the expression like its syntactic form.
2072 Visit(E->getSyntacticForm());
2073}
Ted Kremenek60458782010-11-12 21:34:16 +00002074
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002075void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002076 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002077}
2078
2079bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2080 if (RegionOfInterest.isValid()) {
2081 SourceRange Range = getRawCursorExtent(C);
2082 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2083 return false;
2084 }
2085 return true;
2086}
2087
2088bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2089 while (!WL.empty()) {
2090 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002091 VisitorJob LI = WL.back();
2092 WL.pop_back();
2093
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002094 // Set the Parent field, then back to its old value once we're done.
2095 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2096
2097 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002098 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002099 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002100 if (!D)
2101 continue;
2102
2103 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002104 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2105 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002106 return true;
2107
2108 continue;
2109 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002110 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002111 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002112 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2113 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2114 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2115 Arg != ArgEnd; ++Arg) {
2116 if (VisitTemplateArgumentLoc(*Arg))
2117 return true;
2118 }
2119 continue;
2120 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002121 case VisitorJob::TypeLocVisitKind: {
2122 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002123 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002124 return true;
2125 continue;
2126 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002127 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002128 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002129 if (LabelStmt *stmt = LS->getStmt()) {
2130 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2131 TU))) {
2132 return true;
2133 }
2134 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002135 continue;
2136 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002137
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002138 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2139 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2140 if (VisitNestedNameSpecifierLoc(V->get()))
2141 return true;
2142 continue;
2143 }
2144
Ted Kremenekf64d8032010-11-18 00:02:32 +00002145 case VisitorJob::DeclarationNameInfoVisitKind: {
2146 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2147 ->get()))
2148 return true;
2149 continue;
2150 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002151 case VisitorJob::MemberRefVisitKind: {
2152 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2153 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2154 return true;
2155 continue;
2156 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002157 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002158 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002159 if (!S)
2160 continue;
2161
Ted Kremenekf1107452010-11-12 18:26:56 +00002162 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002163 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002164 if (!IsInRegionOfInterest(Cursor))
2165 continue;
2166 switch (Visitor(Cursor, Parent, ClientData)) {
2167 case CXChildVisit_Break: return true;
2168 case CXChildVisit_Continue: break;
2169 case CXChildVisit_Recurse:
2170 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002171 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002172 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002173 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002174 }
2175 case VisitorJob::MemberExprPartsKind: {
2176 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002177 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002178
2179 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002180 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2181 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002182 return true;
2183
2184 // Visit the declaration name.
2185 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2186 return true;
2187
2188 // Visit the explicitly-specified template arguments, if any.
2189 if (M->hasExplicitTemplateArgs()) {
2190 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2191 *ArgEnd = Arg + M->getNumTemplateArgs();
2192 Arg != ArgEnd; ++Arg) {
2193 if (VisitTemplateArgumentLoc(*Arg))
2194 return true;
2195 }
2196 }
2197 continue;
2198 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002199 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002200 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002201 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002202 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2203 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002204 return true;
2205 // Visit declaration name.
2206 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2207 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002208 continue;
2209 }
Ted Kremenek60458782010-11-12 21:34:16 +00002210 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002211 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002212 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002213 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2214 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002215 return true;
2216 // Visit the declaration name.
2217 if (VisitDeclarationNameInfo(O->getNameInfo()))
2218 return true;
2219 // Visit the overloaded declaration reference.
2220 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2221 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002222 continue;
2223 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002224 case VisitorJob::SizeOfPackExprPartsKind: {
2225 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2226 NamedDecl *Pack = E->getPack();
2227 if (isa<TemplateTypeParmDecl>(Pack)) {
2228 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2229 E->getPackLoc(), TU)))
2230 return true;
2231
2232 continue;
2233 }
2234
2235 if (isa<TemplateTemplateParmDecl>(Pack)) {
2236 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2237 E->getPackLoc(), TU)))
2238 return true;
2239
2240 continue;
2241 }
2242
2243 // Non-type template parameter packs and function parameter packs are
2244 // treated like DeclRefExpr cursors.
2245 continue;
2246 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002247 }
2248 }
2249 return false;
2250}
2251
Ted Kremenekcdba6592010-11-18 00:42:18 +00002252bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002253 VisitorWorkList *WL = 0;
2254 if (!WorkListFreeList.empty()) {
2255 WL = WorkListFreeList.back();
2256 WL->clear();
2257 WorkListFreeList.pop_back();
2258 }
2259 else {
2260 WL = new VisitorWorkList();
2261 WorkListCache.push_back(WL);
2262 }
2263 EnqueueWorkList(*WL, S);
2264 bool result = RunVisitorWorkList(*WL);
2265 WorkListFreeList.push_back(WL);
2266 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002267}
2268
Francois Pichet48a8d142011-07-25 22:00:44 +00002269namespace {
2270typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2271RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2272 const DeclarationNameInfo &NI,
2273 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002274 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002275 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2276 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2277 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2278
2279 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2280
2281 RefNamePieces Pieces;
2282
2283 if (WantQualifier && QLoc.isValid())
2284 Pieces.push_back(QLoc);
2285
2286 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2287 Pieces.push_back(NI.getLoc());
2288
2289 if (WantTemplateArgs && TemplateArgs)
2290 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2291 TemplateArgs->RAngleLoc));
2292
2293 if (Kind == DeclarationName::CXXOperatorName) {
2294 Pieces.push_back(SourceLocation::getFromRawEncoding(
2295 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2296 Pieces.push_back(SourceLocation::getFromRawEncoding(
2297 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2298 }
2299
2300 if (WantSinglePiece) {
2301 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2302 Pieces.clear();
2303 Pieces.push_back(R);
2304 }
2305
2306 return Pieces;
2307}
2308}
2309
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002310//===----------------------------------------------------------------------===//
2311// Misc. API hooks.
2312//===----------------------------------------------------------------------===//
2313
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002314static llvm::sys::Mutex EnableMultithreadingMutex;
2315static bool EnabledMultithreading;
2316
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002317static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002318 // Write the result out to stderr avoiding errs() because raw_ostreams can
2319 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002320 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002321 ::abort();
2322}
2323
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002324extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002325CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2326 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002327 // Disable pretty stack trace functionality, which will otherwise be a very
2328 // poor citizen of the world and set up all sorts of signal handlers.
2329 llvm::DisablePrettyStackTrace = true;
2330
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002331 // We use crash recovery to make some of our APIs more reliable, implicitly
2332 // enable it.
2333 llvm::CrashRecoveryContext::Enable();
2334
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002335 // Enable support for multithreading in LLVM.
2336 {
2337 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2338 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002339 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002340 llvm::llvm_start_multithreaded();
2341 EnabledMultithreading = true;
2342 }
2343 }
2344
Douglas Gregora030b7c2010-01-22 20:35:53 +00002345 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002346 if (excludeDeclarationsFromPCH)
2347 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002348 if (displayDiagnostics)
2349 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002350 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002351}
2352
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002353void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002354 if (CIdx)
2355 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002356}
2357
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002358void clang_toggleCrashRecovery(unsigned isEnabled) {
2359 if (isEnabled)
2360 llvm::CrashRecoveryContext::Enable();
2361 else
2362 llvm::CrashRecoveryContext::Disable();
2363}
2364
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002365CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002366 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002367 if (!CIdx)
2368 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002369
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002370 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002371 FileSystemOptions FileSystemOpts;
2372 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002373
David Blaikied6471f72011-09-25 23:23:43 +00002374 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002375 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002376 CXXIdx->getOnlyLocalDecls(),
2377 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002378 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002379}
2380
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002381unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002382 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002383 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002384}
2385
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002386CXTranslationUnit
2387clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2388 const char *source_filename,
2389 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002390 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002391 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002392 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002393 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002394 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002395 return clang_parseTranslationUnit(CIdx, source_filename,
2396 command_line_args, num_command_line_args,
2397 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002398 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002399}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002400
2401struct ParseTranslationUnitInfo {
2402 CXIndex CIdx;
2403 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002404 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002405 int num_command_line_args;
2406 struct CXUnsavedFile *unsaved_files;
2407 unsigned num_unsaved_files;
2408 unsigned options;
2409 CXTranslationUnit result;
2410};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002411static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002412 ParseTranslationUnitInfo *PTUI =
2413 static_cast<ParseTranslationUnitInfo*>(UserData);
2414 CXIndex CIdx = PTUI->CIdx;
2415 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002416 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002417 int num_command_line_args = PTUI->num_command_line_args;
2418 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2419 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2420 unsigned options = PTUI->options;
2421 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002422
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002423 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002424 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002426 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2427
Douglas Gregor44c181a2010-07-23 00:33:23 +00002428 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002429 // FIXME: Add a flag for modules.
2430 TranslationUnitKind TUKind
2431 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002432 bool CacheCodeCompetionResults
2433 = options & CXTranslationUnit_CacheCompletionResults;
2434
Douglas Gregor5352ac02010-01-28 00:27:43 +00002435 // Configure the diagnostics.
2436 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002437 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002438 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2439 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002440
Ted Kremenek25a11e12011-03-22 01:15:24 +00002441 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002442 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2443 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002444 DiagCleanup(Diags.getPtr());
2445
2446 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2447 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2448
2449 // Recover resources if we crash before exiting this function.
2450 llvm::CrashRecoveryContextCleanupRegistrar<
2451 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2452
Douglas Gregor4db64a42010-01-23 00:14:00 +00002453 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002454 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002455 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002456 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002457 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2458 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002459 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002460
Ted Kremenek25a11e12011-03-22 01:15:24 +00002461 llvm::OwningPtr<std::vector<const char *> >
2462 Args(new std::vector<const char*>());
2463
2464 // Recover resources if we crash before exiting this method.
2465 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2466 ArgsCleanup(Args.get());
2467
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002468 // Since the Clang C library is primarily used by batch tools dealing with
2469 // (often very broken) source code, where spell-checking can have a
2470 // significant negative impact on performance (particularly when
2471 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002472 // Only do this if we haven't found a spell-checking-related argument.
2473 bool FoundSpellCheckingArgument = false;
2474 for (int I = 0; I != num_command_line_args; ++I) {
2475 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2476 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2477 FoundSpellCheckingArgument = true;
2478 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002479 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002480 }
2481 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002482 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002483
Ted Kremenek25a11e12011-03-22 01:15:24 +00002484 Args->insert(Args->end(), command_line_args,
2485 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002486
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002487 // The 'source_filename' argument is optional. If the caller does not
2488 // specify it then it is assumed that the source file is specified
2489 // in the actual argument list.
2490 // Put the source file after command_line_args otherwise if '-x' flag is
2491 // present it will be unused.
2492 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002493 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002494
Douglas Gregor44c181a2010-07-23 00:33:23 +00002495 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002496 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002497 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002498 Args->push_back("-Xclang");
2499 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002500 NestedMacroExpansions
2501 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002502 }
2503
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002504 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002505 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002506 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2507 /* vector::data() not portable */,
2508 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002509 Diags,
2510 CXXIdx->getClangResourcesPath(),
2511 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002512 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002513 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002514 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002515 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002516 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002517 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002518 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002519 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002520
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002521 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002522 // Make sure to check that 'Unit' is non-NULL.
2523 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2524 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2525 DEnd = Unit->stored_diag_end();
2526 D != DEnd; ++D) {
2527 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2528 CXString Msg = clang_formatDiagnostic(&Diag,
2529 clang_defaultDiagnosticDisplayOptions());
2530 fprintf(stderr, "%s\n", clang_getCString(Msg));
2531 clang_disposeString(Msg);
2532 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002533#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002534 // On Windows, force a flush, since there may be multiple copies of
2535 // stderr and stdout in the file system, all with different buffers
2536 // but writing to the same device.
2537 fflush(stderr);
2538#endif
2539 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002540 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002541
Ted Kremeneka60ed472010-11-16 08:15:36 +00002542 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002543}
2544CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2545 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002546 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002547 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002548 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002549 unsigned num_unsaved_files,
2550 unsigned options) {
2551 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002552 num_command_line_args, unsaved_files,
2553 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002554 llvm::CrashRecoveryContext CRC;
2555
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002556 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002557 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2558 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2559 fprintf(stderr, " 'command_line_args' : [");
2560 for (int i = 0; i != num_command_line_args; ++i) {
2561 if (i)
2562 fprintf(stderr, ", ");
2563 fprintf(stderr, "'%s'", command_line_args[i]);
2564 }
2565 fprintf(stderr, "],\n");
2566 fprintf(stderr, " 'unsaved_files' : [");
2567 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2568 if (i)
2569 fprintf(stderr, ", ");
2570 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2571 unsaved_files[i].Length);
2572 }
2573 fprintf(stderr, "],\n");
2574 fprintf(stderr, " 'options' : %d,\n", options);
2575 fprintf(stderr, "}\n");
2576
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002577 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002578 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2579 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002580 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002581
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002582 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002583}
2584
Douglas Gregor19998442010-08-13 15:35:05 +00002585unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2586 return CXSaveTranslationUnit_None;
2587}
2588
2589int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2590 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002591 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002592 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002593
Douglas Gregor39c411f2011-07-06 16:43:36 +00002594 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002595 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2596 PrintLibclangResourceUsage(TU);
2597 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002598}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002599
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002600void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002601 if (CTUnit) {
2602 // If the translation unit has been marked as unsafe to free, just discard
2603 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002604 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002605 return;
2606
Ted Kremeneka60ed472010-11-16 08:15:36 +00002607 delete static_cast<ASTUnit *>(CTUnit->TUData);
2608 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002609 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002610 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002611 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002612}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002613
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002614unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2615 return CXReparse_None;
2616}
2617
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002618struct ReparseTranslationUnitInfo {
2619 CXTranslationUnit TU;
2620 unsigned num_unsaved_files;
2621 struct CXUnsavedFile *unsaved_files;
2622 unsigned options;
2623 int result;
2624};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002625
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002626static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002627 ReparseTranslationUnitInfo *RTUI =
2628 static_cast<ReparseTranslationUnitInfo*>(UserData);
2629 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002630
2631 // Reset the associated diagnostics.
2632 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2633 TU->Diagnostics = 0;
2634
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002635 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2636 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2637 unsigned options = RTUI->options;
2638 (void) options;
2639 RTUI->result = 1;
2640
Douglas Gregorabc563f2010-07-19 21:46:24 +00002641 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002642 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002643
Ted Kremeneka60ed472010-11-16 08:15:36 +00002644 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002645 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002646
Ted Kremenek25a11e12011-03-22 01:15:24 +00002647 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2648 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2649
2650 // Recover resources if we crash before exiting this function.
2651 llvm::CrashRecoveryContextCleanupRegistrar<
2652 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2653
Douglas Gregorabc563f2010-07-19 21:46:24 +00002654 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002655 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002656 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002657 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002658 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2659 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002660 }
2661
Ted Kremenek4ee99262011-03-22 20:16:19 +00002662 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2663 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002664 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002665}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002666
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002667int clang_reparseTranslationUnit(CXTranslationUnit TU,
2668 unsigned num_unsaved_files,
2669 struct CXUnsavedFile *unsaved_files,
2670 unsigned options) {
2671 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2672 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002673
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002674 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002675 clang_reparseTranslationUnit_Impl(&RTUI);
2676 return RTUI.result;
2677 }
2678
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002679 llvm::CrashRecoveryContext CRC;
2680
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002681 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002682 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002683 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002684 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002685 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2686 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002687
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002688 return RTUI.result;
2689}
2690
Douglas Gregordf95a132010-08-09 20:45:32 +00002691
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002692CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002693 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002694 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002695
Ted Kremeneka60ed472010-11-16 08:15:36 +00002696 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002697 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002698}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002699
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002700CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002701 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002702 return Result;
2703}
2704
Ted Kremenekfb480492010-01-13 21:46:36 +00002705} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002706
Ted Kremenekfb480492010-01-13 21:46:36 +00002707//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002708// CXFile Operations.
2709//===----------------------------------------------------------------------===//
2710
2711extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002712CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002713 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002714 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715
Steve Naroff88145032009-10-27 14:35:18 +00002716 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002717 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002718}
2719
2720time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002721 if (!SFile)
2722 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002723
Steve Naroff88145032009-10-27 14:35:18 +00002724 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2725 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002726}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002727
Douglas Gregorb9790342010-01-22 21:44:22 +00002728CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2729 if (!tu)
2730 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002731
Ted Kremeneka60ed472010-11-16 08:15:36 +00002732 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002733
Douglas Gregorb9790342010-01-22 21:44:22 +00002734 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002735 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002736}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002737
Douglas Gregordd3e5542011-05-04 00:14:37 +00002738unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2739 if (!tu || !file)
2740 return 0;
2741
2742 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2743 FileEntry *FEnt = static_cast<FileEntry *>(file);
2744 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2745 .isFileMultipleIncludeGuarded(FEnt);
2746}
2747
Ted Kremenekfb480492010-01-13 21:46:36 +00002748} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002749
Ted Kremenekfb480492010-01-13 21:46:36 +00002750//===----------------------------------------------------------------------===//
2751// CXCursor Operations.
2752//===----------------------------------------------------------------------===//
2753
Ted Kremenekfb480492010-01-13 21:46:36 +00002754static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002755 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002756 return getDeclFromExpr(CE->getSubExpr());
2757
Ted Kremenekfb480492010-01-13 21:46:36 +00002758 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2759 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002760 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2761 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002762 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2763 return ME->getMemberDecl();
2764 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2765 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002766 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002767 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002768 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2769 return getDeclFromExpr(POE->getSyntacticForm());
2770 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2771 if (Expr *Src = OVE->getSourceExpr())
2772 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002773
Ted Kremenekfb480492010-01-13 21:46:36 +00002774 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2775 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002776 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002777 if (!CE->isElidable())
2778 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002779 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2780 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002781
Douglas Gregordb1314e2010-10-01 21:11:22 +00002782 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2783 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002784 if (SubstNonTypeTemplateParmPackExpr *NTTP
2785 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2786 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002787 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2788 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2789 isa<ParmVarDecl>(SizeOfPack->getPack()))
2790 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002791
Ted Kremenekfb480492010-01-13 21:46:36 +00002792 return 0;
2793}
2794
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002795static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002796 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2797 return getLocationFromExpr(CE->getSubExpr());
2798
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002799 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2800 return /*FIXME:*/Msg->getLeftLoc();
2801 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2802 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002803 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2804 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002805 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2806 return Member->getMemberLoc();
2807 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2808 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002809 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2810 return SizeOfPack->getPackLoc();
2811
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002812 return E->getLocStart();
2813}
2814
Ted Kremenekfb480492010-01-13 21:46:36 +00002815extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002816
2817unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002818 CXCursorVisitor visitor,
2819 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002820 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2821 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002822 return CursorVis.VisitChildren(parent);
2823}
2824
David Chisnall3387c652010-11-03 14:12:26 +00002825#ifndef __has_feature
2826#define __has_feature(x) 0
2827#endif
2828#if __has_feature(blocks)
2829typedef enum CXChildVisitResult
2830 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2831
2832static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2833 CXClientData client_data) {
2834 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2835 return block(cursor, parent);
2836}
2837#else
2838// If we are compiled with a compiler that doesn't have native blocks support,
2839// define and call the block manually, so the
2840typedef struct _CXChildVisitResult
2841{
2842 void *isa;
2843 int flags;
2844 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002845 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2846 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002847} *CXCursorVisitorBlock;
2848
2849static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2850 CXClientData client_data) {
2851 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2852 return block->invoke(block, cursor, parent);
2853}
2854#endif
2855
2856
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002857unsigned clang_visitChildrenWithBlock(CXCursor parent,
2858 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002859 return clang_visitChildren(parent, visitWithBlock, block);
2860}
2861
Douglas Gregor78205d42010-01-20 21:45:58 +00002862static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00002863 if (!D)
2864 return createCXString("");
2865
2866 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002867 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002868 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002869 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2870 return createCXString(Property->getIdentifier()->getName());
2871
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002872 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002873 }
2874
Douglas Gregor78205d42010-01-20 21:45:58 +00002875 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002876 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002877
Douglas Gregor78205d42010-01-20 21:45:58 +00002878 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2879 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2880 // and returns different names. NamedDecl returns the class name and
2881 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002882 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002883
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002884 if (isa<UsingDirectiveDecl>(D))
2885 return createCXString("");
2886
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002887 llvm::SmallString<1024> S;
2888 llvm::raw_svector_ostream os(S);
2889 ND->printName(os);
2890
2891 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002892}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002893
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002894CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002895 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002896 return clang_getTranslationUnitSpelling(
2897 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002898
Steve Narofff334b4e2009-09-02 18:26:48 +00002899 if (clang_isReference(C.kind)) {
2900 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002901 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002902 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002903 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002904 }
2905 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002906 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002907 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002908 }
2909 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002910 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002911 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002912 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002913 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002914 case CXCursor_CXXBaseSpecifier: {
2915 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2916 return createCXString(B->getType().getAsString());
2917 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002918 case CXCursor_TypeRef: {
2919 TypeDecl *Type = getCursorTypeRef(C).first;
2920 assert(Type && "Missing type decl");
2921
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002922 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2923 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002924 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002925 case CXCursor_TemplateRef: {
2926 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002927 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002928
2929 return createCXString(Template->getNameAsString());
2930 }
Douglas Gregor69319002010-08-31 23:48:11 +00002931
2932 case CXCursor_NamespaceRef: {
2933 NamedDecl *NS = getCursorNamespaceRef(C).first;
2934 assert(NS && "Missing namespace decl");
2935
2936 return createCXString(NS->getNameAsString());
2937 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002938
Douglas Gregora67e03f2010-09-09 21:42:20 +00002939 case CXCursor_MemberRef: {
2940 FieldDecl *Field = getCursorMemberRef(C).first;
2941 assert(Field && "Missing member decl");
2942
2943 return createCXString(Field->getNameAsString());
2944 }
2945
Douglas Gregor36897b02010-09-10 00:22:18 +00002946 case CXCursor_LabelRef: {
2947 LabelStmt *Label = getCursorLabelRef(C).first;
2948 assert(Label && "Missing label");
2949
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002950 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002951 }
2952
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002953 case CXCursor_OverloadedDeclRef: {
2954 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2955 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2956 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2957 return createCXString(ND->getNameAsString());
2958 return createCXString("");
2959 }
2960 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2961 return createCXString(E->getName().getAsString());
2962 OverloadedTemplateStorage *Ovl
2963 = Storage.get<OverloadedTemplateStorage*>();
2964 if (Ovl->size() == 0)
2965 return createCXString("");
2966 return createCXString((*Ovl->begin())->getNameAsString());
2967 }
2968
Daniel Dunbaracca7252009-11-30 20:42:49 +00002969 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002970 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002971 }
2972 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002973
2974 if (clang_isExpression(C.kind)) {
2975 Decl *D = getDeclFromExpr(getCursorExpr(C));
2976 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002977 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002978 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002979 }
2980
Douglas Gregor36897b02010-09-10 00:22:18 +00002981 if (clang_isStatement(C.kind)) {
2982 Stmt *S = getCursorStmt(C);
2983 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002984 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002985
2986 return createCXString("");
2987 }
2988
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002989 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002990 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002991 ->getNameStart());
2992
Douglas Gregor572feb22010-03-18 18:04:21 +00002993 if (C.kind == CXCursor_MacroDefinition)
2994 return createCXString(getCursorMacroDefinition(C)->getName()
2995 ->getNameStart());
2996
Douglas Gregorecdcb882010-10-20 22:00:55 +00002997 if (C.kind == CXCursor_InclusionDirective)
2998 return createCXString(getCursorInclusionDirective(C)->getFileName());
2999
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003000 if (clang_isDeclaration(C.kind))
3001 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003002
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003003 if (C.kind == CXCursor_AnnotateAttr) {
3004 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3005 return createCXString(AA->getAnnotation());
3006 }
3007
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003008 if (C.kind == CXCursor_AsmLabelAttr) {
3009 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3010 return createCXString(AA->getLabel());
3011 }
3012
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003013 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003014}
3015
Douglas Gregor358559d2010-10-02 22:49:11 +00003016CXString clang_getCursorDisplayName(CXCursor C) {
3017 if (!clang_isDeclaration(C.kind))
3018 return clang_getCursorSpelling(C);
3019
3020 Decl *D = getCursorDecl(C);
3021 if (!D)
3022 return createCXString("");
3023
Douglas Gregor30c42402011-09-27 22:38:19 +00003024 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003025 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3026 D = FunTmpl->getTemplatedDecl();
3027
3028 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3029 llvm::SmallString<64> Str;
3030 llvm::raw_svector_ostream OS(Str);
3031 OS << Function->getNameAsString();
3032 if (Function->getPrimaryTemplate())
3033 OS << "<>";
3034 OS << "(";
3035 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3036 if (I)
3037 OS << ", ";
3038 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3039 }
3040
3041 if (Function->isVariadic()) {
3042 if (Function->getNumParams())
3043 OS << ", ";
3044 OS << "...";
3045 }
3046 OS << ")";
3047 return createCXString(OS.str());
3048 }
3049
3050 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3051 llvm::SmallString<64> Str;
3052 llvm::raw_svector_ostream OS(Str);
3053 OS << ClassTemplate->getNameAsString();
3054 OS << "<";
3055 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3056 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3057 if (I)
3058 OS << ", ";
3059
3060 NamedDecl *Param = Params->getParam(I);
3061 if (Param->getIdentifier()) {
3062 OS << Param->getIdentifier()->getName();
3063 continue;
3064 }
3065
3066 // There is no parameter name, which makes this tricky. Try to come up
3067 // with something useful that isn't too long.
3068 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3069 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3070 else if (NonTypeTemplateParmDecl *NTTP
3071 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3072 OS << NTTP->getType().getAsString(Policy);
3073 else
3074 OS << "template<...> class";
3075 }
3076
3077 OS << ">";
3078 return createCXString(OS.str());
3079 }
3080
3081 if (ClassTemplateSpecializationDecl *ClassSpec
3082 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3083 // If the type was explicitly written, use that.
3084 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3085 return createCXString(TSInfo->getType().getAsString(Policy));
3086
3087 llvm::SmallString<64> Str;
3088 llvm::raw_svector_ostream OS(Str);
3089 OS << ClassSpec->getNameAsString();
3090 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003091 ClassSpec->getTemplateArgs().data(),
3092 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003093 Policy);
3094 return createCXString(OS.str());
3095 }
3096
3097 return clang_getCursorSpelling(C);
3098}
3099
Ted Kremeneke68fff62010-02-17 00:41:32 +00003100CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003101 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003102 case CXCursor_FunctionDecl:
3103 return createCXString("FunctionDecl");
3104 case CXCursor_TypedefDecl:
3105 return createCXString("TypedefDecl");
3106 case CXCursor_EnumDecl:
3107 return createCXString("EnumDecl");
3108 case CXCursor_EnumConstantDecl:
3109 return createCXString("EnumConstantDecl");
3110 case CXCursor_StructDecl:
3111 return createCXString("StructDecl");
3112 case CXCursor_UnionDecl:
3113 return createCXString("UnionDecl");
3114 case CXCursor_ClassDecl:
3115 return createCXString("ClassDecl");
3116 case CXCursor_FieldDecl:
3117 return createCXString("FieldDecl");
3118 case CXCursor_VarDecl:
3119 return createCXString("VarDecl");
3120 case CXCursor_ParmDecl:
3121 return createCXString("ParmDecl");
3122 case CXCursor_ObjCInterfaceDecl:
3123 return createCXString("ObjCInterfaceDecl");
3124 case CXCursor_ObjCCategoryDecl:
3125 return createCXString("ObjCCategoryDecl");
3126 case CXCursor_ObjCProtocolDecl:
3127 return createCXString("ObjCProtocolDecl");
3128 case CXCursor_ObjCPropertyDecl:
3129 return createCXString("ObjCPropertyDecl");
3130 case CXCursor_ObjCIvarDecl:
3131 return createCXString("ObjCIvarDecl");
3132 case CXCursor_ObjCInstanceMethodDecl:
3133 return createCXString("ObjCInstanceMethodDecl");
3134 case CXCursor_ObjCClassMethodDecl:
3135 return createCXString("ObjCClassMethodDecl");
3136 case CXCursor_ObjCImplementationDecl:
3137 return createCXString("ObjCImplementationDecl");
3138 case CXCursor_ObjCCategoryImplDecl:
3139 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003140 case CXCursor_CXXMethod:
3141 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003142 case CXCursor_UnexposedDecl:
3143 return createCXString("UnexposedDecl");
3144 case CXCursor_ObjCSuperClassRef:
3145 return createCXString("ObjCSuperClassRef");
3146 case CXCursor_ObjCProtocolRef:
3147 return createCXString("ObjCProtocolRef");
3148 case CXCursor_ObjCClassRef:
3149 return createCXString("ObjCClassRef");
3150 case CXCursor_TypeRef:
3151 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003152 case CXCursor_TemplateRef:
3153 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003154 case CXCursor_NamespaceRef:
3155 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003156 case CXCursor_MemberRef:
3157 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003158 case CXCursor_LabelRef:
3159 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003160 case CXCursor_OverloadedDeclRef:
3161 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003162 case CXCursor_IntegerLiteral:
3163 return createCXString("IntegerLiteral");
3164 case CXCursor_FloatingLiteral:
3165 return createCXString("FloatingLiteral");
3166 case CXCursor_ImaginaryLiteral:
3167 return createCXString("ImaginaryLiteral");
3168 case CXCursor_StringLiteral:
3169 return createCXString("StringLiteral");
3170 case CXCursor_CharacterLiteral:
3171 return createCXString("CharacterLiteral");
3172 case CXCursor_ParenExpr:
3173 return createCXString("ParenExpr");
3174 case CXCursor_UnaryOperator:
3175 return createCXString("UnaryOperator");
3176 case CXCursor_ArraySubscriptExpr:
3177 return createCXString("ArraySubscriptExpr");
3178 case CXCursor_BinaryOperator:
3179 return createCXString("BinaryOperator");
3180 case CXCursor_CompoundAssignOperator:
3181 return createCXString("CompoundAssignOperator");
3182 case CXCursor_ConditionalOperator:
3183 return createCXString("ConditionalOperator");
3184 case CXCursor_CStyleCastExpr:
3185 return createCXString("CStyleCastExpr");
3186 case CXCursor_CompoundLiteralExpr:
3187 return createCXString("CompoundLiteralExpr");
3188 case CXCursor_InitListExpr:
3189 return createCXString("InitListExpr");
3190 case CXCursor_AddrLabelExpr:
3191 return createCXString("AddrLabelExpr");
3192 case CXCursor_StmtExpr:
3193 return createCXString("StmtExpr");
3194 case CXCursor_GenericSelectionExpr:
3195 return createCXString("GenericSelectionExpr");
3196 case CXCursor_GNUNullExpr:
3197 return createCXString("GNUNullExpr");
3198 case CXCursor_CXXStaticCastExpr:
3199 return createCXString("CXXStaticCastExpr");
3200 case CXCursor_CXXDynamicCastExpr:
3201 return createCXString("CXXDynamicCastExpr");
3202 case CXCursor_CXXReinterpretCastExpr:
3203 return createCXString("CXXReinterpretCastExpr");
3204 case CXCursor_CXXConstCastExpr:
3205 return createCXString("CXXConstCastExpr");
3206 case CXCursor_CXXFunctionalCastExpr:
3207 return createCXString("CXXFunctionalCastExpr");
3208 case CXCursor_CXXTypeidExpr:
3209 return createCXString("CXXTypeidExpr");
3210 case CXCursor_CXXBoolLiteralExpr:
3211 return createCXString("CXXBoolLiteralExpr");
3212 case CXCursor_CXXNullPtrLiteralExpr:
3213 return createCXString("CXXNullPtrLiteralExpr");
3214 case CXCursor_CXXThisExpr:
3215 return createCXString("CXXThisExpr");
3216 case CXCursor_CXXThrowExpr:
3217 return createCXString("CXXThrowExpr");
3218 case CXCursor_CXXNewExpr:
3219 return createCXString("CXXNewExpr");
3220 case CXCursor_CXXDeleteExpr:
3221 return createCXString("CXXDeleteExpr");
3222 case CXCursor_UnaryExpr:
3223 return createCXString("UnaryExpr");
3224 case CXCursor_ObjCStringLiteral:
3225 return createCXString("ObjCStringLiteral");
3226 case CXCursor_ObjCEncodeExpr:
3227 return createCXString("ObjCEncodeExpr");
3228 case CXCursor_ObjCSelectorExpr:
3229 return createCXString("ObjCSelectorExpr");
3230 case CXCursor_ObjCProtocolExpr:
3231 return createCXString("ObjCProtocolExpr");
3232 case CXCursor_ObjCBridgedCastExpr:
3233 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003234 case CXCursor_BlockExpr:
3235 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003236 case CXCursor_PackExpansionExpr:
3237 return createCXString("PackExpansionExpr");
3238 case CXCursor_SizeOfPackExpr:
3239 return createCXString("SizeOfPackExpr");
3240 case CXCursor_UnexposedExpr:
3241 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003242 case CXCursor_DeclRefExpr:
3243 return createCXString("DeclRefExpr");
3244 case CXCursor_MemberRefExpr:
3245 return createCXString("MemberRefExpr");
3246 case CXCursor_CallExpr:
3247 return createCXString("CallExpr");
3248 case CXCursor_ObjCMessageExpr:
3249 return createCXString("ObjCMessageExpr");
3250 case CXCursor_UnexposedStmt:
3251 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003252 case CXCursor_DeclStmt:
3253 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003254 case CXCursor_LabelStmt:
3255 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003256 case CXCursor_CompoundStmt:
3257 return createCXString("CompoundStmt");
3258 case CXCursor_CaseStmt:
3259 return createCXString("CaseStmt");
3260 case CXCursor_DefaultStmt:
3261 return createCXString("DefaultStmt");
3262 case CXCursor_IfStmt:
3263 return createCXString("IfStmt");
3264 case CXCursor_SwitchStmt:
3265 return createCXString("SwitchStmt");
3266 case CXCursor_WhileStmt:
3267 return createCXString("WhileStmt");
3268 case CXCursor_DoStmt:
3269 return createCXString("DoStmt");
3270 case CXCursor_ForStmt:
3271 return createCXString("ForStmt");
3272 case CXCursor_GotoStmt:
3273 return createCXString("GotoStmt");
3274 case CXCursor_IndirectGotoStmt:
3275 return createCXString("IndirectGotoStmt");
3276 case CXCursor_ContinueStmt:
3277 return createCXString("ContinueStmt");
3278 case CXCursor_BreakStmt:
3279 return createCXString("BreakStmt");
3280 case CXCursor_ReturnStmt:
3281 return createCXString("ReturnStmt");
3282 case CXCursor_AsmStmt:
3283 return createCXString("AsmStmt");
3284 case CXCursor_ObjCAtTryStmt:
3285 return createCXString("ObjCAtTryStmt");
3286 case CXCursor_ObjCAtCatchStmt:
3287 return createCXString("ObjCAtCatchStmt");
3288 case CXCursor_ObjCAtFinallyStmt:
3289 return createCXString("ObjCAtFinallyStmt");
3290 case CXCursor_ObjCAtThrowStmt:
3291 return createCXString("ObjCAtThrowStmt");
3292 case CXCursor_ObjCAtSynchronizedStmt:
3293 return createCXString("ObjCAtSynchronizedStmt");
3294 case CXCursor_ObjCAutoreleasePoolStmt:
3295 return createCXString("ObjCAutoreleasePoolStmt");
3296 case CXCursor_ObjCForCollectionStmt:
3297 return createCXString("ObjCForCollectionStmt");
3298 case CXCursor_CXXCatchStmt:
3299 return createCXString("CXXCatchStmt");
3300 case CXCursor_CXXTryStmt:
3301 return createCXString("CXXTryStmt");
3302 case CXCursor_CXXForRangeStmt:
3303 return createCXString("CXXForRangeStmt");
3304 case CXCursor_SEHTryStmt:
3305 return createCXString("SEHTryStmt");
3306 case CXCursor_SEHExceptStmt:
3307 return createCXString("SEHExceptStmt");
3308 case CXCursor_SEHFinallyStmt:
3309 return createCXString("SEHFinallyStmt");
3310 case CXCursor_NullStmt:
3311 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003312 case CXCursor_InvalidFile:
3313 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003314 case CXCursor_InvalidCode:
3315 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003316 case CXCursor_NoDeclFound:
3317 return createCXString("NoDeclFound");
3318 case CXCursor_NotImplemented:
3319 return createCXString("NotImplemented");
3320 case CXCursor_TranslationUnit:
3321 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003322 case CXCursor_UnexposedAttr:
3323 return createCXString("UnexposedAttr");
3324 case CXCursor_IBActionAttr:
3325 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003326 case CXCursor_IBOutletAttr:
3327 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003328 case CXCursor_IBOutletCollectionAttr:
3329 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003330 case CXCursor_CXXFinalAttr:
3331 return createCXString("attribute(final)");
3332 case CXCursor_CXXOverrideAttr:
3333 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003334 case CXCursor_AnnotateAttr:
3335 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003336 case CXCursor_AsmLabelAttr:
3337 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003338 case CXCursor_PreprocessingDirective:
3339 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003340 case CXCursor_MacroDefinition:
3341 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003342 case CXCursor_MacroExpansion:
3343 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003344 case CXCursor_InclusionDirective:
3345 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003346 case CXCursor_Namespace:
3347 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003348 case CXCursor_LinkageSpec:
3349 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003350 case CXCursor_CXXBaseSpecifier:
3351 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003352 case CXCursor_Constructor:
3353 return createCXString("CXXConstructor");
3354 case CXCursor_Destructor:
3355 return createCXString("CXXDestructor");
3356 case CXCursor_ConversionFunction:
3357 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003358 case CXCursor_TemplateTypeParameter:
3359 return createCXString("TemplateTypeParameter");
3360 case CXCursor_NonTypeTemplateParameter:
3361 return createCXString("NonTypeTemplateParameter");
3362 case CXCursor_TemplateTemplateParameter:
3363 return createCXString("TemplateTemplateParameter");
3364 case CXCursor_FunctionTemplate:
3365 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003366 case CXCursor_ClassTemplate:
3367 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003368 case CXCursor_ClassTemplatePartialSpecialization:
3369 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003370 case CXCursor_NamespaceAlias:
3371 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003372 case CXCursor_UsingDirective:
3373 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003374 case CXCursor_UsingDeclaration:
3375 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003376 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003377 return createCXString("TypeAliasDecl");
3378 case CXCursor_ObjCSynthesizeDecl:
3379 return createCXString("ObjCSynthesizeDecl");
3380 case CXCursor_ObjCDynamicDecl:
3381 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003382 case CXCursor_CXXAccessSpecifier:
3383 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003384 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003385
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003386 llvm_unreachable("Unhandled CXCursorKind");
Steve Naroff600866c2009-08-27 19:51:58 +00003387}
Steve Naroff89922f82009-08-31 00:59:03 +00003388
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003389struct GetCursorData {
3390 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003391 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003392 CXCursor &BestCursor;
3393
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003394 GetCursorData(SourceManager &SM,
3395 SourceLocation tokenBegin, CXCursor &outputCursor)
3396 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3397 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3398 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003399};
3400
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003401static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3402 CXCursor parent,
3403 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003404 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3405 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003406
3407 // If we point inside a macro argument we should provide info of what the
3408 // token is so use the actual cursor, don't replace it with a macro expansion
3409 // cursor.
3410 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3411 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003412
3413 if (clang_isDeclaration(cursor.kind)) {
3414 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003415 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003416 if (MD->isImplicit())
3417 return CXChildVisit_Break;
3418 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003419
3420 if (clang_isExpression(cursor.kind) &&
3421 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003422 if (Decl *D = getCursorDecl(*BestCursor)) {
3423 // Avoid having the cursor of an expression replace the declaration cursor
3424 // when the expression source range overlaps the declaration range.
3425 // This can happen for C++ constructor expressions whose range generally
3426 // include the variable declaration, e.g.:
3427 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3428 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3429 D->getLocation() == Data->TokenBeginLoc)
3430 return CXChildVisit_Break;
3431 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003432 }
3433
Douglas Gregor93798e22010-11-05 21:11:19 +00003434 // If our current best cursor is the construction of a temporary object,
3435 // don't replace that cursor with a type reference, because we want
3436 // clang_getCursor() to point at the constructor.
3437 if (clang_isExpression(BestCursor->kind) &&
3438 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003439 cursor.kind == CXCursor_TypeRef) {
3440 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3441 // as having the actual point on the type reference.
3442 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003443 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003444 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003445
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003446 *BestCursor = cursor;
3447 return CXChildVisit_Recurse;
3448}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003449
Douglas Gregorb9790342010-01-22 21:44:22 +00003450CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3451 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003452 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003453
Ted Kremeneka60ed472010-11-16 08:15:36 +00003454 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003455 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3456
Ted Kremeneka297de22010-01-25 22:34:44 +00003457 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003458 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003459
Douglas Gregor40749ee2010-11-03 00:35:38 +00003460 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003461 if (Logging) {
3462 CXFile SearchFile;
3463 unsigned SearchLine, SearchColumn;
3464 CXFile ResultFile;
3465 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003466 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3467 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003468 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3469
Chandler Carruth20174222011-08-31 16:53:37 +00003470 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3471 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3472 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003473 SearchFileName = clang_getFileName(SearchFile);
3474 ResultFileName = clang_getFileName(ResultFile);
3475 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003476 USR = clang_getCursorUSR(Result);
3477 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003478 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3479 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003480 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3481 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003482 clang_disposeString(SearchFileName);
3483 clang_disposeString(ResultFileName);
3484 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003485 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003486
3487 CXCursor Definition = clang_getCursorDefinition(Result);
3488 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3489 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3490 CXString DefinitionKindSpelling
3491 = clang_getCursorKindSpelling(Definition.kind);
3492 CXFile DefinitionFile;
3493 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003494 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3495 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003496 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3497 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3498 clang_getCString(DefinitionKindSpelling),
3499 clang_getCString(DefinitionFileName),
3500 DefinitionLine, DefinitionColumn);
3501 clang_disposeString(DefinitionFileName);
3502 clang_disposeString(DefinitionKindSpelling);
3503 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003504 }
3505
Ted Kremeneke68fff62010-02-17 00:41:32 +00003506 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003507}
3508
Ted Kremenek73885552009-11-17 19:28:59 +00003509CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003510 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003511}
3512
3513unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003514 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003515}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003516
Douglas Gregor9ce55842010-11-20 00:09:34 +00003517unsigned clang_hashCursor(CXCursor C) {
3518 unsigned Index = 0;
3519 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3520 Index = 1;
3521
3522 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3523 std::make_pair(C.kind, C.data[Index]));
3524}
3525
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003526unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003527 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3528}
3529
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003530unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003531 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3532}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003533
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003534unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003535 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3536}
3537
Douglas Gregor97b98722010-01-19 23:20:36 +00003538unsigned clang_isExpression(enum CXCursorKind K) {
3539 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3540}
3541
3542unsigned clang_isStatement(enum CXCursorKind K) {
3543 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3544}
3545
Douglas Gregor8be80e12011-07-06 03:00:34 +00003546unsigned clang_isAttribute(enum CXCursorKind K) {
3547 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3548}
3549
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003550unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3551 return K == CXCursor_TranslationUnit;
3552}
3553
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003554unsigned clang_isPreprocessing(enum CXCursorKind K) {
3555 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3556}
3557
Ted Kremenekad6eff62010-03-08 21:17:29 +00003558unsigned clang_isUnexposed(enum CXCursorKind K) {
3559 switch (K) {
3560 case CXCursor_UnexposedDecl:
3561 case CXCursor_UnexposedExpr:
3562 case CXCursor_UnexposedStmt:
3563 case CXCursor_UnexposedAttr:
3564 return true;
3565 default:
3566 return false;
3567 }
3568}
3569
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003570CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003571 return C.kind;
3572}
3573
Douglas Gregor98258af2010-01-18 22:46:11 +00003574CXSourceLocation clang_getCursorLocation(CXCursor C) {
3575 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003576 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003577 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003578 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3579 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003580 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003581 }
3582
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003583 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003584 std::pair<ObjCProtocolDecl *, SourceLocation> P
3585 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003586 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003587 }
3588
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003589 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003590 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3591 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003592 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003593 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003594
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003595 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003596 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003597 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003598 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003599
3600 case CXCursor_TemplateRef: {
3601 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3602 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3603 }
3604
Douglas Gregor69319002010-08-31 23:48:11 +00003605 case CXCursor_NamespaceRef: {
3606 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3607 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3608 }
3609
Douglas Gregora67e03f2010-09-09 21:42:20 +00003610 case CXCursor_MemberRef: {
3611 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3612 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3613 }
3614
Ted Kremenek3064ef92010-08-27 21:34:58 +00003615 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003616 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3617 if (!BaseSpec)
3618 return clang_getNullLocation();
3619
3620 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3621 return cxloc::translateSourceLocation(getCursorContext(C),
3622 TSInfo->getTypeLoc().getBeginLoc());
3623
3624 return cxloc::translateSourceLocation(getCursorContext(C),
3625 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003626 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003627
Douglas Gregor36897b02010-09-10 00:22:18 +00003628 case CXCursor_LabelRef: {
3629 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3630 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3631 }
3632
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003633 case CXCursor_OverloadedDeclRef:
3634 return cxloc::translateSourceLocation(getCursorContext(C),
3635 getCursorOverloadedDeclRef(C).second);
3636
Douglas Gregorf46034a2010-01-18 23:41:10 +00003637 default:
3638 // FIXME: Need a way to enumerate all non-reference cases.
3639 llvm_unreachable("Missed a reference kind");
3640 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003641 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003642
3643 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003644 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003645 getLocationFromExpr(getCursorExpr(C)));
3646
Douglas Gregor36897b02010-09-10 00:22:18 +00003647 if (clang_isStatement(C.kind))
3648 return cxloc::translateSourceLocation(getCursorContext(C),
3649 getCursorStmt(C)->getLocStart());
3650
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003651 if (C.kind == CXCursor_PreprocessingDirective) {
3652 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3653 return cxloc::translateSourceLocation(getCursorContext(C), L);
3654 }
Douglas Gregor48072312010-03-18 15:23:44 +00003655
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003656 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003657 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003658 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003659 return cxloc::translateSourceLocation(getCursorContext(C), L);
3660 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003661
3662 if (C.kind == CXCursor_MacroDefinition) {
3663 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3664 return cxloc::translateSourceLocation(getCursorContext(C), L);
3665 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003666
3667 if (C.kind == CXCursor_InclusionDirective) {
3668 SourceLocation L
3669 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3670 return cxloc::translateSourceLocation(getCursorContext(C), L);
3671 }
3672
Ted Kremenek9a700d22010-05-12 06:16:13 +00003673 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003674 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003675
Douglas Gregorf46034a2010-01-18 23:41:10 +00003676 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003677 if (!D)
3678 return clang_getNullLocation();
3679
Douglas Gregorf46034a2010-01-18 23:41:10 +00003680 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003681 // FIXME: Multiple variables declared in a single declaration
3682 // currently lack the information needed to correctly determine their
3683 // ranges when accounting for the type-specifier. We use context
3684 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3685 // and if so, whether it is the first decl.
3686 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3687 if (!cxcursor::isFirstInDeclGroup(C))
3688 Loc = VD->getLocation();
3689 }
3690
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003691 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003692}
Douglas Gregora7bde202010-01-19 00:34:46 +00003693
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003694} // end extern "C"
3695
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003696CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3697 assert(TU);
3698
3699 // Guard against an invalid SourceLocation, or we may assert in one
3700 // of the following calls.
3701 if (SLoc.isInvalid())
3702 return clang_getNullCursor();
3703
3704 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3705
3706 // Translate the given source location to make it point at the beginning of
3707 // the token under the cursor.
3708 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3709 CXXUnit->getASTContext().getLangOptions());
3710
3711 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3712 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003713 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003714 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3715 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003716 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003717 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003718 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003719 }
3720
3721 return Result;
3722}
3723
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003724static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003725 if (clang_isReference(C.kind)) {
3726 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003727 case CXCursor_ObjCSuperClassRef:
3728 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003729
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003730 case CXCursor_ObjCProtocolRef:
3731 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003732
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003733 case CXCursor_ObjCClassRef:
3734 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003735
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003736 case CXCursor_TypeRef:
3737 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003738
3739 case CXCursor_TemplateRef:
3740 return getCursorTemplateRef(C).second;
3741
Douglas Gregor69319002010-08-31 23:48:11 +00003742 case CXCursor_NamespaceRef:
3743 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003744
3745 case CXCursor_MemberRef:
3746 return getCursorMemberRef(C).second;
3747
Ted Kremenek3064ef92010-08-27 21:34:58 +00003748 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003749 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003750
Douglas Gregor36897b02010-09-10 00:22:18 +00003751 case CXCursor_LabelRef:
3752 return getCursorLabelRef(C).second;
3753
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003754 case CXCursor_OverloadedDeclRef:
3755 return getCursorOverloadedDeclRef(C).second;
3756
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003757 default:
3758 // FIXME: Need a way to enumerate all non-reference cases.
3759 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003760 }
3761 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003762
3763 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003764 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003765
3766 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003767 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003768
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003769 if (clang_isAttribute(C.kind))
3770 return getCursorAttr(C)->getRange();
3771
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003772 if (C.kind == CXCursor_PreprocessingDirective)
3773 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003774
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003775 if (C.kind == CXCursor_MacroExpansion) {
3776 ASTUnit *TU = getCursorASTUnit(C);
3777 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3778 return TU->mapRangeFromPreamble(Range);
3779 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003780
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003781 if (C.kind == CXCursor_MacroDefinition) {
3782 ASTUnit *TU = getCursorASTUnit(C);
3783 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3784 return TU->mapRangeFromPreamble(Range);
3785 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003786
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003787 if (C.kind == CXCursor_InclusionDirective) {
3788 ASTUnit *TU = getCursorASTUnit(C);
3789 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3790 return TU->mapRangeFromPreamble(Range);
3791 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003792
Ted Kremenek007a7c92010-11-01 23:26:51 +00003793 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3794 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003795 if (!D)
3796 return SourceRange();
3797
Ted Kremenek007a7c92010-11-01 23:26:51 +00003798 SourceRange R = D->getSourceRange();
3799 // FIXME: Multiple variables declared in a single declaration
3800 // currently lack the information needed to correctly determine their
3801 // ranges when accounting for the type-specifier. We use context
3802 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3803 // and if so, whether it is the first decl.
3804 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3805 if (!cxcursor::isFirstInDeclGroup(C))
3806 R.setBegin(VD->getLocation());
3807 }
3808 return R;
3809 }
Douglas Gregor66537982010-11-17 17:14:07 +00003810 return SourceRange();
3811}
3812
3813/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3814/// the decl-specifier-seq for declarations.
3815static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3816 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3817 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003818 if (!D)
3819 return SourceRange();
3820
Douglas Gregor66537982010-11-17 17:14:07 +00003821 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003822
Douglas Gregor2494dd02011-03-01 01:34:45 +00003823 // Adjust the start of the location for declarations preceded by
3824 // declaration specifiers.
3825 SourceLocation StartLoc;
3826 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3827 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3828 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3829 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3830 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3831 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3832 }
3833
3834 if (StartLoc.isValid() && R.getBegin().isValid() &&
3835 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3836 R.setBegin(StartLoc);
3837
3838 // FIXME: Multiple variables declared in a single declaration
3839 // currently lack the information needed to correctly determine their
3840 // ranges when accounting for the type-specifier. We use context
3841 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3842 // and if so, whether it is the first decl.
3843 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3844 if (!cxcursor::isFirstInDeclGroup(C))
3845 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003846 }
3847
3848 return R;
3849 }
3850
3851 return getRawCursorExtent(C);
3852}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003853
3854extern "C" {
3855
3856CXSourceRange clang_getCursorExtent(CXCursor C) {
3857 SourceRange R = getRawCursorExtent(C);
3858 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003859 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003860
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003861 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003862}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003863
3864CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003865 if (clang_isInvalid(C.kind))
3866 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003867
Ted Kremeneka60ed472010-11-16 08:15:36 +00003868 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003869 if (clang_isDeclaration(C.kind)) {
3870 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003871 if (!D)
3872 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003873 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003874 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003875 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003876 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3877 return MakeCXCursor(Property, tu);
3878
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003879 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003880 }
3881
Douglas Gregor97b98722010-01-19 23:20:36 +00003882 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003883 Expr *E = getCursorExpr(C);
3884 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003885 if (D) {
3886 CXCursor declCursor = MakeCXCursor(D, tu);
3887 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3888 declCursor);
3889 return declCursor;
3890 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003891
3892 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003893 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003894
Douglas Gregor97b98722010-01-19 23:20:36 +00003895 return clang_getNullCursor();
3896 }
3897
Douglas Gregor36897b02010-09-10 00:22:18 +00003898 if (clang_isStatement(C.kind)) {
3899 Stmt *S = getCursorStmt(C);
3900 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003901 if (LabelDecl *label = Goto->getLabel())
3902 if (LabelStmt *labelS = label->getStmt())
3903 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003904
3905 return clang_getNullCursor();
3906 }
3907
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003908 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003909 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003910 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003911 }
3912
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003913 if (!clang_isReference(C.kind))
3914 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003915
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003916 switch (C.kind) {
3917 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003918 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003919
3920 case CXCursor_ObjCProtocolRef: {
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00003921 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
3922 if (ObjCProtocolDecl *Def = Prot->getDefinition())
3923 return MakeCXCursor(Def, tu);
3924
3925 CXCursor C = MakeCXCursor(Prot, tu);
3926 C.kind = CXCursor_ObjCProtocolDecl; // override "Unexposed".
3927 return C;
3928 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003929
Douglas Gregor7723fec2011-12-15 20:29:51 +00003930 case CXCursor_ObjCClassRef: {
3931 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3932 if (ObjCInterfaceDecl *Def = Class->getDefinition())
3933 return MakeCXCursor(Def, tu);
3934
Argyrios Kyrtzidis98c16b82012-01-24 19:40:15 +00003935 CXCursor C = MakeCXCursor(Class, tu);
3936 C.kind = CXCursor_ObjCInterfaceDecl; // override "Unexposed".
3937 return C;
Douglas Gregor7723fec2011-12-15 20:29:51 +00003938 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003939
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003940 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003941 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003942
3943 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003944 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003945
Douglas Gregor69319002010-08-31 23:48:11 +00003946 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003947 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003948
Douglas Gregora67e03f2010-09-09 21:42:20 +00003949 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003950 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003951
Ted Kremenek3064ef92010-08-27 21:34:58 +00003952 case CXCursor_CXXBaseSpecifier: {
3953 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3954 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003955 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003956 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003957
Douglas Gregor36897b02010-09-10 00:22:18 +00003958 case CXCursor_LabelRef:
3959 // FIXME: We end up faking the "parent" declaration here because we
3960 // don't want to make CXCursor larger.
3961 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003962 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3963 .getTranslationUnitDecl(),
3964 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003965
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003966 case CXCursor_OverloadedDeclRef:
3967 return C;
3968
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003969 default:
3970 // We would prefer to enumerate all non-reference cursor kinds here.
3971 llvm_unreachable("Unhandled reference cursor kind");
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003972 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003973}
3974
Douglas Gregorb6998662010-01-19 19:34:47 +00003975CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003976 if (clang_isInvalid(C.kind))
3977 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003978
Ted Kremeneka60ed472010-11-16 08:15:36 +00003979 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003980
Douglas Gregorb6998662010-01-19 19:34:47 +00003981 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003982 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003983 C = clang_getCursorReferenced(C);
3984 WasReference = true;
3985 }
3986
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003987 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003988 return clang_getCursorReferenced(C);
3989
Douglas Gregorb6998662010-01-19 19:34:47 +00003990 if (!clang_isDeclaration(C.kind))
3991 return clang_getNullCursor();
3992
3993 Decl *D = getCursorDecl(C);
3994 if (!D)
3995 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003996
Douglas Gregorb6998662010-01-19 19:34:47 +00003997 switch (D->getKind()) {
3998 // Declaration kinds that don't really separate the notions of
3999 // declaration and definition.
4000 case Decl::Namespace:
4001 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004002 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004003 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004004 case Decl::TemplateTypeParm:
4005 case Decl::EnumConstant:
4006 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004007 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004008 case Decl::ObjCIvar:
4009 case Decl::ObjCAtDefsField:
4010 case Decl::ImplicitParam:
4011 case Decl::ParmVar:
4012 case Decl::NonTypeTemplateParm:
4013 case Decl::TemplateTemplateParm:
4014 case Decl::ObjCCategoryImpl:
4015 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004016 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004017 case Decl::LinkageSpec:
4018 case Decl::ObjCPropertyImpl:
4019 case Decl::FileScopeAsm:
4020 case Decl::StaticAssert:
4021 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004022 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004023 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004024 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004025 return C;
4026
4027 // Declaration kinds that don't make any sense here, but are
4028 // nonetheless harmless.
4029 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004030 break;
4031
4032 // Declaration kinds for which the definition is not resolvable.
4033 case Decl::UnresolvedUsingTypename:
4034 case Decl::UnresolvedUsingValue:
4035 break;
4036
4037 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004038 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004039 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004040
4041 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004042 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004043
4044 case Decl::Enum:
4045 case Decl::Record:
4046 case Decl::CXXRecord:
4047 case Decl::ClassTemplateSpecialization:
4048 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004049 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004050 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004051 return clang_getNullCursor();
4052
4053 case Decl::Function:
4054 case Decl::CXXMethod:
4055 case Decl::CXXConstructor:
4056 case Decl::CXXDestructor:
4057 case Decl::CXXConversion: {
4058 const FunctionDecl *Def = 0;
4059 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004060 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004061 return clang_getNullCursor();
4062 }
4063
4064 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004065 // Ask the variable if it has a definition.
4066 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004067 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004068 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004069 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004070
Douglas Gregorb6998662010-01-19 19:34:47 +00004071 case Decl::FunctionTemplate: {
4072 const FunctionDecl *Def = 0;
4073 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004074 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004075 return clang_getNullCursor();
4076 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004077
Douglas Gregorb6998662010-01-19 19:34:47 +00004078 case Decl::ClassTemplate: {
4079 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004080 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004081 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004083 return clang_getNullCursor();
4084 }
4085
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004086 case Decl::Using:
4087 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004088 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004089
4090 case Decl::UsingShadow:
4091 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004092 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004093 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004094
4095 case Decl::ObjCMethod: {
4096 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4097 if (Method->isThisDeclarationADefinition())
4098 return C;
4099
4100 // Dig out the method definition in the associated
4101 // @implementation, if we have it.
4102 // FIXME: The ASTs should make finding the definition easier.
4103 if (ObjCInterfaceDecl *Class
4104 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4105 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4106 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4107 Method->isInstanceMethod()))
4108 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004109 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004110
4111 return clang_getNullCursor();
4112 }
4113
4114 case Decl::ObjCCategory:
4115 if (ObjCCategoryImplDecl *Impl
4116 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004117 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004118 return clang_getNullCursor();
4119
4120 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004121 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4122 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004123 return clang_getNullCursor();
4124
Douglas Gregor375bb142011-12-27 22:43:10 +00004125 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004126 // There are two notions of a "definition" for an Objective-C
4127 // class: the interface and its implementation. When we resolved a
4128 // reference to an Objective-C class, produce the @interface as
4129 // the definition; when we were provided with the interface,
4130 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004131 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004132 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004133 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004134 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004135 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004136 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004137 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004138 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004139
Douglas Gregorb6998662010-01-19 19:34:47 +00004140 case Decl::ObjCProperty:
4141 // FIXME: We don't really know where to find the
4142 // ObjCPropertyImplDecls that implement this property.
4143 return clang_getNullCursor();
4144
4145 case Decl::ObjCCompatibleAlias:
4146 if (ObjCInterfaceDecl *Class
4147 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004148 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4149 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004150
Douglas Gregorb6998662010-01-19 19:34:47 +00004151 return clang_getNullCursor();
4152
Douglas Gregorb6998662010-01-19 19:34:47 +00004153 case Decl::Friend:
4154 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004155 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004156 return clang_getNullCursor();
4157
4158 case Decl::FriendTemplate:
4159 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004160 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004161 return clang_getNullCursor();
4162 }
4163
4164 return clang_getNullCursor();
4165}
4166
4167unsigned clang_isCursorDefinition(CXCursor C) {
4168 if (!clang_isDeclaration(C.kind))
4169 return 0;
4170
4171 return clang_getCursorDefinition(C) == C;
4172}
4173
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004174CXCursor clang_getCanonicalCursor(CXCursor C) {
4175 if (!clang_isDeclaration(C.kind))
4176 return C;
4177
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004178 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004179 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4180 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4181 return MakeCXCursor(CatD, getCursorTU(C));
4182
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004183 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4184 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4185 return MakeCXCursor(IFD, getCursorTU(C));
4186
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004187 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004188 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004189
4190 return C;
4191}
4192
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004193unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004194 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004195 return 0;
4196
4197 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4198 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4199 return E->getNumDecls();
4200
4201 if (OverloadedTemplateStorage *S
4202 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4203 return S->size();
4204
4205 Decl *D = Storage.get<Decl*>();
4206 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004207 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004208
4209 return 0;
4210}
4211
4212CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004213 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004214 return clang_getNullCursor();
4215
4216 if (index >= clang_getNumOverloadedDecls(cursor))
4217 return clang_getNullCursor();
4218
Ted Kremeneka60ed472010-11-16 08:15:36 +00004219 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004220 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4221 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004222 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004223
4224 if (OverloadedTemplateStorage *S
4225 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004226 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004227
4228 Decl *D = Storage.get<Decl*>();
4229 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4230 // FIXME: This is, unfortunately, linear time.
4231 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4232 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004233 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004234 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004235
4236 return clang_getNullCursor();
4237}
4238
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004239void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004240 const char **startBuf,
4241 const char **endBuf,
4242 unsigned *startLine,
4243 unsigned *startColumn,
4244 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004245 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004246 assert(getCursorDecl(C) && "CXCursor has null decl");
4247 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004248 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4249 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004250
Steve Naroff4ade6d62009-09-23 17:52:52 +00004251 SourceManager &SM = FD->getASTContext().getSourceManager();
4252 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4253 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4254 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4255 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4256 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4257 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4258}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004259
Douglas Gregor430d7a12011-07-25 17:48:11 +00004260
4261CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4262 unsigned PieceIndex) {
4263 RefNamePieces Pieces;
4264
4265 switch (C.kind) {
4266 case CXCursor_MemberRefExpr:
4267 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4268 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4269 E->getQualifierLoc().getSourceRange());
4270 break;
4271
4272 case CXCursor_DeclRefExpr:
4273 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4274 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4275 E->getQualifierLoc().getSourceRange(),
4276 E->getExplicitTemplateArgsOpt());
4277 break;
4278
4279 case CXCursor_CallExpr:
4280 if (CXXOperatorCallExpr *OCE =
4281 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4282 Expr *Callee = OCE->getCallee();
4283 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4284 Callee = ICE->getSubExpr();
4285
4286 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4287 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4288 DRE->getQualifierLoc().getSourceRange());
4289 }
4290 break;
4291
4292 default:
4293 break;
4294 }
4295
4296 if (Pieces.empty()) {
4297 if (PieceIndex == 0)
4298 return clang_getCursorExtent(C);
4299 } else if (PieceIndex < Pieces.size()) {
4300 SourceRange R = Pieces[PieceIndex];
4301 if (R.isValid())
4302 return cxloc::translateSourceRange(getCursorContext(C), R);
4303 }
4304
4305 return clang_getNullRange();
4306}
4307
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004308void clang_enableStackTraces(void) {
4309 llvm::sys::PrintStackTraceOnErrorSignal();
4310}
4311
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004312void clang_executeOnThread(void (*fn)(void*), void *user_data,
4313 unsigned stack_size) {
4314 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4315}
4316
Ted Kremenekfb480492010-01-13 21:46:36 +00004317} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004318
Ted Kremenekfb480492010-01-13 21:46:36 +00004319//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004320// Token-based Operations.
4321//===----------------------------------------------------------------------===//
4322
4323/* CXToken layout:
4324 * int_data[0]: a CXTokenKind
4325 * int_data[1]: starting token location
4326 * int_data[2]: token length
4327 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004328 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004329 * otherwise unused.
4330 */
4331extern "C" {
4332
4333CXTokenKind clang_getTokenKind(CXToken CXTok) {
4334 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4335}
4336
4337CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4338 switch (clang_getTokenKind(CXTok)) {
4339 case CXToken_Identifier:
4340 case CXToken_Keyword:
4341 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004342 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4343 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004344
4345 case CXToken_Literal: {
4346 // We have stashed the starting pointer in the ptr_data field. Use it.
4347 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004348 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004349 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004350
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004351 case CXToken_Punctuation:
4352 case CXToken_Comment:
4353 break;
4354 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004355
4356 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004357 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004358 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004359 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004360 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004361
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004362 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4363 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004364 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004365 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004366 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004367 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4368 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004369 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004370
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004371 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004372}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004373
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004374CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004375 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004376 if (!CXXUnit)
4377 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004378
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004379 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4380 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4381}
4382
4383CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004384 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004385 if (!CXXUnit)
4386 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004387
4388 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004389 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4390}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004391
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004392static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4393 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004394 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4395 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004396 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004397 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004398 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004399
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004400 // Cannot tokenize across files.
4401 if (BeginLocInfo.first != EndLocInfo.first)
4402 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004403
4404 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004405 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004406 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004407 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004408 if (Invalid)
4409 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004410
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004411 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4412 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004413 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004414 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004415
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004416 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004417 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004418 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004419 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004420 do {
4421 // Lex the next token
4422 Lex.LexFromRawLexer(Tok);
4423 if (Tok.is(tok::eof))
4424 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004425
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004426 // Initialize the CXToken.
4427 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004428
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004429 // - Common fields
4430 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4431 CXTok.int_data[2] = Tok.getLength();
4432 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004433
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004434 // - Kind-specific fields
4435 if (Tok.isLiteral()) {
4436 CXTok.int_data[0] = CXToken_Literal;
4437 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004438 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004439 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004440 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004441 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004442
David Chisnall096428b2010-10-13 21:44:48 +00004443 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004444 CXTok.int_data[0] = CXToken_Keyword;
4445 }
4446 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004447 CXTok.int_data[0] = Tok.is(tok::identifier)
4448 ? CXToken_Identifier
4449 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004450 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004451 CXTok.ptr_data = II;
4452 } else if (Tok.is(tok::comment)) {
4453 CXTok.int_data[0] = CXToken_Comment;
4454 CXTok.ptr_data = 0;
4455 } else {
4456 CXTok.int_data[0] = CXToken_Punctuation;
4457 CXTok.ptr_data = 0;
4458 }
4459 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004460 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004461 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004462}
4463
4464void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4465 CXToken **Tokens, unsigned *NumTokens) {
4466 if (Tokens)
4467 *Tokens = 0;
4468 if (NumTokens)
4469 *NumTokens = 0;
4470
4471 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4472 if (!CXXUnit || !Tokens || !NumTokens)
4473 return;
4474
4475 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4476
4477 SourceRange R = cxloc::translateCXSourceRange(Range);
4478 if (R.isInvalid())
4479 return;
4480
4481 SmallVector<CXToken, 32> CXTokens;
4482 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004483
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004484 if (CXTokens.empty())
4485 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004486
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004487 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4488 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4489 *NumTokens = CXTokens.size();
4490}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004491
Ted Kremenek6db61092010-05-05 00:55:15 +00004492void clang_disposeTokens(CXTranslationUnit TU,
4493 CXToken *Tokens, unsigned NumTokens) {
4494 free(Tokens);
4495}
4496
4497} // end: extern "C"
4498
4499//===----------------------------------------------------------------------===//
4500// Token annotation APIs.
4501//===----------------------------------------------------------------------===//
4502
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004503typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004504static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4505 CXCursor parent,
4506 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004507namespace {
4508class AnnotateTokensWorker {
4509 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004510 CXToken *Tokens;
4511 CXCursor *Cursors;
4512 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004513 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004514 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004515 CursorVisitor AnnotateVis;
4516 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004517 bool HasContextSensitiveKeywords;
4518
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004519 bool MoreTokens() const { return TokIdx < NumTokens; }
4520 unsigned NextToken() const { return TokIdx; }
4521 void AdvanceToken() { ++TokIdx; }
4522 SourceLocation GetTokenLoc(unsigned tokI) {
4523 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4524 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004525 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004526 return Tokens[tokI].int_data[3] != 0;
4527 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004528 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004529 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4530 }
4531
4532 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004533 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4534 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004535
Ted Kremenek6db61092010-05-05 00:55:15 +00004536public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004537 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004538 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004539 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004540 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004541 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004542 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004543 AnnotateTokensVisitor, this,
4544 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004545 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004546 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004547 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4548 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004549
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004550 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004551 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004552 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004553
4554 /// \brief Determine whether the annotator saw any cursors that have
4555 /// context-sensitive keywords.
4556 bool hasContextSensitiveKeywords() const {
4557 return HasContextSensitiveKeywords;
4558 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004559};
4560}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004561
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004562void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004563 // Walk the AST within the region of interest, annotating tokens
4564 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004565 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004566
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004567 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4568 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004569 if (Pos != Annotated.end() &&
4570 (clang_isInvalid(Cursors[I].kind) ||
4571 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004572 Cursors[I] = Pos->second;
4573 }
4574
4575 // Finish up annotating any tokens left.
4576 if (!MoreTokens())
4577 return;
4578
4579 const CXCursor &C = clang_getNullCursor();
4580 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004581 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4582 continue;
4583
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004584 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4585 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004586 }
4587}
4588
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004589/// \brief It annotates and advances tokens with a cursor until the comparison
4590//// between the cursor location and the source range is the same as
4591/// \arg compResult.
4592///
4593/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4594/// Pass RangeOverlap to annotate tokens inside a range.
4595void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4596 RangeComparisonResult compResult,
4597 SourceRange range) {
4598 while (MoreTokens()) {
4599 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004600 if (isFunctionMacroToken(I))
4601 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004602
4603 SourceLocation TokLoc = GetTokenLoc(I);
4604 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4605 Cursors[I] = updateC;
4606 AdvanceToken();
4607 continue;
4608 }
4609 break;
4610 }
4611}
4612
4613/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004614void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4615 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004616 RangeComparisonResult compResult,
4617 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004618 assert(MoreTokens());
4619 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004620 "Should be called only for macro arg tokens");
4621
4622 // This works differently than annotateAndAdvanceTokens; because expanded
4623 // macro arguments can have arbitrary translation-unit source order, we do not
4624 // advance the token index one by one until a token fails the range test.
4625 // We only advance once past all of the macro arg tokens if all of them
4626 // pass the range test. If one of them fails we keep the token index pointing
4627 // at the start of the macro arg tokens so that the failing token will be
4628 // annotated by a subsequent annotation try.
4629
4630 bool atLeastOneCompFail = false;
4631
4632 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004633 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4634 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004635 if (TokLoc.isFileID())
4636 continue; // not macro arg token, it's parens or comma.
4637 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4638 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4639 Cursors[I] = updateC;
4640 } else
4641 atLeastOneCompFail = true;
4642 }
4643
4644 if (!atLeastOneCompFail)
4645 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4646}
4647
Ted Kremenek6db61092010-05-05 00:55:15 +00004648enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004649AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004650 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004651 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004652 if (cursorRange.isInvalid())
4653 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004654
4655 if (!HasContextSensitiveKeywords) {
4656 // Objective-C properties can have context-sensitive keywords.
4657 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4658 if (ObjCPropertyDecl *Property
4659 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4660 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4661 }
4662 // Objective-C methods can have context-sensitive keywords.
4663 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4664 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4665 if (ObjCMethodDecl *Method
4666 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4667 if (Method->getObjCDeclQualifier())
4668 HasContextSensitiveKeywords = true;
4669 else {
4670 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4671 PEnd = Method->param_end();
4672 P != PEnd; ++P) {
4673 if ((*P)->getObjCDeclQualifier()) {
4674 HasContextSensitiveKeywords = true;
4675 break;
4676 }
4677 }
4678 }
4679 }
4680 }
4681 // C++ methods can have context-sensitive keywords.
4682 else if (cursor.kind == CXCursor_CXXMethod) {
4683 if (CXXMethodDecl *Method
4684 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4685 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4686 HasContextSensitiveKeywords = true;
4687 }
4688 }
4689 // C++ classes can have context-sensitive keywords.
4690 else if (cursor.kind == CXCursor_StructDecl ||
4691 cursor.kind == CXCursor_ClassDecl ||
4692 cursor.kind == CXCursor_ClassTemplate ||
4693 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4694 if (Decl *D = getCursorDecl(cursor))
4695 if (D->hasAttr<FinalAttr>())
4696 HasContextSensitiveKeywords = true;
4697 }
4698 }
4699
Douglas Gregor4419b672010-10-21 06:10:04 +00004700 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004701 // For macro expansions, just note where the beginning of the macro
4702 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004703 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004704 Annotated[Loc.int_data] = cursor;
4705 return CXChildVisit_Recurse;
4706 }
4707
Douglas Gregor4419b672010-10-21 06:10:04 +00004708 // Items in the preprocessing record are kept separate from items in
4709 // declarations, so we keep a separate token index.
4710 unsigned SavedTokIdx = TokIdx;
4711 TokIdx = PreprocessingTokIdx;
4712
4713 // Skip tokens up until we catch up to the beginning of the preprocessing
4714 // entry.
4715 while (MoreTokens()) {
4716 const unsigned I = NextToken();
4717 SourceLocation TokLoc = GetTokenLoc(I);
4718 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4719 case RangeBefore:
4720 AdvanceToken();
4721 continue;
4722 case RangeAfter:
4723 case RangeOverlap:
4724 break;
4725 }
4726 break;
4727 }
4728
4729 // Look at all of the tokens within this range.
4730 while (MoreTokens()) {
4731 const unsigned I = NextToken();
4732 SourceLocation TokLoc = GetTokenLoc(I);
4733 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4734 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004735 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004736 case RangeAfter:
4737 break;
4738 case RangeOverlap:
4739 Cursors[I] = cursor;
4740 AdvanceToken();
4741 continue;
4742 }
4743 break;
4744 }
4745
4746 // Save the preprocessing token index; restore the non-preprocessing
4747 // token index.
4748 PreprocessingTokIdx = TokIdx;
4749 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004750 return CXChildVisit_Recurse;
4751 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004752
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004753 if (cursorRange.isInvalid())
4754 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004755
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004756 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4757
Ted Kremeneka333c662010-05-12 05:29:33 +00004758 // Adjust the annotated range based specific declarations.
4759 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4760 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004761 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004762
4763 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004764 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004765 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4766 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004767 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004768 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4769 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004770 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004771
4772 if (StartLoc.isValid() && L.isValid() &&
4773 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4774 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004775 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004776
Ted Kremenek3f404602010-08-14 01:14:06 +00004777 // If the location of the cursor occurs within a macro instantiation, record
4778 // the spelling location of the cursor in our annotation map. We can then
4779 // paper over the token labelings during a post-processing step to try and
4780 // get cursor mappings for tokens that are the *arguments* of a macro
4781 // instantiation.
4782 if (L.isMacroID()) {
4783 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4784 // Only invalidate the old annotation if it isn't part of a preprocessing
4785 // directive. Here we assume that the default construction of CXCursor
4786 // results in CXCursor.kind being an initialized value (i.e., 0). If
4787 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004788
Ted Kremenek3f404602010-08-14 01:14:06 +00004789 CXCursor &oldC = Annotated[rawEncoding];
4790 if (!clang_isPreprocessing(oldC.kind))
4791 oldC = cursor;
4792 }
4793
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004794 const enum CXCursorKind K = clang_getCursorKind(parent);
4795 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004796 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4797 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004798
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004799 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004800
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004801 // Avoid having the cursor of an expression "overwrite" the annotation of the
4802 // variable declaration that it belongs to.
4803 // This can happen for C++ constructor expressions whose range generally
4804 // include the variable declaration, e.g.:
4805 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4806 if (clang_isExpression(cursorK)) {
4807 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004808 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004809 const unsigned I = NextToken();
4810 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4811 E->getLocStart() == D->getLocation() &&
4812 E->getLocStart() == GetTokenLoc(I)) {
4813 Cursors[I] = updateC;
4814 AdvanceToken();
4815 }
4816 }
4817 }
4818
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004819 // Visit children to get their cursor information.
4820 const unsigned BeforeChildren = NextToken();
4821 VisitChildren(cursor);
4822 const unsigned AfterChildren = NextToken();
4823
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004824 // Scan the tokens that are at the end of the cursor, but are not captured
4825 // but the child cursors.
4826 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004827
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004828 // Scan the tokens that are at the beginning of the cursor, but are not
4829 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004830 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4831 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4832 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004833
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004834 Cursors[I] = cursor;
4835 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004836
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004837 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004838}
4839
Ted Kremenek6db61092010-05-05 00:55:15 +00004840static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4841 CXCursor parent,
4842 CXClientData client_data) {
4843 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4844}
4845
Ted Kremenek6628a612011-03-18 22:51:30 +00004846namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004847
4848/// \brief Uses the macro expansions in the preprocessing record to find
4849/// and mark tokens that are macro arguments. This info is used by the
4850/// AnnotateTokensWorker.
4851class MarkMacroArgTokensVisitor {
4852 SourceManager &SM;
4853 CXToken *Tokens;
4854 unsigned NumTokens;
4855 unsigned CurIdx;
4856
4857public:
4858 MarkMacroArgTokensVisitor(SourceManager &SM,
4859 CXToken *tokens, unsigned numTokens)
4860 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4861
4862 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4863 if (cursor.kind != CXCursor_MacroExpansion)
4864 return CXChildVisit_Continue;
4865
4866 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4867 if (macroRange.getBegin() == macroRange.getEnd())
4868 return CXChildVisit_Continue; // it's not a function macro.
4869
4870 for (; CurIdx < NumTokens; ++CurIdx) {
4871 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4872 macroRange.getBegin()))
4873 break;
4874 }
4875
4876 if (CurIdx == NumTokens)
4877 return CXChildVisit_Break;
4878
4879 for (; CurIdx < NumTokens; ++CurIdx) {
4880 SourceLocation tokLoc = getTokenLoc(CurIdx);
4881 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4882 break;
4883
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004884 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004885 }
4886
4887 if (CurIdx == NumTokens)
4888 return CXChildVisit_Break;
4889
4890 return CXChildVisit_Continue;
4891 }
4892
4893private:
4894 SourceLocation getTokenLoc(unsigned tokI) {
4895 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4896 }
4897
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004898 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004899 // The third field is reserved and currently not used. Use it here
4900 // to mark macro arg expanded tokens with their expanded locations.
4901 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4902 }
4903};
4904
4905} // end anonymous namespace
4906
4907static CXChildVisitResult
4908MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4909 CXClientData client_data) {
4910 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4911 parent);
4912}
4913
4914namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004915 struct clang_annotateTokens_Data {
4916 CXTranslationUnit TU;
4917 ASTUnit *CXXUnit;
4918 CXToken *Tokens;
4919 unsigned NumTokens;
4920 CXCursor *Cursors;
4921 };
4922}
4923
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004924static void annotatePreprocessorTokens(CXTranslationUnit TU,
4925 SourceRange RegionOfInterest,
4926 AnnotateTokensData &Annotated) {
4927 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4928
4929 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4930 std::pair<FileID, unsigned> BeginLocInfo
4931 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4932 std::pair<FileID, unsigned> EndLocInfo
4933 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4934
4935 if (BeginLocInfo.first != EndLocInfo.first)
4936 return;
4937
4938 StringRef Buffer;
4939 bool Invalid = false;
4940 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4941 if (Buffer.empty() || Invalid)
4942 return;
4943
4944 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4945 CXXUnit->getASTContext().getLangOptions(),
4946 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4947 Buffer.end());
4948 Lex.SetCommentRetentionState(true);
4949
4950 // Lex tokens in raw mode until we hit the end of the range, to avoid
4951 // entering #includes or expanding macros.
4952 while (true) {
4953 Token Tok;
4954 Lex.LexFromRawLexer(Tok);
4955
4956 reprocess:
4957 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4958 // We have found a preprocessing directive. Gobble it up so that we
4959 // don't see it while preprocessing these tokens later, but keep track
4960 // of all of the token locations inside this preprocessing directive so
4961 // that we can annotate them appropriately.
4962 //
4963 // FIXME: Some simple tests here could identify macro definitions and
4964 // #undefs, to provide specific cursor kinds for those.
4965 SmallVector<SourceLocation, 32> Locations;
4966 do {
4967 Locations.push_back(Tok.getLocation());
4968 Lex.LexFromRawLexer(Tok);
4969 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4970
4971 using namespace cxcursor;
4972 CXCursor Cursor
4973 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4974 Locations.back()),
4975 TU);
4976 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4977 Annotated[Locations[I].getRawEncoding()] = Cursor;
4978 }
4979
4980 if (Tok.isAtStartOfLine())
4981 goto reprocess;
4982
4983 continue;
4984 }
4985
4986 if (Tok.is(tok::eof))
4987 break;
4988 }
4989}
4990
Ted Kremenekab979612010-11-11 08:05:23 +00004991// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004992static void clang_annotateTokensImpl(void *UserData) {
4993 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4994 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4995 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4996 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4997 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4998
4999 // Determine the region of interest, which contains all of the tokens.
5000 SourceRange RegionOfInterest;
5001 RegionOfInterest.setBegin(
5002 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5003 RegionOfInterest.setEnd(
5004 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5005 Tokens[NumTokens-1])));
5006
5007 // A mapping from the source locations found when re-lexing or traversing the
5008 // region of interest to the corresponding cursors.
5009 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005010
Ted Kremenek6628a612011-03-18 22:51:30 +00005011 // Relex the tokens within the source range to look for preprocessing
5012 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005013 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005014
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005015 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5016 // Search and mark tokens that are macro argument expansions.
5017 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5018 Tokens, NumTokens);
5019 CursorVisitor MacroArgMarker(TU,
5020 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005021 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005022 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005023 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005024 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5025 }
5026
Ted Kremenek6628a612011-03-18 22:51:30 +00005027 // Annotate all of the source locations in the region of interest that map to
5028 // a specific cursor.
5029 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5030 TU, RegionOfInterest);
5031
5032 // FIXME: We use a ridiculous stack size here because the data-recursion
5033 // algorithm uses a large stack frame than the non-data recursive version,
5034 // and AnnotationTokensWorker currently transforms the data-recursion
5035 // algorithm back into a traditional recursion by explicitly calling
5036 // VisitChildren(). We will need to remove this explicit recursive call.
5037 W.AnnotateTokens();
5038
5039 // If we ran into any entities that involve context-sensitive keywords,
5040 // take another pass through the tokens to mark them as such.
5041 if (W.hasContextSensitiveKeywords()) {
5042 for (unsigned I = 0; I != NumTokens; ++I) {
5043 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5044 continue;
5045
5046 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5047 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5048 if (ObjCPropertyDecl *Property
5049 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5050 if (Property->getPropertyAttributesAsWritten() != 0 &&
5051 llvm::StringSwitch<bool>(II->getName())
5052 .Case("readonly", true)
5053 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005054 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005055 .Case("readwrite", true)
5056 .Case("retain", true)
5057 .Case("copy", true)
5058 .Case("nonatomic", true)
5059 .Case("atomic", true)
5060 .Case("getter", true)
5061 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005062 .Case("strong", true)
5063 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005064 .Default(false))
5065 Tokens[I].int_data[0] = CXToken_Keyword;
5066 }
5067 continue;
5068 }
5069
5070 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5071 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5072 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5073 if (llvm::StringSwitch<bool>(II->getName())
5074 .Case("in", true)
5075 .Case("out", true)
5076 .Case("inout", true)
5077 .Case("oneway", true)
5078 .Case("bycopy", true)
5079 .Case("byref", true)
5080 .Default(false))
5081 Tokens[I].int_data[0] = CXToken_Keyword;
5082 continue;
5083 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005084
5085 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5086 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5087 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005088 continue;
5089 }
5090 }
5091 }
Ted Kremenekab979612010-11-11 08:05:23 +00005092}
5093
Ted Kremenek6db61092010-05-05 00:55:15 +00005094extern "C" {
5095
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005096void clang_annotateTokens(CXTranslationUnit TU,
5097 CXToken *Tokens, unsigned NumTokens,
5098 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005099
5100 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005101 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005102
Douglas Gregor4419b672010-10-21 06:10:04 +00005103 // Any token we don't specifically annotate will have a NULL cursor.
5104 CXCursor C = clang_getNullCursor();
5105 for (unsigned I = 0; I != NumTokens; ++I)
5106 Cursors[I] = C;
5107
Ted Kremeneka60ed472010-11-16 08:15:36 +00005108 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005109 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005110 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005111
Douglas Gregorbdf60622010-03-05 21:16:25 +00005112 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005113
5114 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005115 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005116 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005117 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005118 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5119 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005120}
Ted Kremenek6628a612011-03-18 22:51:30 +00005121
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005122} // end: extern "C"
5123
5124//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005125// Operations for querying linkage of a cursor.
5126//===----------------------------------------------------------------------===//
5127
5128extern "C" {
5129CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005130 if (!clang_isDeclaration(cursor.kind))
5131 return CXLinkage_Invalid;
5132
Ted Kremenek16b42592010-03-03 06:36:57 +00005133 Decl *D = cxcursor::getCursorDecl(cursor);
5134 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5135 switch (ND->getLinkage()) {
5136 case NoLinkage: return CXLinkage_NoLinkage;
5137 case InternalLinkage: return CXLinkage_Internal;
5138 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5139 case ExternalLinkage: return CXLinkage_External;
5140 };
5141
5142 return CXLinkage_Invalid;
5143}
5144} // end: extern "C"
5145
5146//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005147// Operations for querying language of a cursor.
5148//===----------------------------------------------------------------------===//
5149
5150static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005151 if (!D)
5152 return CXLanguage_C;
5153
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005154 switch (D->getKind()) {
5155 default:
5156 break;
5157 case Decl::ImplicitParam:
5158 case Decl::ObjCAtDefsField:
5159 case Decl::ObjCCategory:
5160 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005161 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005162 case Decl::ObjCImplementation:
5163 case Decl::ObjCInterface:
5164 case Decl::ObjCIvar:
5165 case Decl::ObjCMethod:
5166 case Decl::ObjCProperty:
5167 case Decl::ObjCPropertyImpl:
5168 case Decl::ObjCProtocol:
5169 return CXLanguage_ObjC;
5170 case Decl::CXXConstructor:
5171 case Decl::CXXConversion:
5172 case Decl::CXXDestructor:
5173 case Decl::CXXMethod:
5174 case Decl::CXXRecord:
5175 case Decl::ClassTemplate:
5176 case Decl::ClassTemplatePartialSpecialization:
5177 case Decl::ClassTemplateSpecialization:
5178 case Decl::Friend:
5179 case Decl::FriendTemplate:
5180 case Decl::FunctionTemplate:
5181 case Decl::LinkageSpec:
5182 case Decl::Namespace:
5183 case Decl::NamespaceAlias:
5184 case Decl::NonTypeTemplateParm:
5185 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005186 case Decl::TemplateTemplateParm:
5187 case Decl::TemplateTypeParm:
5188 case Decl::UnresolvedUsingTypename:
5189 case Decl::UnresolvedUsingValue:
5190 case Decl::Using:
5191 case Decl::UsingDirective:
5192 case Decl::UsingShadow:
5193 return CXLanguage_CPlusPlus;
5194 }
5195
5196 return CXLanguage_C;
5197}
5198
5199extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005200
5201enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5202 if (clang_isDeclaration(cursor.kind))
5203 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005204 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005205 return CXAvailability_Available;
5206
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005207 switch (D->getAvailability()) {
5208 case AR_Available:
5209 case AR_NotYetIntroduced:
5210 return CXAvailability_Available;
5211
5212 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005213 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005214
5215 case AR_Unavailable:
5216 return CXAvailability_NotAvailable;
5217 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005218 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005219
Douglas Gregor58ddb602010-08-23 23:00:57 +00005220 return CXAvailability_Available;
5221}
5222
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005223CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5224 if (clang_isDeclaration(cursor.kind))
5225 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5226
5227 return CXLanguage_Invalid;
5228}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005229
5230 /// \brief If the given cursor is the "templated" declaration
5231 /// descibing a class or function template, return the class or
5232 /// function template.
5233static Decl *maybeGetTemplateCursor(Decl *D) {
5234 if (!D)
5235 return 0;
5236
5237 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5238 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5239 return FunTmpl;
5240
5241 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5242 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5243 return ClassTmpl;
5244
5245 return D;
5246}
5247
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005248CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5249 if (clang_isDeclaration(cursor.kind)) {
5250 if (Decl *D = getCursorDecl(cursor)) {
5251 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005252 if (!DC)
5253 return clang_getNullCursor();
5254
5255 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5256 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005257 }
5258 }
5259
5260 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5261 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005262 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005263 }
5264
5265 return clang_getNullCursor();
5266}
5267
5268CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5269 if (clang_isDeclaration(cursor.kind)) {
5270 if (Decl *D = getCursorDecl(cursor)) {
5271 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005272 if (!DC)
5273 return clang_getNullCursor();
5274
5275 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5276 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005277 }
5278 }
5279
5280 // FIXME: Note that we can't easily compute the lexical context of a
5281 // statement or expression, so we return nothing.
5282 return clang_getNullCursor();
5283}
5284
Douglas Gregor9f592342010-10-01 20:25:15 +00005285void clang_getOverriddenCursors(CXCursor cursor,
5286 CXCursor **overridden,
5287 unsigned *num_overridden) {
5288 if (overridden)
5289 *overridden = 0;
5290 if (num_overridden)
5291 *num_overridden = 0;
5292 if (!overridden || !num_overridden)
5293 return;
5294
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005295 SmallVector<CXCursor, 8> Overridden;
5296 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005297
Ted Kremenek24077122011-11-14 23:51:37 +00005298 // Don't allocate memory if we have no overriden cursors.
5299 if (Overridden.size() == 0)
5300 return;
5301
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005302 *num_overridden = Overridden.size();
5303 *overridden = new CXCursor [Overridden.size()];
5304 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005305}
5306
5307void clang_disposeOverriddenCursors(CXCursor *overridden) {
5308 delete [] overridden;
5309}
5310
Douglas Gregorecdcb882010-10-20 22:00:55 +00005311CXFile clang_getIncludedFile(CXCursor cursor) {
5312 if (cursor.kind != CXCursor_InclusionDirective)
5313 return 0;
5314
5315 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5316 return (void *)ID->getFile();
5317}
5318
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005319} // end: extern "C"
5320
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005321
5322//===----------------------------------------------------------------------===//
5323// C++ AST instrospection.
5324//===----------------------------------------------------------------------===//
5325
5326extern "C" {
5327unsigned clang_CXXMethod_isStatic(CXCursor C) {
5328 if (!clang_isDeclaration(C.kind))
5329 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005330
5331 CXXMethodDecl *Method = 0;
5332 Decl *D = cxcursor::getCursorDecl(C);
5333 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5334 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5335 else
5336 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5337 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005338}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005339
Douglas Gregor211924b2011-05-12 15:17:24 +00005340unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5341 if (!clang_isDeclaration(C.kind))
5342 return 0;
5343
5344 CXXMethodDecl *Method = 0;
5345 Decl *D = cxcursor::getCursorDecl(C);
5346 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5347 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5348 else
5349 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5350 return (Method && Method->isVirtual()) ? 1 : 0;
5351}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005352} // end: extern "C"
5353
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005354//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005355// Attribute introspection.
5356//===----------------------------------------------------------------------===//
5357
5358extern "C" {
5359CXType clang_getIBOutletCollectionType(CXCursor C) {
5360 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005361 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005362
5363 IBOutletCollectionAttr *A =
5364 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5365
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005366 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005367}
5368} // end: extern "C"
5369
5370//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005371// Inspecting memory usage.
5372//===----------------------------------------------------------------------===//
5373
Ted Kremenekf7870022011-04-20 16:41:07 +00005374typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005375
Ted Kremenekf7870022011-04-20 16:41:07 +00005376static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5377 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005378 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005379 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005380 entries.push_back(entry);
5381}
5382
5383extern "C" {
5384
Ted Kremenekf7870022011-04-20 16:41:07 +00005385const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005386 const char *str = "";
5387 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005388 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005389 str = "ASTContext: expressions, declarations, and types";
5390 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005391 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005392 str = "ASTContext: identifiers";
5393 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005394 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005395 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005396 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005397 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005398 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005399 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005400 case CXTUResourceUsage_SourceManagerContentCache:
5401 str = "SourceManager: content cache allocator";
5402 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005403 case CXTUResourceUsage_AST_SideTables:
5404 str = "ASTContext: side tables";
5405 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005406 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5407 str = "SourceManager: malloc'ed memory buffers";
5408 break;
5409 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5410 str = "SourceManager: mmap'ed memory buffers";
5411 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005412 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5413 str = "ExternalASTSource: malloc'ed memory buffers";
5414 break;
5415 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5416 str = "ExternalASTSource: mmap'ed memory buffers";
5417 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005418 case CXTUResourceUsage_Preprocessor:
5419 str = "Preprocessor: malloc'ed memory";
5420 break;
5421 case CXTUResourceUsage_PreprocessingRecord:
5422 str = "Preprocessor: PreprocessingRecord";
5423 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005424 case CXTUResourceUsage_SourceManager_DataStructures:
5425 str = "SourceManager: data structures and tables";
5426 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005427 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5428 str = "Preprocessor: header search tables";
5429 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005430 }
5431 return str;
5432}
5433
Ted Kremenekf7870022011-04-20 16:41:07 +00005434CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005435 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005436 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005437 return usage;
5438 }
5439
5440 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5441 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5442 ASTContext &astContext = astUnit->getASTContext();
5443
5444 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005445 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005446 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005447
5448 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005449 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005450 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5451
5452 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005453 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005454 (unsigned long) astContext.Selectors.getTotalMemory());
5455
Ted Kremenekba29bd22011-04-28 04:53:38 +00005456 // How much memory is used by ASTContext's side tables?
5457 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5458 (unsigned long) astContext.getSideTableAllocatedMemory());
5459
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005460 // How much memory is used for caching global code completion results?
5461 unsigned long completionBytes = 0;
5462 if (GlobalCodeCompletionAllocator *completionAllocator =
5463 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005464 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005465 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005466 createCXTUResourceUsageEntry(*entries,
5467 CXTUResourceUsage_GlobalCompletionResults,
5468 completionBytes);
5469
5470 // How much memory is being used by SourceManager's content cache?
5471 createCXTUResourceUsageEntry(*entries,
5472 CXTUResourceUsage_SourceManagerContentCache,
5473 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005474
5475 // How much memory is being used by the MemoryBuffer's in SourceManager?
5476 const SourceManager::MemoryBufferSizes &srcBufs =
5477 astUnit->getSourceManager().getMemoryBufferSizes();
5478
5479 createCXTUResourceUsageEntry(*entries,
5480 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5481 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005482 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005483 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5484 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005485 createCXTUResourceUsageEntry(*entries,
5486 CXTUResourceUsage_SourceManager_DataStructures,
5487 (unsigned long) astContext.getSourceManager()
5488 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005489
5490 // How much memory is being used by the ExternalASTSource?
5491 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5492 const ExternalASTSource::MemoryBufferSizes &sizes =
5493 esrc->getMemoryBufferSizes();
5494
5495 createCXTUResourceUsageEntry(*entries,
5496 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5497 (unsigned long) sizes.malloc_bytes);
5498 createCXTUResourceUsageEntry(*entries,
5499 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5500 (unsigned long) sizes.mmap_bytes);
5501 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005502
5503 // How much memory is being used by the Preprocessor?
5504 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005505 createCXTUResourceUsageEntry(*entries,
5506 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005507 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005508
5509 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5510 createCXTUResourceUsageEntry(*entries,
5511 CXTUResourceUsage_PreprocessingRecord,
5512 pRec->getTotalMemory());
5513 }
5514
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005515 createCXTUResourceUsageEntry(*entries,
5516 CXTUResourceUsage_Preprocessor_HeaderSearch,
5517 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005518
Ted Kremenekf7870022011-04-20 16:41:07 +00005519 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005520 (unsigned) entries->size(),
5521 entries->size() ? &(*entries)[0] : 0 };
5522 entries.take();
5523 return usage;
5524}
5525
Ted Kremenekf7870022011-04-20 16:41:07 +00005526void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005527 if (usage.data)
5528 delete (MemUsageEntries*) usage.data;
5529}
5530
5531} // end extern "C"
5532
Douglas Gregor6df78732011-05-05 20:27:22 +00005533void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5534 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5535 for (unsigned I = 0; I != Usage.numEntries; ++I)
5536 fprintf(stderr, " %s: %lu\n",
5537 clang_getTUResourceUsageName(Usage.entries[I].kind),
5538 Usage.entries[I].amount);
5539
5540 clang_disposeCXTUResourceUsage(Usage);
5541}
5542
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005543//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005544// Misc. utility functions.
5545//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005546
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005547/// Default to using an 8 MB stack size on "safety" threads.
5548static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005549
5550namespace clang {
5551
5552bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005553 void (*Fn)(void*), void *UserData,
5554 unsigned Size) {
5555 if (!Size)
5556 Size = GetSafetyThreadStackSize();
5557 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005558 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5559 return CRC.RunSafely(Fn, UserData);
5560}
5561
5562unsigned GetSafetyThreadStackSize() {
5563 return SafetyStackThreadSize;
5564}
5565
5566void SetSafetyThreadStackSize(unsigned Value) {
5567 SafetyStackThreadSize = Value;
5568}
5569
5570}
5571
Ted Kremenek04bb7162010-01-22 22:44:15 +00005572extern "C" {
5573
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005574CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005575 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005576}
5577
5578} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005579