blob: 280a48c101679518d32a3e219f668d7818e6ac1b [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Argyrios Kyrtzidise397bf12011-11-03 19:02:34 +000022#include "CursorVisitor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000023
Ted Kremenek04bb7162010-01-22 22:44:15 +000024#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000027#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000030#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000031#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000032#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000037#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000038#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000039#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000040#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000041#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000043#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000048#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000049
Steve Naroff50398192009-08-28 15:28:48 +000050using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000051using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000052using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000053using namespace clang::cxtu;
Steve Naroff50398192009-08-28 15:28:48 +000054
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000055CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000056 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
Ted Kremenek15322172011-11-10 08:43:12 +000061 D->Diagnostics = 0;
Ted Kremeneka60ed472010-11-16 08:15:36 +000062 return D;
63}
64
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000065cxtu::CXTUOwner::~CXTUOwner() {
66 if (TU)
67 clang_disposeTranslationUnit(TU);
68}
69
Ted Kremenekf0e23e82010-02-17 00:41:40 +000070/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000071/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072static RangeComparisonResult RangeCompare(SourceManager &SM,
73 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 SourceRange R2) {
75 assert(R1.isValid() && "First range is invalid?");
76 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000077 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000078 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000079 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeAfter;
83 return RangeOverlap;
84}
85
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000086/// \brief Determine if a source location falls within, before, or after a
87/// a given source range.
88static RangeComparisonResult LocationCompare(SourceManager &SM,
89 SourceLocation L, SourceRange R) {
90 assert(R.isValid() && "First range is invalid?");
91 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000092 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000093 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000094 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
95 return RangeBefore;
96 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
97 return RangeAfter;
98 return RangeOverlap;
99}
100
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000101/// \brief Translate a Clang source range into a CIndex source range.
102///
103/// Clang internally represents ranges where the end location points to the
104/// start of the token at the end. However, for external clients it is more
105/// useful to have a CXSourceRange be a proper half-open interval. This routine
106/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000107CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000108 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000109 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000113 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000114 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000116 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000117 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 }
119
120 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
121 R.getBegin().getRawEncoding(),
122 EndLoc.getRawEncoding() };
123 return Result;
124}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000125
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000126//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000127// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000128//===----------------------------------------------------------------------===//
129
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000130static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000131static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
132
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000135 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136}
137
Douglas Gregorb1373d02010-01-20 20:59:29 +0000138/// \brief Visit the given cursor and, if requested by the visitor,
139/// its children.
140///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141/// \param Cursor the cursor to visit.
142///
143/// \param CheckRegionOfInterest if true, then the caller already checked that
144/// this cursor is within the region of interest.
145///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146/// \returns true if the visitation should be aborted, false if it
147/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000149 if (clang_isInvalid(Cursor.kind))
150 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000151
Douglas Gregorb1373d02010-01-20 20:59:29 +0000152 if (clang_isDeclaration(Cursor.kind)) {
153 Decl *D = getCursorDecl(Cursor);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +0000154 if (!D) {
155 assert(0 && "Invalid declaration cursor");
156 return true; // abort.
157 }
158
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000159 // Ignore implicit declarations, unless it's an objc method because
160 // currently we should report implicit methods for properties when indexing.
161 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162 return false;
163 }
164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 // If we have a range of interest, and this cursor doesn't intersect with it,
166 // we're done.
167 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000168 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000169 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170 return false;
171 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 switch (Visitor(Cursor, Parent, ClientData)) {
174 case CXChildVisit_Break:
175 return true;
176
177 case CXChildVisit_Continue:
178 return false;
179
180 case CXChildVisit_Recurse:
181 return VisitChildren(Cursor);
182 }
183
Douglas Gregorfd643772010-01-25 16:45:46 +0000184 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000185}
186
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000187static bool visitPreprocessedEntitiesInRange(SourceRange R,
188 PreprocessingRecord &PPRec,
189 CursorVisitor &Visitor) {
190 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
191 FileID FID;
192
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000193 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000194 // If the begin/end of the range lie in the same FileID, do the optimization
195 // where we skip preprocessed entities that do not come from the same FileID.
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()");
576 return false;
577}
578
Richard Smith162e1c12011-04-15 14:24:37 +0000579bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
580 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
581 return Visit(TSInfo->getTypeLoc());
582
583 return false;
584}
585
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000586bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
587 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
588 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590 return false;
591}
592
593bool CursorVisitor::VisitTagDecl(TagDecl *D) {
594 return VisitDeclContext(D);
595}
596
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000597bool CursorVisitor::VisitClassTemplateSpecializationDecl(
598 ClassTemplateSpecializationDecl *D) {
599 bool ShouldVisitBody = false;
600 switch (D->getSpecializationKind()) {
601 case TSK_Undeclared:
602 case TSK_ImplicitInstantiation:
603 // Nothing to visit
604 return false;
605
606 case TSK_ExplicitInstantiationDeclaration:
607 case TSK_ExplicitInstantiationDefinition:
608 break;
609
610 case TSK_ExplicitSpecialization:
611 ShouldVisitBody = true;
612 break;
613 }
614
615 // Visit the template arguments used in the specialization.
616 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
617 TypeLoc TL = SpecType->getTypeLoc();
618 if (TemplateSpecializationTypeLoc *TSTLoc
619 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
620 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
621 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
622 return true;
623 }
624 }
625
626 if (ShouldVisitBody && VisitCXXRecordDecl(D))
627 return true;
628
629 return false;
630}
631
Douglas Gregor74dbe642010-08-31 19:31:58 +0000632bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
633 ClassTemplatePartialSpecializationDecl *D) {
634 // FIXME: Visit the "outer" template parameter lists on the TagDecl
635 // before visiting these template parameters.
636 if (VisitTemplateParameters(D->getTemplateParameters()))
637 return true;
638
639 // Visit the partial specialization arguments.
640 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
641 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
642 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
643 return true;
644
645 return VisitCXXRecordDecl(D);
646}
647
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000648bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000649 // Visit the default argument.
650 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
651 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
652 if (Visit(DefArg->getTypeLoc()))
653 return true;
654
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000655 return false;
656}
657
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000658bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
659 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000660 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000661 return false;
662}
663
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000664bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
665 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
666 if (Visit(TSInfo->getTypeLoc()))
667 return true;
668
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000669 // Visit the nested-name-specifier, if present.
670 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
671 if (VisitNestedNameSpecifierLoc(QualifierLoc))
672 return true;
673
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000674 return false;
675}
676
Douglas Gregora67e03f2010-09-09 21:42:20 +0000677/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000678static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
679 CXXCtorInitializer const * const *X
680 = static_cast<CXXCtorInitializer const * const *>(Xp);
681 CXXCtorInitializer const * const *Y
682 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000683
684 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
685 return -1;
686 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
687 return 1;
688 else
689 return 0;
690}
691
Douglas Gregorb1373d02010-01-20 20:59:29 +0000692bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000693 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
694 // Visit the function declaration's syntactic components in the order
695 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000696 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000697 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
698
699 // If we have a function declared directly (without the use of a typedef),
700 // visit just the return type. Otherwise, just visit the function's type
701 // now.
702 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
703 (!FTL && Visit(TL)))
704 return true;
705
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000706 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000707 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
708 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000709 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000710
711 // Visit the declaration name.
712 if (VisitDeclarationNameInfo(ND->getNameInfo()))
713 return true;
714
715 // FIXME: Visit explicitly-specified template arguments!
716
717 // Visit the function parameters, if we have a function type.
718 if (FTL && VisitFunctionTypeLoc(*FTL, true))
719 return true;
720
721 // FIXME: Attributes?
722 }
723
Sean Hunt10620eb2011-05-06 20:44:56 +0000724 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000725 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
726 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000727 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000728 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
729 IEnd = Constructor->init_end();
730 I != IEnd; ++I) {
731 if (!(*I)->isWritten())
732 continue;
733
734 WrittenInits.push_back(*I);
735 }
736
737 // Sort the initializers in source order
738 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000739 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000740
741 // Visit the initializers in source order
742 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000743 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000744 if (Init->isAnyMemberInitializer()) {
745 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000746 Init->getMemberLocation(), TU)))
747 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000748 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
749 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000750 return true;
751 }
752
753 // Visit the initializer value.
754 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000755 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000756 return true;
757 }
758 }
759
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000760 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761 return true;
762 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000763
Douglas Gregorb1373d02010-01-20 20:59:29 +0000764 return false;
765}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000766
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000767bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
768 if (VisitDeclaratorDecl(D))
769 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000770
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000771 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000772 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000773
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000774 return false;
775}
776
777bool CursorVisitor::VisitVarDecl(VarDecl *D) {
778 if (VisitDeclaratorDecl(D))
779 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000782 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 return false;
785}
786
Douglas Gregor84b51d72010-09-01 20:16:53 +0000787bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
788 if (VisitDeclaratorDecl(D))
789 return true;
790
791 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
792 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000793 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000794
795 return false;
796}
797
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000798bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
799 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
800 // before visiting these template parameters.
801 if (VisitTemplateParameters(D->getTemplateParameters()))
802 return true;
803
804 return VisitFunctionDecl(D->getTemplatedDecl());
805}
806
Douglas Gregor39d6f072010-08-31 19:02:00 +0000807bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
808 // FIXME: Visit the "outer" template parameter lists on the TagDecl
809 // before visiting these template parameters.
810 if (VisitTemplateParameters(D->getTemplateParameters()))
811 return true;
812
813 return VisitCXXRecordDecl(D->getTemplatedDecl());
814}
815
Douglas Gregor84b51d72010-09-01 20:16:53 +0000816bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
817 if (VisitTemplateParameters(D->getTemplateParameters()))
818 return true;
819
820 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
821 VisitTemplateArgumentLoc(D->getDefaultArgument()))
822 return true;
823
824 return false;
825}
826
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000827bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000828 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
829 if (Visit(TSInfo->getTypeLoc()))
830 return true;
831
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000833 PEnd = ND->param_end();
834 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000835 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836 return true;
837 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000840 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 return false;
844}
845
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000846template <typename DeclIt>
847static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
848 SourceManager &SM, SourceLocation EndLoc,
849 SmallVectorImpl<Decl *> &Decls) {
850 DeclIt next = *DI_current;
851 while (++next != DE_current) {
852 Decl *D_next = *next;
853 if (!D_next)
854 break;
855 SourceLocation L = D_next->getLocStart();
856 if (!L.isValid())
857 break;
858 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
859 *DI_current = next;
860 Decls.push_back(D_next);
861 continue;
862 }
863 break;
864 }
865}
866
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000867namespace {
868 struct ContainerDeclsSort {
869 SourceManager &SM;
870 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
871 bool operator()(Decl *A, Decl *B) {
872 SourceLocation L_A = A->getLocStart();
873 SourceLocation L_B = B->getLocStart();
874 assert(L_A.isValid() && L_B.isValid());
875 return SM.isBeforeInTranslationUnit(L_A, L_B);
876 }
877 };
878}
879
Douglas Gregora59e3902010-01-21 23:27:09 +0000880bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000881 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
882 // an @implementation can lexically contain Decls that are not properly
883 // nested in the AST. When we identify such cases, we need to retrofit
884 // this nesting here.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000885 if (!DI_current && !FileDI_current)
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000886 return VisitDeclContext(D);
887
888 // Scan the Decls that immediately come after the container
889 // in the current DeclContext. If any fall within the
890 // container's lexical region, stash them into a vector
891 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000892 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000893 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000894 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000895 if (EndLoc.isValid()) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +0000896 if (DI_current) {
897 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
898 DeclsInContainer);
899 } else {
900 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
901 DeclsInContainer);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000902 }
903 }
904
905 // The common case.
906 if (DeclsInContainer.empty())
907 return VisitDeclContext(D);
908
909 // Get all the Decls in the DeclContext, and sort them with the
910 // additional ones we've collected. Then visit them.
911 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
912 I!=E; ++I) {
913 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000914 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
915 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000916 continue;
917 DeclsInContainer.push_back(subDecl);
918 }
919
920 // Now sort the Decls so that they appear in lexical order.
921 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
922 ContainerDeclsSort(SM));
923
924 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000925 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000926 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000927 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000928 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
929 if (!V.hasValue())
930 continue;
931 if (!V.getValue())
932 return false;
933 if (Visit(Cursor, true))
934 return true;
935 }
936 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000937}
938
Douglas Gregorb1373d02010-01-20 20:59:29 +0000939bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000940 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
941 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000942 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000943
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000944 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
945 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
946 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000947 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000948 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregora59e3902010-01-21 23:27:09 +0000950 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000951}
952
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000953bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000954 if (!PID->isThisDeclarationADefinition())
955 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
956
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000957 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
958 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
959 E = PID->protocol_end(); I != E; ++I, ++PL)
960 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
961 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000962
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000963 return VisitObjCContainerDecl(PID);
964}
965
Ted Kremenek23173d72010-05-18 21:09:07 +0000966bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000967 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000968 return true;
969
Ted Kremenek23173d72010-05-18 21:09:07 +0000970 // FIXME: This implements a workaround with @property declarations also being
971 // installed in the DeclContext for the @interface. Eventually this code
972 // should be removed.
973 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
974 if (!CDecl || !CDecl->IsClassExtension())
975 return false;
976
977 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
978 if (!ID)
979 return false;
980
981 IdentifierInfo *PropertyId = PD->getIdentifier();
982 ObjCPropertyDecl *prevDecl =
983 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
984
985 if (!prevDecl)
986 return false;
987
988 // Visit synthesized methods since they will be skipped when visiting
989 // the @interface.
990 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000991 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000992 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000993 return true;
994
995 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000996 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000997 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000998 return true;
999
1000 return false;
1001}
1002
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001004 if (!D->isThisDeclarationADefinition()) {
1005 // Forward declaration is treated like a reference.
1006 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1007 }
1008
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001009 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001010 if (D->getSuperClass() &&
1011 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001013 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001016 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1017 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1018 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001019 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001020 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021
Douglas Gregora59e3902010-01-21 23:27:09 +00001022 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001023}
1024
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001025bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1026 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001027}
1028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001030 // 'ID' could be null when dealing with invalid code.
1031 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1032 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001035 return VisitObjCImplDecl(D);
1036}
1037
1038bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1039#if 0
1040 // Issue callbacks for super class.
1041 // FIXME: No source location information!
1042 if (D->getSuperClass() &&
1043 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045 TU)))
1046 return true;
1047#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001049 return VisitObjCImplDecl(D);
1050}
1051
Douglas Gregora4ffd852010-11-17 01:03:52 +00001052bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1053 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1054 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1055
1056 return false;
1057}
1058
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001059bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1060 return VisitDeclContext(D);
1061}
1062
Douglas Gregor69319002010-08-31 23:48:11 +00001063bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001064 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001065 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1066 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001067 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001068
1069 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1070 D->getTargetNameLoc(), TU));
1071}
1072
Douglas Gregor7e242562010-09-01 19:52:22 +00001073bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001074 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001075 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1076 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001078 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001079
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001080 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1081 return true;
1082
Douglas Gregor7e242562010-09-01 19:52:22 +00001083 return VisitDeclarationNameInfo(D->getNameInfo());
1084}
1085
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001086bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001088 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1089 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001091
1092 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1093 D->getIdentLocation(), TU));
1094}
1095
Douglas Gregor7e242562010-09-01 19:52:22 +00001096bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001097 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001098 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1099 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001101 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001102
Douglas Gregor7e242562010-09-01 19:52:22 +00001103 return VisitDeclarationNameInfo(D->getNameInfo());
1104}
1105
1106bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1107 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001108 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001109 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1110 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001111 return true;
1112
Douglas Gregor7e242562010-09-01 19:52:22 +00001113 return false;
1114}
1115
Douglas Gregor01829d32010-08-31 14:41:23 +00001116bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1117 switch (Name.getName().getNameKind()) {
1118 case clang::DeclarationName::Identifier:
1119 case clang::DeclarationName::CXXLiteralOperatorName:
1120 case clang::DeclarationName::CXXOperatorName:
1121 case clang::DeclarationName::CXXUsingDirective:
1122 return false;
1123
1124 case clang::DeclarationName::CXXConstructorName:
1125 case clang::DeclarationName::CXXDestructorName:
1126 case clang::DeclarationName::CXXConversionFunctionName:
1127 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1128 return Visit(TSInfo->getTypeLoc());
1129 return false;
1130
1131 case clang::DeclarationName::ObjCZeroArgSelector:
1132 case clang::DeclarationName::ObjCOneArgSelector:
1133 case clang::DeclarationName::ObjCMultiArgSelector:
1134 // FIXME: Per-identifier location info?
1135 return false;
1136 }
1137
1138 return false;
1139}
1140
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001141bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1142 SourceRange Range) {
1143 // FIXME: This whole routine is a hack to work around the lack of proper
1144 // source information in nested-name-specifiers (PR5791). Since we do have
1145 // a beginning source location, we can visit the first component of the
1146 // nested-name-specifier, if it's a single-token component.
1147 if (!NNS)
1148 return false;
1149
1150 // Get the first component in the nested-name-specifier.
1151 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1152 NNS = Prefix;
1153
1154 switch (NNS->getKind()) {
1155 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001156 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1157 TU));
1158
Douglas Gregor14aba762011-02-24 02:36:08 +00001159 case NestedNameSpecifier::NamespaceAlias:
1160 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1161 Range.getBegin(), TU));
1162
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001163 case NestedNameSpecifier::TypeSpec: {
1164 // If the type has a form where we know that the beginning of the source
1165 // range matches up with a reference cursor. Visit the appropriate reference
1166 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001167 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001168 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1169 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1170 if (const TagType *Tag = dyn_cast<TagType>(T))
1171 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1172 if (const TemplateSpecializationType *TST
1173 = dyn_cast<TemplateSpecializationType>(T))
1174 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1175 break;
1176 }
1177
1178 case NestedNameSpecifier::TypeSpecWithTemplate:
1179 case NestedNameSpecifier::Global:
1180 case NestedNameSpecifier::Identifier:
1181 break;
1182 }
1183
1184 return false;
1185}
1186
Douglas Gregordc355712011-02-25 00:36:19 +00001187bool
1188CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001189 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001190 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1191 Qualifiers.push_back(Qualifier);
1192
1193 while (!Qualifiers.empty()) {
1194 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1195 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1196 switch (NNS->getKind()) {
1197 case NestedNameSpecifier::Namespace:
1198 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001199 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001200 TU)))
1201 return true;
1202
1203 break;
1204
1205 case NestedNameSpecifier::NamespaceAlias:
1206 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001207 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001208 TU)))
1209 return true;
1210
1211 break;
1212
1213 case NestedNameSpecifier::TypeSpec:
1214 case NestedNameSpecifier::TypeSpecWithTemplate:
1215 if (Visit(Q.getTypeLoc()))
1216 return true;
1217
1218 break;
1219
1220 case NestedNameSpecifier::Global:
1221 case NestedNameSpecifier::Identifier:
1222 break;
1223 }
1224 }
1225
1226 return false;
1227}
1228
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001229bool CursorVisitor::VisitTemplateParameters(
1230 const TemplateParameterList *Params) {
1231 if (!Params)
1232 return false;
1233
1234 for (TemplateParameterList::const_iterator P = Params->begin(),
1235 PEnd = Params->end();
1236 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001237 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001238 return true;
1239 }
1240
1241 return false;
1242}
1243
Douglas Gregor0b36e612010-08-31 20:37:03 +00001244bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1245 switch (Name.getKind()) {
1246 case TemplateName::Template:
1247 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1248
1249 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001250 // Visit the overloaded template set.
1251 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1252 return true;
1253
Douglas Gregor0b36e612010-08-31 20:37:03 +00001254 return false;
1255
1256 case TemplateName::DependentTemplate:
1257 // FIXME: Visit nested-name-specifier.
1258 return false;
1259
1260 case TemplateName::QualifiedTemplate:
1261 // FIXME: Visit nested-name-specifier.
1262 return Visit(MakeCursorTemplateRef(
1263 Name.getAsQualifiedTemplateName()->getDecl(),
1264 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001265
1266 case TemplateName::SubstTemplateTemplateParm:
1267 return Visit(MakeCursorTemplateRef(
1268 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1269 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001270
1271 case TemplateName::SubstTemplateTemplateParmPack:
1272 return Visit(MakeCursorTemplateRef(
1273 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1274 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001275 }
1276
1277 return false;
1278}
1279
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001280bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1281 switch (TAL.getArgument().getKind()) {
1282 case TemplateArgument::Null:
1283 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001284 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001285 return false;
1286
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001287 case TemplateArgument::Type:
1288 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1289 return Visit(TSInfo->getTypeLoc());
1290 return false;
1291
1292 case TemplateArgument::Declaration:
1293 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001294 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001295 return false;
1296
1297 case TemplateArgument::Expression:
1298 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001299 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300 return false;
1301
1302 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001303 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001304 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1305 return true;
1306
Douglas Gregora7fc9012011-01-05 18:58:31 +00001307 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001308 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001309 }
1310
1311 return false;
1312}
1313
Ted Kremeneka0536d82010-05-07 01:04:29 +00001314bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1315 return VisitDeclContext(D);
1316}
1317
Douglas Gregor01829d32010-08-31 14:41:23 +00001318bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1319 return Visit(TL.getUnqualifiedLoc());
1320}
1321
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001322bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001323 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001324
1325 // Some builtin types (such as Objective-C's "id", "sel", and
1326 // "Class") have associated declarations. Create cursors for those.
1327 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001328 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001329
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001330 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001331 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001332 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001333#define BUILTIN_TYPE(Id, SingletonId)
1334#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1335#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1336#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1337#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1338#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001339 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001340
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001341 case BuiltinType::ObjCId:
1342 VisitType = Context.getObjCIdType();
1343 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001344
1345 case BuiltinType::ObjCClass:
1346 VisitType = Context.getObjCClassType();
1347 break;
1348
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001349 case BuiltinType::ObjCSel:
1350 VisitType = Context.getObjCSelType();
1351 break;
1352 }
1353
1354 if (!VisitType.isNull()) {
1355 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001356 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001357 TU));
1358 }
1359
1360 return false;
1361}
1362
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001363bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001364 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001365}
1366
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1368 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1369}
1370
1371bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001372 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001373 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001374
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1376}
1377
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001378bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001379 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001380}
1381
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001382bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1383 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1384 return true;
1385
John McCallc12c5bb2010-05-15 11:32:37 +00001386 return false;
1387}
1388
1389bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1390 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1391 return true;
1392
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1394 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1395 TU)))
1396 return true;
1397 }
1398
1399 return false;
1400}
1401
1402bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001403 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001404}
1405
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001406bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1407 return Visit(TL.getInnerLoc());
1408}
1409
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001410bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1411 return Visit(TL.getPointeeLoc());
1412}
1413
1414bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1415 return Visit(TL.getPointeeLoc());
1416}
1417
1418bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1419 return Visit(TL.getPointeeLoc());
1420}
1421
1422bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001423 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001424}
1425
1426bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001427 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001428}
1429
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001430bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1431 return Visit(TL.getModifiedLoc());
1432}
1433
Douglas Gregor01829d32010-08-31 14:41:23 +00001434bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1435 bool SkipResultType) {
1436 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001437 return true;
1438
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001439 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001440 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001441 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001442 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001443
1444 return false;
1445}
1446
1447bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1448 if (Visit(TL.getElementLoc()))
1449 return true;
1450
1451 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001452 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001453
1454 return false;
1455}
1456
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001457bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1458 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001459 // Visit the template name.
1460 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1461 TL.getTemplateNameLoc()))
1462 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001463
1464 // Visit the template arguments.
1465 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1466 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1467 return true;
1468
1469 return false;
1470}
1471
Douglas Gregor2332c112010-01-21 20:48:56 +00001472bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1473 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1474}
1475
1476bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1477 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1478 return Visit(TSInfo->getTypeLoc());
1479
1480 return false;
1481}
1482
Sean Huntca63c202011-05-24 22:41:36 +00001483bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1484 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1485 return Visit(TSInfo->getTypeLoc());
1486
1487 return false;
1488}
1489
Douglas Gregor2494dd02011-03-01 01:34:45 +00001490bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1491 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1492 return true;
1493
1494 return false;
1495}
1496
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001497bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1498 DependentTemplateSpecializationTypeLoc TL) {
1499 // Visit the nested-name-specifier, if there is one.
1500 if (TL.getQualifierLoc() &&
1501 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1502 return true;
1503
1504 // Visit the template arguments.
1505 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1506 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1507 return true;
1508
1509 return false;
1510}
1511
Douglas Gregor9e876872011-03-01 18:12:44 +00001512bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1513 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1514 return true;
1515
1516 return Visit(TL.getNamedTypeLoc());
1517}
1518
Douglas Gregor7536dd52010-12-20 02:24:11 +00001519bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1520 return Visit(TL.getPatternLoc());
1521}
1522
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001523bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1524 if (Expr *E = TL.getUnderlyingExpr())
1525 return Visit(MakeCXCursor(E, StmtParent, TU));
1526
1527 return false;
1528}
1529
1530bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1531 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1532}
1533
Eli Friedmanb001de72011-10-06 23:00:33 +00001534bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1535 return Visit(TL.getValueLoc());
1536}
1537
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001538#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1539bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1540 return Visit##PARENT##Loc(TL); \
1541}
1542
1543DEFAULT_TYPELOC_IMPL(Complex, Type)
1544DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1545DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1546DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1547DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1548DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1549DEFAULT_TYPELOC_IMPL(Vector, Type)
1550DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1551DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1552DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1553DEFAULT_TYPELOC_IMPL(Record, TagType)
1554DEFAULT_TYPELOC_IMPL(Enum, TagType)
1555DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1556DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1557DEFAULT_TYPELOC_IMPL(Auto, Type)
1558
Ted Kremenek3064ef92010-08-27 21:34:58 +00001559bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001560 // Visit the nested-name-specifier, if present.
1561 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1562 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1563 return true;
1564
John McCall5e1cdac2011-10-07 06:10:15 +00001565 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001566 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1567 E = D->bases_end(); I != E; ++I) {
1568 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1569 return true;
1570 }
1571 }
1572
1573 return VisitTagDecl(D);
1574}
1575
Ted Kremenek09dfa372010-02-18 05:46:33 +00001576bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001577 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1578 i != e; ++i)
1579 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001580 return true;
1581
1582 return false;
1583}
1584
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001585//===----------------------------------------------------------------------===//
1586// Data-recursive visitor methods.
1587//===----------------------------------------------------------------------===//
1588
Ted Kremenek28a71942010-11-13 00:36:47 +00001589namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001590#define DEF_JOB(NAME, DATA, KIND)\
1591class NAME : public VisitorJob {\
1592public:\
1593 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1594 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001595 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001596};
1597
1598DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1599DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001600DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001601DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001602DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001603 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001604DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001605#undef DEF_JOB
1606
1607class DeclVisit : public VisitorJob {
1608public:
1609 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1610 VisitorJob(parent, VisitorJob::DeclVisitKind,
1611 d, isFirst ? (void*) 1 : (void*) 0) {}
1612 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001613 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001614 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001615 Decl *get() const { return static_cast<Decl*>(data[0]); }
1616 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001617};
Ted Kremenek035dc412010-11-13 00:36:50 +00001618class TypeLocVisit : public VisitorJob {
1619public:
1620 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1621 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1622 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1623
1624 static bool classof(const VisitorJob *VJ) {
1625 return VJ->getKind() == TypeLocVisitKind;
1626 }
1627
Ted Kremenek82f3c502010-11-15 22:23:26 +00001628 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001629 QualType T = QualType::getFromOpaquePtr(data[0]);
1630 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001631 }
1632};
1633
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001634class LabelRefVisit : public VisitorJob {
1635public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001636 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1637 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001638 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001639
1640 static bool classof(const VisitorJob *VJ) {
1641 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1642 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001643 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001644 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001645 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001646};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001647
1648class NestedNameSpecifierLocVisit : public VisitorJob {
1649public:
1650 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1651 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1652 Qualifier.getNestedNameSpecifier(),
1653 Qualifier.getOpaqueData()) { }
1654
1655 static bool classof(const VisitorJob *VJ) {
1656 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1657 }
1658
1659 NestedNameSpecifierLoc get() const {
1660 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1661 data[1]);
1662 }
1663};
1664
Ted Kremenekf64d8032010-11-18 00:02:32 +00001665class DeclarationNameInfoVisit : public VisitorJob {
1666public:
1667 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1668 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1669 static bool classof(const VisitorJob *VJ) {
1670 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1671 }
1672 DeclarationNameInfo get() const {
1673 Stmt *S = static_cast<Stmt*>(data[0]);
1674 switch (S->getStmtClass()) {
1675 default:
1676 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001677 case clang::Stmt::MSDependentExistsStmtClass:
1678 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001679 case Stmt::CXXDependentScopeMemberExprClass:
1680 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1681 case Stmt::DependentScopeDeclRefExprClass:
1682 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1683 }
1684 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001685};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001686class MemberRefVisit : public VisitorJob {
1687public:
1688 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1689 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001690 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001691 static bool classof(const VisitorJob *VJ) {
1692 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1693 }
1694 FieldDecl *get() const {
1695 return static_cast<FieldDecl*>(data[0]);
1696 }
1697 SourceLocation getLoc() const {
1698 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1699 }
1700};
Ted Kremenek28a71942010-11-13 00:36:47 +00001701class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1702 VisitorWorkList &WL;
1703 CXCursor Parent;
1704public:
1705 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1706 : WL(wl), Parent(parent) {}
1707
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001708 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001709 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001710 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001711 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001712 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001713 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001714 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001715 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001716 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001717 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001718 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001719 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001720 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001721 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001722 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001723 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001724 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001725 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001726 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001727 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001728 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1729 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001730 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001731 void VisitIfStmt(IfStmt *If);
1732 void VisitInitListExpr(InitListExpr *IE);
1733 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001734 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001735 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001736 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1737 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001738 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001739 void VisitStmt(Stmt *S);
1740 void VisitSwitchStmt(SwitchStmt *S);
1741 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001742 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001743 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001744 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001745 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001746 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001747 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001748 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001749 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1750 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001751
Ted Kremenek28a71942010-11-13 00:36:47 +00001752private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001753 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001754 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001755 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001756 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001757 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001758 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001759 void AddTypeLoc(TypeSourceInfo *TI);
1760 void EnqueueChildren(Stmt *S);
1761};
1762} // end anonyous namespace
1763
Ted Kremenekf64d8032010-11-18 00:02:32 +00001764void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1765 // 'S' should always be non-null, since it comes from the
1766 // statement we are visiting.
1767 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1768}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001769
1770void
1771EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1772 if (Qualifier)
1773 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1774}
1775
Ted Kremenek28a71942010-11-13 00:36:47 +00001776void EnqueueVisitor::AddStmt(Stmt *S) {
1777 if (S)
1778 WL.push_back(StmtVisit(S, Parent));
1779}
Ted Kremenek035dc412010-11-13 00:36:50 +00001780void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001781 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001782 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001783}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001784void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001785 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001786 if (A)
1787 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001788 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001789}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001790void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1791 if (D)
1792 WL.push_back(MemberRefVisit(D, L, Parent));
1793}
Ted Kremenek28a71942010-11-13 00:36:47 +00001794void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1795 if (TI)
1796 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1797 }
1798void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001799 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001800 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001801 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001802 }
1803 if (size == WL.size())
1804 return;
1805 // Now reverse the entries we just added. This will match the DFS
1806 // ordering performed by the worklist.
1807 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1808 std::reverse(I, E);
1809}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001810void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1811 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1812}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001813void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1814 AddDecl(B->getBlockDecl());
1815}
Ted Kremenek28a71942010-11-13 00:36:47 +00001816void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1817 EnqueueChildren(E);
1818 AddTypeLoc(E->getTypeSourceInfo());
1819}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001820void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1821 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1822 E = S->body_rend(); I != E; ++I) {
1823 AddStmt(*I);
1824 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001825}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001826void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001827VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1828 AddStmt(S->getSubStmt());
1829 AddDeclarationNameInfo(S);
1830 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1831 AddNestedNameSpecifierLoc(QualifierLoc);
1832}
1833
1834void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001835VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1836 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1837 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001838 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1839 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001840 if (!E->isImplicitAccess())
1841 AddStmt(E->getBase());
1842}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001843void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1844 // Enqueue the initializer or constructor arguments.
1845 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1846 AddStmt(E->getConstructorArg(I-1));
1847 // Enqueue the array size, if any.
1848 AddStmt(E->getArraySize());
1849 // Enqueue the allocated type.
1850 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1851 // Enqueue the placement arguments.
1852 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1853 AddStmt(E->getPlacementArg(I-1));
1854}
Ted Kremenek28a71942010-11-13 00:36:47 +00001855void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001856 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1857 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001858 AddStmt(CE->getCallee());
1859 AddStmt(CE->getArg(0));
1860}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001861void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1862 // Visit the name of the type being destroyed.
1863 AddTypeLoc(E->getDestroyedTypeInfo());
1864 // Visit the scope type that looks disturbingly like the nested-name-specifier
1865 // but isn't.
1866 AddTypeLoc(E->getScopeTypeInfo());
1867 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001868 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1869 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001870 // Visit base expression.
1871 AddStmt(E->getBase());
1872}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001873void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1874 AddTypeLoc(E->getTypeSourceInfo());
1875}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001876void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1877 EnqueueChildren(E);
1878 AddTypeLoc(E->getTypeSourceInfo());
1879}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001880void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1881 EnqueueChildren(E);
1882 if (E->isTypeOperand())
1883 AddTypeLoc(E->getTypeOperandSourceInfo());
1884}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001885
1886void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1887 *E) {
1888 EnqueueChildren(E);
1889 AddTypeLoc(E->getTypeSourceInfo());
1890}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001891void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1892 EnqueueChildren(E);
1893 if (E->isTypeOperand())
1894 AddTypeLoc(E->getTypeOperandSourceInfo());
1895}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001896
1897void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1898 EnqueueChildren(S);
1899 AddDecl(S->getExceptionDecl());
1900}
1901
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001902void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001903 if (DR->hasExplicitTemplateArgs()) {
1904 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1905 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001906 WL.push_back(DeclRefExprParts(DR, Parent));
1907}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001908void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1909 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1910 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001911 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001912}
Ted Kremenek035dc412010-11-13 00:36:50 +00001913void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1914 unsigned size = WL.size();
1915 bool isFirst = true;
1916 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1917 D != DEnd; ++D) {
1918 AddDecl(*D, isFirst);
1919 isFirst = false;
1920 }
1921 if (size == WL.size())
1922 return;
1923 // Now reverse the entries we just added. This will match the DFS
1924 // ordering performed by the worklist.
1925 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1926 std::reverse(I, E);
1927}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001928void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1929 AddStmt(E->getInit());
1930 typedef DesignatedInitExpr::Designator Designator;
1931 for (DesignatedInitExpr::reverse_designators_iterator
1932 D = E->designators_rbegin(), DEnd = E->designators_rend();
1933 D != DEnd; ++D) {
1934 if (D->isFieldDesignator()) {
1935 if (FieldDecl *Field = D->getField())
1936 AddMemberRef(Field, D->getFieldLoc());
1937 continue;
1938 }
1939 if (D->isArrayDesignator()) {
1940 AddStmt(E->getArrayIndex(*D));
1941 continue;
1942 }
1943 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1944 AddStmt(E->getArrayRangeEnd(*D));
1945 AddStmt(E->getArrayRangeStart(*D));
1946 }
1947}
Ted Kremenek28a71942010-11-13 00:36:47 +00001948void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1949 EnqueueChildren(E);
1950 AddTypeLoc(E->getTypeInfoAsWritten());
1951}
1952void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1953 AddStmt(FS->getBody());
1954 AddStmt(FS->getInc());
1955 AddStmt(FS->getCond());
1956 AddDecl(FS->getConditionVariable());
1957 AddStmt(FS->getInit());
1958}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001959void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1960 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1961}
Ted Kremenek28a71942010-11-13 00:36:47 +00001962void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1963 AddStmt(If->getElse());
1964 AddStmt(If->getThen());
1965 AddStmt(If->getCond());
1966 AddDecl(If->getConditionVariable());
1967}
1968void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1969 // We care about the syntactic form of the initializer list, only.
1970 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1971 IE = Syntactic;
1972 EnqueueChildren(IE);
1973}
1974void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001975 WL.push_back(MemberExprParts(M, Parent));
1976
1977 // If the base of the member access expression is an implicit 'this', don't
1978 // visit it.
1979 // FIXME: If we ever want to show these implicit accesses, this will be
1980 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001981 if (!M->isImplicitAccess())
1982 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001983}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001984void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1985 AddTypeLoc(E->getEncodedTypeSourceInfo());
1986}
Ted Kremenek28a71942010-11-13 00:36:47 +00001987void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1988 EnqueueChildren(M);
1989 AddTypeLoc(M->getClassReceiverTypeInfo());
1990}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001991void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1992 // Visit the components of the offsetof expression.
1993 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1994 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1995 const OffsetOfNode &Node = E->getComponent(I-1);
1996 switch (Node.getKind()) {
1997 case OffsetOfNode::Array:
1998 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1999 break;
2000 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002001 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002002 break;
2003 case OffsetOfNode::Identifier:
2004 case OffsetOfNode::Base:
2005 continue;
2006 }
2007 }
2008 // Visit the type into which we're computing the offset.
2009 AddTypeLoc(E->getTypeSourceInfo());
2010}
Ted Kremenek28a71942010-11-13 00:36:47 +00002011void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002012 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002013 WL.push_back(OverloadExprParts(E, Parent));
2014}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002015void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2016 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002017 EnqueueChildren(E);
2018 if (E->isArgumentType())
2019 AddTypeLoc(E->getArgumentTypeInfo());
2020}
Ted Kremenek28a71942010-11-13 00:36:47 +00002021void EnqueueVisitor::VisitStmt(Stmt *S) {
2022 EnqueueChildren(S);
2023}
2024void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2025 AddStmt(S->getBody());
2026 AddStmt(S->getCond());
2027 AddDecl(S->getConditionVariable());
2028}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002029
Ted Kremenek28a71942010-11-13 00:36:47 +00002030void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2031 AddStmt(W->getBody());
2032 AddStmt(W->getCond());
2033 AddDecl(W->getConditionVariable());
2034}
John Wiegley21ff2e52011-04-28 00:16:57 +00002035
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002036void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2037 AddTypeLoc(E->getQueriedTypeSourceInfo());
2038}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002039
2040void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002041 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002042 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002043}
2044
John Wiegley21ff2e52011-04-28 00:16:57 +00002045void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2046 AddTypeLoc(E->getQueriedTypeSourceInfo());
2047}
2048
John Wiegley55262202011-04-25 06:54:41 +00002049void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2050 EnqueueChildren(E);
2051}
2052
Ted Kremenek28a71942010-11-13 00:36:47 +00002053void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2054 VisitOverloadExpr(U);
2055 if (!U->isImplicitAccess())
2056 AddStmt(U->getBase());
2057}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002058void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2059 AddStmt(E->getSubExpr());
2060 AddTypeLoc(E->getWrittenTypeInfo());
2061}
Douglas Gregor94d96292011-01-19 20:34:17 +00002062void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2063 WL.push_back(SizeOfPackExprParts(E, Parent));
2064}
John McCall4b9c2d22011-11-06 09:01:30 +00002065void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2066 // If the opaque value has a source expression, just transparently
2067 // visit that. This is useful for (e.g.) pseudo-object expressions.
2068 if (Expr *SourceExpr = E->getSourceExpr())
2069 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002070}
2071void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2072 // Treat the expression like its syntactic form.
2073 Visit(E->getSyntacticForm());
2074}
Ted Kremenek60458782010-11-12 21:34:16 +00002075
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002076void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002077 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002078}
2079
2080bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2081 if (RegionOfInterest.isValid()) {
2082 SourceRange Range = getRawCursorExtent(C);
2083 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2084 return false;
2085 }
2086 return true;
2087}
2088
2089bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2090 while (!WL.empty()) {
2091 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002092 VisitorJob LI = WL.back();
2093 WL.pop_back();
2094
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002095 // Set the Parent field, then back to its old value once we're done.
2096 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2097
2098 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002099 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002100 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002101 if (!D)
2102 continue;
2103
2104 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002105 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2106 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002107 return true;
2108
2109 continue;
2110 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002111 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002112 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002113 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2114 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2115 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2116 Arg != ArgEnd; ++Arg) {
2117 if (VisitTemplateArgumentLoc(*Arg))
2118 return true;
2119 }
2120 continue;
2121 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002122 case VisitorJob::TypeLocVisitKind: {
2123 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002124 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002125 return true;
2126 continue;
2127 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002128 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002129 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002130 if (LabelStmt *stmt = LS->getStmt()) {
2131 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2132 TU))) {
2133 return true;
2134 }
2135 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002136 continue;
2137 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002138
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002139 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2140 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2141 if (VisitNestedNameSpecifierLoc(V->get()))
2142 return true;
2143 continue;
2144 }
2145
Ted Kremenekf64d8032010-11-18 00:02:32 +00002146 case VisitorJob::DeclarationNameInfoVisitKind: {
2147 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2148 ->get()))
2149 return true;
2150 continue;
2151 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002152 case VisitorJob::MemberRefVisitKind: {
2153 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2154 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2155 return true;
2156 continue;
2157 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002158 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002159 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002160 if (!S)
2161 continue;
2162
Ted Kremenekf1107452010-11-12 18:26:56 +00002163 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002164 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002165 if (!IsInRegionOfInterest(Cursor))
2166 continue;
2167 switch (Visitor(Cursor, Parent, ClientData)) {
2168 case CXChildVisit_Break: return true;
2169 case CXChildVisit_Continue: break;
2170 case CXChildVisit_Recurse:
2171 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002172 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002173 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002174 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002175 }
2176 case VisitorJob::MemberExprPartsKind: {
2177 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002178 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002179
2180 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002181 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2182 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002183 return true;
2184
2185 // Visit the declaration name.
2186 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2187 return true;
2188
2189 // Visit the explicitly-specified template arguments, if any.
2190 if (M->hasExplicitTemplateArgs()) {
2191 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2192 *ArgEnd = Arg + M->getNumTemplateArgs();
2193 Arg != ArgEnd; ++Arg) {
2194 if (VisitTemplateArgumentLoc(*Arg))
2195 return true;
2196 }
2197 }
2198 continue;
2199 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002200 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002201 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002202 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002203 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2204 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002205 return true;
2206 // Visit declaration name.
2207 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2208 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002209 continue;
2210 }
Ted Kremenek60458782010-11-12 21:34:16 +00002211 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002212 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002213 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002214 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2215 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002216 return true;
2217 // Visit the declaration name.
2218 if (VisitDeclarationNameInfo(O->getNameInfo()))
2219 return true;
2220 // Visit the overloaded declaration reference.
2221 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2222 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002223 continue;
2224 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002225 case VisitorJob::SizeOfPackExprPartsKind: {
2226 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2227 NamedDecl *Pack = E->getPack();
2228 if (isa<TemplateTypeParmDecl>(Pack)) {
2229 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2230 E->getPackLoc(), TU)))
2231 return true;
2232
2233 continue;
2234 }
2235
2236 if (isa<TemplateTemplateParmDecl>(Pack)) {
2237 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2238 E->getPackLoc(), TU)))
2239 return true;
2240
2241 continue;
2242 }
2243
2244 // Non-type template parameter packs and function parameter packs are
2245 // treated like DeclRefExpr cursors.
2246 continue;
2247 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002248 }
2249 }
2250 return false;
2251}
2252
Ted Kremenekcdba6592010-11-18 00:42:18 +00002253bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002254 VisitorWorkList *WL = 0;
2255 if (!WorkListFreeList.empty()) {
2256 WL = WorkListFreeList.back();
2257 WL->clear();
2258 WorkListFreeList.pop_back();
2259 }
2260 else {
2261 WL = new VisitorWorkList();
2262 WorkListCache.push_back(WL);
2263 }
2264 EnqueueWorkList(*WL, S);
2265 bool result = RunVisitorWorkList(*WL);
2266 WorkListFreeList.push_back(WL);
2267 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002268}
2269
Francois Pichet48a8d142011-07-25 22:00:44 +00002270namespace {
2271typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2272RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2273 const DeclarationNameInfo &NI,
2274 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002275 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002276 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2277 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2278 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2279
2280 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2281
2282 RefNamePieces Pieces;
2283
2284 if (WantQualifier && QLoc.isValid())
2285 Pieces.push_back(QLoc);
2286
2287 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2288 Pieces.push_back(NI.getLoc());
2289
2290 if (WantTemplateArgs && TemplateArgs)
2291 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2292 TemplateArgs->RAngleLoc));
2293
2294 if (Kind == DeclarationName::CXXOperatorName) {
2295 Pieces.push_back(SourceLocation::getFromRawEncoding(
2296 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2297 Pieces.push_back(SourceLocation::getFromRawEncoding(
2298 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2299 }
2300
2301 if (WantSinglePiece) {
2302 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2303 Pieces.clear();
2304 Pieces.push_back(R);
2305 }
2306
2307 return Pieces;
2308}
2309}
2310
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002311//===----------------------------------------------------------------------===//
2312// Misc. API hooks.
2313//===----------------------------------------------------------------------===//
2314
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002315static llvm::sys::Mutex EnableMultithreadingMutex;
2316static bool EnabledMultithreading;
2317
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002318static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002319 // Write the result out to stderr avoiding errs() because raw_ostreams can
2320 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002321 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002322 ::abort();
2323}
2324
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002325extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002326CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2327 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002328 // Disable pretty stack trace functionality, which will otherwise be a very
2329 // poor citizen of the world and set up all sorts of signal handlers.
2330 llvm::DisablePrettyStackTrace = true;
2331
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002332 // We use crash recovery to make some of our APIs more reliable, implicitly
2333 // enable it.
2334 llvm::CrashRecoveryContext::Enable();
2335
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002336 // Enable support for multithreading in LLVM.
2337 {
2338 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2339 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002340 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002341 llvm::llvm_start_multithreaded();
2342 EnabledMultithreading = true;
2343 }
2344 }
2345
Douglas Gregora030b7c2010-01-22 20:35:53 +00002346 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002347 if (excludeDeclarationsFromPCH)
2348 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002349 if (displayDiagnostics)
2350 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002351 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002352}
2353
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002354void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002355 if (CIdx)
2356 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002357}
2358
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002359void clang_toggleCrashRecovery(unsigned isEnabled) {
2360 if (isEnabled)
2361 llvm::CrashRecoveryContext::Enable();
2362 else
2363 llvm::CrashRecoveryContext::Disable();
2364}
2365
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002366CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002367 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002368 if (!CIdx)
2369 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002370
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002371 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002372 FileSystemOptions FileSystemOpts;
2373 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002374
David Blaikied6471f72011-09-25 23:23:43 +00002375 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002376 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002377 CXXIdx->getOnlyLocalDecls(),
2378 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002379 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002380}
2381
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002382unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002383 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002384 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002385}
2386
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002387CXTranslationUnit
2388clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2389 const char *source_filename,
2390 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002391 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002392 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002393 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002394 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002395 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002396 return clang_parseTranslationUnit(CIdx, source_filename,
2397 command_line_args, num_command_line_args,
2398 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002399 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002400}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002401
2402struct ParseTranslationUnitInfo {
2403 CXIndex CIdx;
2404 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002405 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002406 int num_command_line_args;
2407 struct CXUnsavedFile *unsaved_files;
2408 unsigned num_unsaved_files;
2409 unsigned options;
2410 CXTranslationUnit result;
2411};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002412static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002413 ParseTranslationUnitInfo *PTUI =
2414 static_cast<ParseTranslationUnitInfo*>(UserData);
2415 CXIndex CIdx = PTUI->CIdx;
2416 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002417 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002418 int num_command_line_args = PTUI->num_command_line_args;
2419 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2420 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2421 unsigned options = PTUI->options;
2422 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002423
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002424 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002425 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002426
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002427 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2428
Douglas Gregor44c181a2010-07-23 00:33:23 +00002429 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002430 // FIXME: Add a flag for modules.
2431 TranslationUnitKind TUKind
2432 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002433 bool CacheCodeCompetionResults
2434 = options & CXTranslationUnit_CacheCompletionResults;
2435
Douglas Gregor5352ac02010-01-28 00:27:43 +00002436 // Configure the diagnostics.
2437 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002438 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002439 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2440 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441
Ted Kremenek25a11e12011-03-22 01:15:24 +00002442 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002443 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2444 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002445 DiagCleanup(Diags.getPtr());
2446
2447 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2448 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2449
2450 // Recover resources if we crash before exiting this function.
2451 llvm::CrashRecoveryContextCleanupRegistrar<
2452 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2453
Douglas Gregor4db64a42010-01-23 00:14:00 +00002454 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002455 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002456 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002457 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002458 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2459 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002460 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002461
Ted Kremenek25a11e12011-03-22 01:15:24 +00002462 llvm::OwningPtr<std::vector<const char *> >
2463 Args(new std::vector<const char*>());
2464
2465 // Recover resources if we crash before exiting this method.
2466 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2467 ArgsCleanup(Args.get());
2468
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002469 // Since the Clang C library is primarily used by batch tools dealing with
2470 // (often very broken) source code, where spell-checking can have a
2471 // significant negative impact on performance (particularly when
2472 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002473 // Only do this if we haven't found a spell-checking-related argument.
2474 bool FoundSpellCheckingArgument = false;
2475 for (int I = 0; I != num_command_line_args; ++I) {
2476 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2477 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2478 FoundSpellCheckingArgument = true;
2479 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002480 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002481 }
2482 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002483 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002484
Ted Kremenek25a11e12011-03-22 01:15:24 +00002485 Args->insert(Args->end(), command_line_args,
2486 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002487
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002488 // The 'source_filename' argument is optional. If the caller does not
2489 // specify it then it is assumed that the source file is specified
2490 // in the actual argument list.
2491 // Put the source file after command_line_args otherwise if '-x' flag is
2492 // present it will be unused.
2493 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002494 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002495
Douglas Gregor44c181a2010-07-23 00:33:23 +00002496 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002497 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002498 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002499 Args->push_back("-Xclang");
2500 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002501 NestedMacroExpansions
2502 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002503 }
2504
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002505 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002506 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002507 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2508 /* vector::data() not portable */,
2509 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002510 Diags,
2511 CXXIdx->getClangResourcesPath(),
2512 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002513 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002514 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002515 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002516 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002517 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002518 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002519 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002520 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002521
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002522 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002523 // Make sure to check that 'Unit' is non-NULL.
2524 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2525 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2526 DEnd = Unit->stored_diag_end();
2527 D != DEnd; ++D) {
2528 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2529 CXString Msg = clang_formatDiagnostic(&Diag,
2530 clang_defaultDiagnosticDisplayOptions());
2531 fprintf(stderr, "%s\n", clang_getCString(Msg));
2532 clang_disposeString(Msg);
2533 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002534#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002535 // On Windows, force a flush, since there may be multiple copies of
2536 // stderr and stdout in the file system, all with different buffers
2537 // but writing to the same device.
2538 fflush(stderr);
2539#endif
2540 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002541 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002542
Ted Kremeneka60ed472010-11-16 08:15:36 +00002543 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002544}
2545CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2546 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002547 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002548 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002549 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002550 unsigned num_unsaved_files,
2551 unsigned options) {
2552 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002553 num_command_line_args, unsaved_files,
2554 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002555 llvm::CrashRecoveryContext CRC;
2556
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002557 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002558 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2559 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2560 fprintf(stderr, " 'command_line_args' : [");
2561 for (int i = 0; i != num_command_line_args; ++i) {
2562 if (i)
2563 fprintf(stderr, ", ");
2564 fprintf(stderr, "'%s'", command_line_args[i]);
2565 }
2566 fprintf(stderr, "],\n");
2567 fprintf(stderr, " 'unsaved_files' : [");
2568 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2569 if (i)
2570 fprintf(stderr, ", ");
2571 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2572 unsaved_files[i].Length);
2573 }
2574 fprintf(stderr, "],\n");
2575 fprintf(stderr, " 'options' : %d,\n", options);
2576 fprintf(stderr, "}\n");
2577
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002578 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002579 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2580 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002581 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002582
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002583 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002584}
2585
Douglas Gregor19998442010-08-13 15:35:05 +00002586unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2587 return CXSaveTranslationUnit_None;
2588}
2589
2590int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2591 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002592 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002593 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002594
Douglas Gregor39c411f2011-07-06 16:43:36 +00002595 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002596 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2597 PrintLibclangResourceUsage(TU);
2598 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002599}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002600
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002601void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002602 if (CTUnit) {
2603 // If the translation unit has been marked as unsafe to free, just discard
2604 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002605 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002606 return;
2607
Ted Kremeneka60ed472010-11-16 08:15:36 +00002608 delete static_cast<ASTUnit *>(CTUnit->TUData);
2609 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002610 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002611 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002612 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002613}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002614
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002615unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2616 return CXReparse_None;
2617}
2618
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002619struct ReparseTranslationUnitInfo {
2620 CXTranslationUnit TU;
2621 unsigned num_unsaved_files;
2622 struct CXUnsavedFile *unsaved_files;
2623 unsigned options;
2624 int result;
2625};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002626
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002627static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002628 ReparseTranslationUnitInfo *RTUI =
2629 static_cast<ReparseTranslationUnitInfo*>(UserData);
2630 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002631
2632 // Reset the associated diagnostics.
2633 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2634 TU->Diagnostics = 0;
2635
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002636 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2637 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2638 unsigned options = RTUI->options;
2639 (void) options;
2640 RTUI->result = 1;
2641
Douglas Gregorabc563f2010-07-19 21:46:24 +00002642 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002643 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002644
Ted Kremeneka60ed472010-11-16 08:15:36 +00002645 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002646 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002647
Ted Kremenek25a11e12011-03-22 01:15:24 +00002648 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2649 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2650
2651 // Recover resources if we crash before exiting this function.
2652 llvm::CrashRecoveryContextCleanupRegistrar<
2653 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2654
Douglas Gregorabc563f2010-07-19 21:46:24 +00002655 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002656 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002657 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002658 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002659 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2660 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002661 }
2662
Ted Kremenek4ee99262011-03-22 20:16:19 +00002663 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2664 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002665 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002666}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002667
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002668int clang_reparseTranslationUnit(CXTranslationUnit TU,
2669 unsigned num_unsaved_files,
2670 struct CXUnsavedFile *unsaved_files,
2671 unsigned options) {
2672 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2673 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002674
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002675 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002676 clang_reparseTranslationUnit_Impl(&RTUI);
2677 return RTUI.result;
2678 }
2679
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002680 llvm::CrashRecoveryContext CRC;
2681
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002682 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002683 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002684 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002685 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002686 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2687 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002688
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002689 return RTUI.result;
2690}
2691
Douglas Gregordf95a132010-08-09 20:45:32 +00002692
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002693CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002694 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002695 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002696
Ted Kremeneka60ed472010-11-16 08:15:36 +00002697 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002698 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002699}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002700
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002701CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002702 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002703 return Result;
2704}
2705
Ted Kremenekfb480492010-01-13 21:46:36 +00002706} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002707
Ted Kremenekfb480492010-01-13 21:46:36 +00002708//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002709// CXFile Operations.
2710//===----------------------------------------------------------------------===//
2711
2712extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002713CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002714 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002715 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002716
Steve Naroff88145032009-10-27 14:35:18 +00002717 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002718 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002719}
2720
2721time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002722 if (!SFile)
2723 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002724
Steve Naroff88145032009-10-27 14:35:18 +00002725 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2726 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002727}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002728
Douglas Gregorb9790342010-01-22 21:44:22 +00002729CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2730 if (!tu)
2731 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002732
Ted Kremeneka60ed472010-11-16 08:15:36 +00002733 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002734
Douglas Gregorb9790342010-01-22 21:44:22 +00002735 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002736 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002737}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002738
Douglas Gregordd3e5542011-05-04 00:14:37 +00002739unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2740 if (!tu || !file)
2741 return 0;
2742
2743 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2744 FileEntry *FEnt = static_cast<FileEntry *>(file);
2745 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2746 .isFileMultipleIncludeGuarded(FEnt);
2747}
2748
Ted Kremenekfb480492010-01-13 21:46:36 +00002749} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002750
Ted Kremenekfb480492010-01-13 21:46:36 +00002751//===----------------------------------------------------------------------===//
2752// CXCursor Operations.
2753//===----------------------------------------------------------------------===//
2754
Ted Kremenekfb480492010-01-13 21:46:36 +00002755static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002756 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002757 return getDeclFromExpr(CE->getSubExpr());
2758
Ted Kremenekfb480492010-01-13 21:46:36 +00002759 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2760 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002761 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2762 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002763 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2764 return ME->getMemberDecl();
2765 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2766 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002767 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002768 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002769 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2770 return getDeclFromExpr(POE->getSyntacticForm());
2771 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2772 if (Expr *Src = OVE->getSourceExpr())
2773 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002774
Ted Kremenekfb480492010-01-13 21:46:36 +00002775 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2776 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002777 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002778 if (!CE->isElidable())
2779 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002780 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2781 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002782
Douglas Gregordb1314e2010-10-01 21:11:22 +00002783 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2784 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002785 if (SubstNonTypeTemplateParmPackExpr *NTTP
2786 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2787 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002788 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2789 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2790 isa<ParmVarDecl>(SizeOfPack->getPack()))
2791 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002792
Ted Kremenekfb480492010-01-13 21:46:36 +00002793 return 0;
2794}
2795
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002796static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002797 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2798 return getLocationFromExpr(CE->getSubExpr());
2799
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002800 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2801 return /*FIXME:*/Msg->getLeftLoc();
2802 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2803 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002804 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2805 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002806 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2807 return Member->getMemberLoc();
2808 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2809 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002810 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2811 return SizeOfPack->getPackLoc();
2812
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002813 return E->getLocStart();
2814}
2815
Ted Kremenekfb480492010-01-13 21:46:36 +00002816extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002817
2818unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002819 CXCursorVisitor visitor,
2820 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002821 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2822 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002823 return CursorVis.VisitChildren(parent);
2824}
2825
David Chisnall3387c652010-11-03 14:12:26 +00002826#ifndef __has_feature
2827#define __has_feature(x) 0
2828#endif
2829#if __has_feature(blocks)
2830typedef enum CXChildVisitResult
2831 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2832
2833static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2834 CXClientData client_data) {
2835 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2836 return block(cursor, parent);
2837}
2838#else
2839// If we are compiled with a compiler that doesn't have native blocks support,
2840// define and call the block manually, so the
2841typedef struct _CXChildVisitResult
2842{
2843 void *isa;
2844 int flags;
2845 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002846 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2847 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002848} *CXCursorVisitorBlock;
2849
2850static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2851 CXClientData client_data) {
2852 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2853 return block->invoke(block, cursor, parent);
2854}
2855#endif
2856
2857
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002858unsigned clang_visitChildrenWithBlock(CXCursor parent,
2859 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002860 return clang_visitChildren(parent, visitWithBlock, block);
2861}
2862
Douglas Gregor78205d42010-01-20 21:45:58 +00002863static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00002864 if (!D)
2865 return createCXString("");
2866
2867 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002868 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002869 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002870 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2871 return createCXString(Property->getIdentifier()->getName());
2872
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002873 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002874 }
2875
Douglas Gregor78205d42010-01-20 21:45:58 +00002876 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002877 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002878
Douglas Gregor78205d42010-01-20 21:45:58 +00002879 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2880 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2881 // and returns different names. NamedDecl returns the class name and
2882 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002883 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002884
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002885 if (isa<UsingDirectiveDecl>(D))
2886 return createCXString("");
2887
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002888 llvm::SmallString<1024> S;
2889 llvm::raw_svector_ostream os(S);
2890 ND->printName(os);
2891
2892 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002893}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002894
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002895CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002896 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002897 return clang_getTranslationUnitSpelling(
2898 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002899
Steve Narofff334b4e2009-09-02 18:26:48 +00002900 if (clang_isReference(C.kind)) {
2901 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002902 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002903 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002904 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002905 }
2906 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002907 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002908 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002909 }
2910 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002911 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002912 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002913 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002914 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002915 case CXCursor_CXXBaseSpecifier: {
2916 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2917 return createCXString(B->getType().getAsString());
2918 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002919 case CXCursor_TypeRef: {
2920 TypeDecl *Type = getCursorTypeRef(C).first;
2921 assert(Type && "Missing type decl");
2922
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002923 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2924 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002925 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002926 case CXCursor_TemplateRef: {
2927 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002928 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002929
2930 return createCXString(Template->getNameAsString());
2931 }
Douglas Gregor69319002010-08-31 23:48:11 +00002932
2933 case CXCursor_NamespaceRef: {
2934 NamedDecl *NS = getCursorNamespaceRef(C).first;
2935 assert(NS && "Missing namespace decl");
2936
2937 return createCXString(NS->getNameAsString());
2938 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002939
Douglas Gregora67e03f2010-09-09 21:42:20 +00002940 case CXCursor_MemberRef: {
2941 FieldDecl *Field = getCursorMemberRef(C).first;
2942 assert(Field && "Missing member decl");
2943
2944 return createCXString(Field->getNameAsString());
2945 }
2946
Douglas Gregor36897b02010-09-10 00:22:18 +00002947 case CXCursor_LabelRef: {
2948 LabelStmt *Label = getCursorLabelRef(C).first;
2949 assert(Label && "Missing label");
2950
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002951 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002952 }
2953
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002954 case CXCursor_OverloadedDeclRef: {
2955 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2956 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2957 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2958 return createCXString(ND->getNameAsString());
2959 return createCXString("");
2960 }
2961 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2962 return createCXString(E->getName().getAsString());
2963 OverloadedTemplateStorage *Ovl
2964 = Storage.get<OverloadedTemplateStorage*>();
2965 if (Ovl->size() == 0)
2966 return createCXString("");
2967 return createCXString((*Ovl->begin())->getNameAsString());
2968 }
2969
Daniel Dunbaracca7252009-11-30 20:42:49 +00002970 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002971 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002972 }
2973 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002974
2975 if (clang_isExpression(C.kind)) {
2976 Decl *D = getDeclFromExpr(getCursorExpr(C));
2977 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002978 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002979 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002980 }
2981
Douglas Gregor36897b02010-09-10 00:22:18 +00002982 if (clang_isStatement(C.kind)) {
2983 Stmt *S = getCursorStmt(C);
2984 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002985 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002986
2987 return createCXString("");
2988 }
2989
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002990 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002991 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002992 ->getNameStart());
2993
Douglas Gregor572feb22010-03-18 18:04:21 +00002994 if (C.kind == CXCursor_MacroDefinition)
2995 return createCXString(getCursorMacroDefinition(C)->getName()
2996 ->getNameStart());
2997
Douglas Gregorecdcb882010-10-20 22:00:55 +00002998 if (C.kind == CXCursor_InclusionDirective)
2999 return createCXString(getCursorInclusionDirective(C)->getFileName());
3000
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003001 if (clang_isDeclaration(C.kind))
3002 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003003
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003004 if (C.kind == CXCursor_AnnotateAttr) {
3005 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3006 return createCXString(AA->getAnnotation());
3007 }
3008
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003009 if (C.kind == CXCursor_AsmLabelAttr) {
3010 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3011 return createCXString(AA->getLabel());
3012 }
3013
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003014 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003015}
3016
Douglas Gregor358559d2010-10-02 22:49:11 +00003017CXString clang_getCursorDisplayName(CXCursor C) {
3018 if (!clang_isDeclaration(C.kind))
3019 return clang_getCursorSpelling(C);
3020
3021 Decl *D = getCursorDecl(C);
3022 if (!D)
3023 return createCXString("");
3024
Douglas Gregor30c42402011-09-27 22:38:19 +00003025 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003026 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3027 D = FunTmpl->getTemplatedDecl();
3028
3029 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3030 llvm::SmallString<64> Str;
3031 llvm::raw_svector_ostream OS(Str);
3032 OS << Function->getNameAsString();
3033 if (Function->getPrimaryTemplate())
3034 OS << "<>";
3035 OS << "(";
3036 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3037 if (I)
3038 OS << ", ";
3039 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3040 }
3041
3042 if (Function->isVariadic()) {
3043 if (Function->getNumParams())
3044 OS << ", ";
3045 OS << "...";
3046 }
3047 OS << ")";
3048 return createCXString(OS.str());
3049 }
3050
3051 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3052 llvm::SmallString<64> Str;
3053 llvm::raw_svector_ostream OS(Str);
3054 OS << ClassTemplate->getNameAsString();
3055 OS << "<";
3056 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3057 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3058 if (I)
3059 OS << ", ";
3060
3061 NamedDecl *Param = Params->getParam(I);
3062 if (Param->getIdentifier()) {
3063 OS << Param->getIdentifier()->getName();
3064 continue;
3065 }
3066
3067 // There is no parameter name, which makes this tricky. Try to come up
3068 // with something useful that isn't too long.
3069 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3070 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3071 else if (NonTypeTemplateParmDecl *NTTP
3072 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3073 OS << NTTP->getType().getAsString(Policy);
3074 else
3075 OS << "template<...> class";
3076 }
3077
3078 OS << ">";
3079 return createCXString(OS.str());
3080 }
3081
3082 if (ClassTemplateSpecializationDecl *ClassSpec
3083 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3084 // If the type was explicitly written, use that.
3085 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3086 return createCXString(TSInfo->getType().getAsString(Policy));
3087
3088 llvm::SmallString<64> Str;
3089 llvm::raw_svector_ostream OS(Str);
3090 OS << ClassSpec->getNameAsString();
3091 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003092 ClassSpec->getTemplateArgs().data(),
3093 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003094 Policy);
3095 return createCXString(OS.str());
3096 }
3097
3098 return clang_getCursorSpelling(C);
3099}
3100
Ted Kremeneke68fff62010-02-17 00:41:32 +00003101CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003102 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003103 case CXCursor_FunctionDecl:
3104 return createCXString("FunctionDecl");
3105 case CXCursor_TypedefDecl:
3106 return createCXString("TypedefDecl");
3107 case CXCursor_EnumDecl:
3108 return createCXString("EnumDecl");
3109 case CXCursor_EnumConstantDecl:
3110 return createCXString("EnumConstantDecl");
3111 case CXCursor_StructDecl:
3112 return createCXString("StructDecl");
3113 case CXCursor_UnionDecl:
3114 return createCXString("UnionDecl");
3115 case CXCursor_ClassDecl:
3116 return createCXString("ClassDecl");
3117 case CXCursor_FieldDecl:
3118 return createCXString("FieldDecl");
3119 case CXCursor_VarDecl:
3120 return createCXString("VarDecl");
3121 case CXCursor_ParmDecl:
3122 return createCXString("ParmDecl");
3123 case CXCursor_ObjCInterfaceDecl:
3124 return createCXString("ObjCInterfaceDecl");
3125 case CXCursor_ObjCCategoryDecl:
3126 return createCXString("ObjCCategoryDecl");
3127 case CXCursor_ObjCProtocolDecl:
3128 return createCXString("ObjCProtocolDecl");
3129 case CXCursor_ObjCPropertyDecl:
3130 return createCXString("ObjCPropertyDecl");
3131 case CXCursor_ObjCIvarDecl:
3132 return createCXString("ObjCIvarDecl");
3133 case CXCursor_ObjCInstanceMethodDecl:
3134 return createCXString("ObjCInstanceMethodDecl");
3135 case CXCursor_ObjCClassMethodDecl:
3136 return createCXString("ObjCClassMethodDecl");
3137 case CXCursor_ObjCImplementationDecl:
3138 return createCXString("ObjCImplementationDecl");
3139 case CXCursor_ObjCCategoryImplDecl:
3140 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003141 case CXCursor_CXXMethod:
3142 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003143 case CXCursor_UnexposedDecl:
3144 return createCXString("UnexposedDecl");
3145 case CXCursor_ObjCSuperClassRef:
3146 return createCXString("ObjCSuperClassRef");
3147 case CXCursor_ObjCProtocolRef:
3148 return createCXString("ObjCProtocolRef");
3149 case CXCursor_ObjCClassRef:
3150 return createCXString("ObjCClassRef");
3151 case CXCursor_TypeRef:
3152 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003153 case CXCursor_TemplateRef:
3154 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003155 case CXCursor_NamespaceRef:
3156 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003157 case CXCursor_MemberRef:
3158 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003159 case CXCursor_LabelRef:
3160 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003161 case CXCursor_OverloadedDeclRef:
3162 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003163 case CXCursor_IntegerLiteral:
3164 return createCXString("IntegerLiteral");
3165 case CXCursor_FloatingLiteral:
3166 return createCXString("FloatingLiteral");
3167 case CXCursor_ImaginaryLiteral:
3168 return createCXString("ImaginaryLiteral");
3169 case CXCursor_StringLiteral:
3170 return createCXString("StringLiteral");
3171 case CXCursor_CharacterLiteral:
3172 return createCXString("CharacterLiteral");
3173 case CXCursor_ParenExpr:
3174 return createCXString("ParenExpr");
3175 case CXCursor_UnaryOperator:
3176 return createCXString("UnaryOperator");
3177 case CXCursor_ArraySubscriptExpr:
3178 return createCXString("ArraySubscriptExpr");
3179 case CXCursor_BinaryOperator:
3180 return createCXString("BinaryOperator");
3181 case CXCursor_CompoundAssignOperator:
3182 return createCXString("CompoundAssignOperator");
3183 case CXCursor_ConditionalOperator:
3184 return createCXString("ConditionalOperator");
3185 case CXCursor_CStyleCastExpr:
3186 return createCXString("CStyleCastExpr");
3187 case CXCursor_CompoundLiteralExpr:
3188 return createCXString("CompoundLiteralExpr");
3189 case CXCursor_InitListExpr:
3190 return createCXString("InitListExpr");
3191 case CXCursor_AddrLabelExpr:
3192 return createCXString("AddrLabelExpr");
3193 case CXCursor_StmtExpr:
3194 return createCXString("StmtExpr");
3195 case CXCursor_GenericSelectionExpr:
3196 return createCXString("GenericSelectionExpr");
3197 case CXCursor_GNUNullExpr:
3198 return createCXString("GNUNullExpr");
3199 case CXCursor_CXXStaticCastExpr:
3200 return createCXString("CXXStaticCastExpr");
3201 case CXCursor_CXXDynamicCastExpr:
3202 return createCXString("CXXDynamicCastExpr");
3203 case CXCursor_CXXReinterpretCastExpr:
3204 return createCXString("CXXReinterpretCastExpr");
3205 case CXCursor_CXXConstCastExpr:
3206 return createCXString("CXXConstCastExpr");
3207 case CXCursor_CXXFunctionalCastExpr:
3208 return createCXString("CXXFunctionalCastExpr");
3209 case CXCursor_CXXTypeidExpr:
3210 return createCXString("CXXTypeidExpr");
3211 case CXCursor_CXXBoolLiteralExpr:
3212 return createCXString("CXXBoolLiteralExpr");
3213 case CXCursor_CXXNullPtrLiteralExpr:
3214 return createCXString("CXXNullPtrLiteralExpr");
3215 case CXCursor_CXXThisExpr:
3216 return createCXString("CXXThisExpr");
3217 case CXCursor_CXXThrowExpr:
3218 return createCXString("CXXThrowExpr");
3219 case CXCursor_CXXNewExpr:
3220 return createCXString("CXXNewExpr");
3221 case CXCursor_CXXDeleteExpr:
3222 return createCXString("CXXDeleteExpr");
3223 case CXCursor_UnaryExpr:
3224 return createCXString("UnaryExpr");
3225 case CXCursor_ObjCStringLiteral:
3226 return createCXString("ObjCStringLiteral");
3227 case CXCursor_ObjCEncodeExpr:
3228 return createCXString("ObjCEncodeExpr");
3229 case CXCursor_ObjCSelectorExpr:
3230 return createCXString("ObjCSelectorExpr");
3231 case CXCursor_ObjCProtocolExpr:
3232 return createCXString("ObjCProtocolExpr");
3233 case CXCursor_ObjCBridgedCastExpr:
3234 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003235 case CXCursor_BlockExpr:
3236 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003237 case CXCursor_PackExpansionExpr:
3238 return createCXString("PackExpansionExpr");
3239 case CXCursor_SizeOfPackExpr:
3240 return createCXString("SizeOfPackExpr");
3241 case CXCursor_UnexposedExpr:
3242 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003243 case CXCursor_DeclRefExpr:
3244 return createCXString("DeclRefExpr");
3245 case CXCursor_MemberRefExpr:
3246 return createCXString("MemberRefExpr");
3247 case CXCursor_CallExpr:
3248 return createCXString("CallExpr");
3249 case CXCursor_ObjCMessageExpr:
3250 return createCXString("ObjCMessageExpr");
3251 case CXCursor_UnexposedStmt:
3252 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003253 case CXCursor_DeclStmt:
3254 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003255 case CXCursor_LabelStmt:
3256 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003257 case CXCursor_CompoundStmt:
3258 return createCXString("CompoundStmt");
3259 case CXCursor_CaseStmt:
3260 return createCXString("CaseStmt");
3261 case CXCursor_DefaultStmt:
3262 return createCXString("DefaultStmt");
3263 case CXCursor_IfStmt:
3264 return createCXString("IfStmt");
3265 case CXCursor_SwitchStmt:
3266 return createCXString("SwitchStmt");
3267 case CXCursor_WhileStmt:
3268 return createCXString("WhileStmt");
3269 case CXCursor_DoStmt:
3270 return createCXString("DoStmt");
3271 case CXCursor_ForStmt:
3272 return createCXString("ForStmt");
3273 case CXCursor_GotoStmt:
3274 return createCXString("GotoStmt");
3275 case CXCursor_IndirectGotoStmt:
3276 return createCXString("IndirectGotoStmt");
3277 case CXCursor_ContinueStmt:
3278 return createCXString("ContinueStmt");
3279 case CXCursor_BreakStmt:
3280 return createCXString("BreakStmt");
3281 case CXCursor_ReturnStmt:
3282 return createCXString("ReturnStmt");
3283 case CXCursor_AsmStmt:
3284 return createCXString("AsmStmt");
3285 case CXCursor_ObjCAtTryStmt:
3286 return createCXString("ObjCAtTryStmt");
3287 case CXCursor_ObjCAtCatchStmt:
3288 return createCXString("ObjCAtCatchStmt");
3289 case CXCursor_ObjCAtFinallyStmt:
3290 return createCXString("ObjCAtFinallyStmt");
3291 case CXCursor_ObjCAtThrowStmt:
3292 return createCXString("ObjCAtThrowStmt");
3293 case CXCursor_ObjCAtSynchronizedStmt:
3294 return createCXString("ObjCAtSynchronizedStmt");
3295 case CXCursor_ObjCAutoreleasePoolStmt:
3296 return createCXString("ObjCAutoreleasePoolStmt");
3297 case CXCursor_ObjCForCollectionStmt:
3298 return createCXString("ObjCForCollectionStmt");
3299 case CXCursor_CXXCatchStmt:
3300 return createCXString("CXXCatchStmt");
3301 case CXCursor_CXXTryStmt:
3302 return createCXString("CXXTryStmt");
3303 case CXCursor_CXXForRangeStmt:
3304 return createCXString("CXXForRangeStmt");
3305 case CXCursor_SEHTryStmt:
3306 return createCXString("SEHTryStmt");
3307 case CXCursor_SEHExceptStmt:
3308 return createCXString("SEHExceptStmt");
3309 case CXCursor_SEHFinallyStmt:
3310 return createCXString("SEHFinallyStmt");
3311 case CXCursor_NullStmt:
3312 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003313 case CXCursor_InvalidFile:
3314 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003315 case CXCursor_InvalidCode:
3316 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003317 case CXCursor_NoDeclFound:
3318 return createCXString("NoDeclFound");
3319 case CXCursor_NotImplemented:
3320 return createCXString("NotImplemented");
3321 case CXCursor_TranslationUnit:
3322 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003323 case CXCursor_UnexposedAttr:
3324 return createCXString("UnexposedAttr");
3325 case CXCursor_IBActionAttr:
3326 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003327 case CXCursor_IBOutletAttr:
3328 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003329 case CXCursor_IBOutletCollectionAttr:
3330 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003331 case CXCursor_CXXFinalAttr:
3332 return createCXString("attribute(final)");
3333 case CXCursor_CXXOverrideAttr:
3334 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003335 case CXCursor_AnnotateAttr:
3336 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003337 case CXCursor_AsmLabelAttr:
3338 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003339 case CXCursor_PreprocessingDirective:
3340 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003341 case CXCursor_MacroDefinition:
3342 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003343 case CXCursor_MacroExpansion:
3344 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003345 case CXCursor_InclusionDirective:
3346 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003347 case CXCursor_Namespace:
3348 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003349 case CXCursor_LinkageSpec:
3350 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003351 case CXCursor_CXXBaseSpecifier:
3352 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003353 case CXCursor_Constructor:
3354 return createCXString("CXXConstructor");
3355 case CXCursor_Destructor:
3356 return createCXString("CXXDestructor");
3357 case CXCursor_ConversionFunction:
3358 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003359 case CXCursor_TemplateTypeParameter:
3360 return createCXString("TemplateTypeParameter");
3361 case CXCursor_NonTypeTemplateParameter:
3362 return createCXString("NonTypeTemplateParameter");
3363 case CXCursor_TemplateTemplateParameter:
3364 return createCXString("TemplateTemplateParameter");
3365 case CXCursor_FunctionTemplate:
3366 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003367 case CXCursor_ClassTemplate:
3368 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003369 case CXCursor_ClassTemplatePartialSpecialization:
3370 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003371 case CXCursor_NamespaceAlias:
3372 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003373 case CXCursor_UsingDirective:
3374 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003375 case CXCursor_UsingDeclaration:
3376 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003377 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003378 return createCXString("TypeAliasDecl");
3379 case CXCursor_ObjCSynthesizeDecl:
3380 return createCXString("ObjCSynthesizeDecl");
3381 case CXCursor_ObjCDynamicDecl:
3382 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003383 case CXCursor_CXXAccessSpecifier:
3384 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003385 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003386
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003387 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003388 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003389}
Steve Naroff89922f82009-08-31 00:59:03 +00003390
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003391struct GetCursorData {
3392 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003393 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003394 CXCursor &BestCursor;
3395
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003396 GetCursorData(SourceManager &SM,
3397 SourceLocation tokenBegin, CXCursor &outputCursor)
3398 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3399 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3400 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003401};
3402
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003403static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3404 CXCursor parent,
3405 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003406 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3407 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003408
3409 // If we point inside a macro argument we should provide info of what the
3410 // token is so use the actual cursor, don't replace it with a macro expansion
3411 // cursor.
3412 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3413 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003414
3415 if (clang_isDeclaration(cursor.kind)) {
3416 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003417 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003418 if (MD->isImplicit())
3419 return CXChildVisit_Break;
3420 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003421
3422 if (clang_isExpression(cursor.kind) &&
3423 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003424 if (Decl *D = getCursorDecl(*BestCursor)) {
3425 // Avoid having the cursor of an expression replace the declaration cursor
3426 // when the expression source range overlaps the declaration range.
3427 // This can happen for C++ constructor expressions whose range generally
3428 // include the variable declaration, e.g.:
3429 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3430 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3431 D->getLocation() == Data->TokenBeginLoc)
3432 return CXChildVisit_Break;
3433 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003434 }
3435
Douglas Gregor93798e22010-11-05 21:11:19 +00003436 // If our current best cursor is the construction of a temporary object,
3437 // don't replace that cursor with a type reference, because we want
3438 // clang_getCursor() to point at the constructor.
3439 if (clang_isExpression(BestCursor->kind) &&
3440 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003441 cursor.kind == CXCursor_TypeRef) {
3442 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3443 // as having the actual point on the type reference.
3444 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003445 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003446 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003447
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003448 *BestCursor = cursor;
3449 return CXChildVisit_Recurse;
3450}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003451
Douglas Gregorb9790342010-01-22 21:44:22 +00003452CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3453 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003454 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003455
Ted Kremeneka60ed472010-11-16 08:15:36 +00003456 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003457 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3458
Ted Kremeneka297de22010-01-25 22:34:44 +00003459 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003460 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003461
Douglas Gregor40749ee2010-11-03 00:35:38 +00003462 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003463 if (Logging) {
3464 CXFile SearchFile;
3465 unsigned SearchLine, SearchColumn;
3466 CXFile ResultFile;
3467 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003468 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3469 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003470 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3471
Chandler Carruth20174222011-08-31 16:53:37 +00003472 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3473 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3474 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003475 SearchFileName = clang_getFileName(SearchFile);
3476 ResultFileName = clang_getFileName(ResultFile);
3477 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003478 USR = clang_getCursorUSR(Result);
3479 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003480 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3481 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003482 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3483 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003484 clang_disposeString(SearchFileName);
3485 clang_disposeString(ResultFileName);
3486 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003487 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003488
3489 CXCursor Definition = clang_getCursorDefinition(Result);
3490 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3491 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3492 CXString DefinitionKindSpelling
3493 = clang_getCursorKindSpelling(Definition.kind);
3494 CXFile DefinitionFile;
3495 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003496 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3497 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003498 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3499 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3500 clang_getCString(DefinitionKindSpelling),
3501 clang_getCString(DefinitionFileName),
3502 DefinitionLine, DefinitionColumn);
3503 clang_disposeString(DefinitionFileName);
3504 clang_disposeString(DefinitionKindSpelling);
3505 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003506 }
3507
Ted Kremeneke68fff62010-02-17 00:41:32 +00003508 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003509}
3510
Ted Kremenek73885552009-11-17 19:28:59 +00003511CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003512 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003513}
3514
3515unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003516 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003517}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003518
Douglas Gregor9ce55842010-11-20 00:09:34 +00003519unsigned clang_hashCursor(CXCursor C) {
3520 unsigned Index = 0;
3521 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3522 Index = 1;
3523
3524 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3525 std::make_pair(C.kind, C.data[Index]));
3526}
3527
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003528unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003529 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3530}
3531
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003532unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003533 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3534}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003535
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003536unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003537 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3538}
3539
Douglas Gregor97b98722010-01-19 23:20:36 +00003540unsigned clang_isExpression(enum CXCursorKind K) {
3541 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3542}
3543
3544unsigned clang_isStatement(enum CXCursorKind K) {
3545 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3546}
3547
Douglas Gregor8be80e12011-07-06 03:00:34 +00003548unsigned clang_isAttribute(enum CXCursorKind K) {
3549 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3550}
3551
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003552unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3553 return K == CXCursor_TranslationUnit;
3554}
3555
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003556unsigned clang_isPreprocessing(enum CXCursorKind K) {
3557 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3558}
3559
Ted Kremenekad6eff62010-03-08 21:17:29 +00003560unsigned clang_isUnexposed(enum CXCursorKind K) {
3561 switch (K) {
3562 case CXCursor_UnexposedDecl:
3563 case CXCursor_UnexposedExpr:
3564 case CXCursor_UnexposedStmt:
3565 case CXCursor_UnexposedAttr:
3566 return true;
3567 default:
3568 return false;
3569 }
3570}
3571
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003572CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003573 return C.kind;
3574}
3575
Douglas Gregor98258af2010-01-18 22:46:11 +00003576CXSourceLocation clang_getCursorLocation(CXCursor C) {
3577 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003578 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003579 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003580 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3581 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003582 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003583 }
3584
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003586 std::pair<ObjCProtocolDecl *, SourceLocation> P
3587 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003588 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003589 }
3590
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003591 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003592 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3593 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003594 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003595 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003596
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003597 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003598 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003599 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003600 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003601
3602 case CXCursor_TemplateRef: {
3603 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3604 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3605 }
3606
Douglas Gregor69319002010-08-31 23:48:11 +00003607 case CXCursor_NamespaceRef: {
3608 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3609 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3610 }
3611
Douglas Gregora67e03f2010-09-09 21:42:20 +00003612 case CXCursor_MemberRef: {
3613 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3614 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3615 }
3616
Ted Kremenek3064ef92010-08-27 21:34:58 +00003617 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003618 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3619 if (!BaseSpec)
3620 return clang_getNullLocation();
3621
3622 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3623 return cxloc::translateSourceLocation(getCursorContext(C),
3624 TSInfo->getTypeLoc().getBeginLoc());
3625
3626 return cxloc::translateSourceLocation(getCursorContext(C),
3627 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003628 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003629
Douglas Gregor36897b02010-09-10 00:22:18 +00003630 case CXCursor_LabelRef: {
3631 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3632 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3633 }
3634
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003635 case CXCursor_OverloadedDeclRef:
3636 return cxloc::translateSourceLocation(getCursorContext(C),
3637 getCursorOverloadedDeclRef(C).second);
3638
Douglas Gregorf46034a2010-01-18 23:41:10 +00003639 default:
3640 // FIXME: Need a way to enumerate all non-reference cases.
3641 llvm_unreachable("Missed a reference kind");
3642 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003643 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003644
3645 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003646 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003647 getLocationFromExpr(getCursorExpr(C)));
3648
Douglas Gregor36897b02010-09-10 00:22:18 +00003649 if (clang_isStatement(C.kind))
3650 return cxloc::translateSourceLocation(getCursorContext(C),
3651 getCursorStmt(C)->getLocStart());
3652
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003653 if (C.kind == CXCursor_PreprocessingDirective) {
3654 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3655 return cxloc::translateSourceLocation(getCursorContext(C), L);
3656 }
Douglas Gregor48072312010-03-18 15:23:44 +00003657
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003658 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003659 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003660 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003661 return cxloc::translateSourceLocation(getCursorContext(C), L);
3662 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003663
3664 if (C.kind == CXCursor_MacroDefinition) {
3665 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3666 return cxloc::translateSourceLocation(getCursorContext(C), L);
3667 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003668
3669 if (C.kind == CXCursor_InclusionDirective) {
3670 SourceLocation L
3671 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3672 return cxloc::translateSourceLocation(getCursorContext(C), L);
3673 }
3674
Ted Kremenek9a700d22010-05-12 06:16:13 +00003675 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003676 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003677
Douglas Gregorf46034a2010-01-18 23:41:10 +00003678 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003679 if (!D)
3680 return clang_getNullLocation();
3681
Douglas Gregorf46034a2010-01-18 23:41:10 +00003682 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003683 // FIXME: Multiple variables declared in a single declaration
3684 // currently lack the information needed to correctly determine their
3685 // ranges when accounting for the type-specifier. We use context
3686 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3687 // and if so, whether it is the first decl.
3688 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3689 if (!cxcursor::isFirstInDeclGroup(C))
3690 Loc = VD->getLocation();
3691 }
3692
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003693 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003694}
Douglas Gregora7bde202010-01-19 00:34:46 +00003695
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003696} // end extern "C"
3697
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003698CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3699 assert(TU);
3700
3701 // Guard against an invalid SourceLocation, or we may assert in one
3702 // of the following calls.
3703 if (SLoc.isInvalid())
3704 return clang_getNullCursor();
3705
3706 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3707
3708 // Translate the given source location to make it point at the beginning of
3709 // the token under the cursor.
3710 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3711 CXXUnit->getASTContext().getLangOptions());
3712
3713 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3714 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003715 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003716 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3717 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003718 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003719 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003720 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003721 }
3722
3723 return Result;
3724}
3725
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003726static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003727 if (clang_isReference(C.kind)) {
3728 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003729 case CXCursor_ObjCSuperClassRef:
3730 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003731
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003732 case CXCursor_ObjCProtocolRef:
3733 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003734
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003735 case CXCursor_ObjCClassRef:
3736 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003737
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003738 case CXCursor_TypeRef:
3739 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003740
3741 case CXCursor_TemplateRef:
3742 return getCursorTemplateRef(C).second;
3743
Douglas Gregor69319002010-08-31 23:48:11 +00003744 case CXCursor_NamespaceRef:
3745 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003746
3747 case CXCursor_MemberRef:
3748 return getCursorMemberRef(C).second;
3749
Ted Kremenek3064ef92010-08-27 21:34:58 +00003750 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003751 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003752
Douglas Gregor36897b02010-09-10 00:22:18 +00003753 case CXCursor_LabelRef:
3754 return getCursorLabelRef(C).second;
3755
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003756 case CXCursor_OverloadedDeclRef:
3757 return getCursorOverloadedDeclRef(C).second;
3758
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003759 default:
3760 // FIXME: Need a way to enumerate all non-reference cases.
3761 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003762 }
3763 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003764
3765 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003766 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003767
3768 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003769 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003770
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003771 if (clang_isAttribute(C.kind))
3772 return getCursorAttr(C)->getRange();
3773
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003774 if (C.kind == CXCursor_PreprocessingDirective)
3775 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003776
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003777 if (C.kind == CXCursor_MacroExpansion) {
3778 ASTUnit *TU = getCursorASTUnit(C);
3779 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3780 return TU->mapRangeFromPreamble(Range);
3781 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003782
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003783 if (C.kind == CXCursor_MacroDefinition) {
3784 ASTUnit *TU = getCursorASTUnit(C);
3785 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3786 return TU->mapRangeFromPreamble(Range);
3787 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003788
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003789 if (C.kind == CXCursor_InclusionDirective) {
3790 ASTUnit *TU = getCursorASTUnit(C);
3791 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3792 return TU->mapRangeFromPreamble(Range);
3793 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003794
Ted Kremenek007a7c92010-11-01 23:26:51 +00003795 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3796 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003797 if (!D)
3798 return SourceRange();
3799
Ted Kremenek007a7c92010-11-01 23:26:51 +00003800 SourceRange R = D->getSourceRange();
3801 // FIXME: Multiple variables declared in a single declaration
3802 // currently lack the information needed to correctly determine their
3803 // ranges when accounting for the type-specifier. We use context
3804 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3805 // and if so, whether it is the first decl.
3806 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3807 if (!cxcursor::isFirstInDeclGroup(C))
3808 R.setBegin(VD->getLocation());
3809 }
3810 return R;
3811 }
Douglas Gregor66537982010-11-17 17:14:07 +00003812 return SourceRange();
3813}
3814
3815/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3816/// the decl-specifier-seq for declarations.
3817static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3818 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3819 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003820 if (!D)
3821 return SourceRange();
3822
Douglas Gregor66537982010-11-17 17:14:07 +00003823 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003824
Douglas Gregor2494dd02011-03-01 01:34:45 +00003825 // Adjust the start of the location for declarations preceded by
3826 // declaration specifiers.
3827 SourceLocation StartLoc;
3828 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3829 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3830 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3831 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3832 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3833 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3834 }
3835
3836 if (StartLoc.isValid() && R.getBegin().isValid() &&
3837 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3838 R.setBegin(StartLoc);
3839
3840 // FIXME: Multiple variables declared in a single declaration
3841 // currently lack the information needed to correctly determine their
3842 // ranges when accounting for the type-specifier. We use context
3843 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3844 // and if so, whether it is the first decl.
3845 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3846 if (!cxcursor::isFirstInDeclGroup(C))
3847 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003848 }
3849
3850 return R;
3851 }
3852
3853 return getRawCursorExtent(C);
3854}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003855
3856extern "C" {
3857
3858CXSourceRange clang_getCursorExtent(CXCursor C) {
3859 SourceRange R = getRawCursorExtent(C);
3860 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003861 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003862
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003863 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003864}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003865
3866CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003867 if (clang_isInvalid(C.kind))
3868 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869
Ted Kremeneka60ed472010-11-16 08:15:36 +00003870 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003871 if (clang_isDeclaration(C.kind)) {
3872 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003873 if (!D)
3874 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003875 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003876 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003877 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003878 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3879 return MakeCXCursor(Property, tu);
3880
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003881 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003882 }
3883
Douglas Gregor97b98722010-01-19 23:20:36 +00003884 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003885 Expr *E = getCursorExpr(C);
3886 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003887 if (D) {
3888 CXCursor declCursor = MakeCXCursor(D, tu);
3889 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3890 declCursor);
3891 return declCursor;
3892 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003893
3894 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003896
Douglas Gregor97b98722010-01-19 23:20:36 +00003897 return clang_getNullCursor();
3898 }
3899
Douglas Gregor36897b02010-09-10 00:22:18 +00003900 if (clang_isStatement(C.kind)) {
3901 Stmt *S = getCursorStmt(C);
3902 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003903 if (LabelDecl *label = Goto->getLabel())
3904 if (LabelStmt *labelS = label->getStmt())
3905 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003906
3907 return clang_getNullCursor();
3908 }
3909
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003910 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003911 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003912 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003913 }
3914
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003915 if (!clang_isReference(C.kind))
3916 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003917
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003918 switch (C.kind) {
3919 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003920 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003921
3922 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003923 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003924
Douglas Gregor7723fec2011-12-15 20:29:51 +00003925 case CXCursor_ObjCClassRef: {
3926 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3927 if (ObjCInterfaceDecl *Def = Class->getDefinition())
3928 return MakeCXCursor(Def, tu);
3929
3930 return MakeCXCursor(Class, tu);
3931 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003932
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003933 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003934 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003935
3936 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003937 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003938
Douglas Gregor69319002010-08-31 23:48:11 +00003939 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003940 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003941
Douglas Gregora67e03f2010-09-09 21:42:20 +00003942 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003943 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003944
Ted Kremenek3064ef92010-08-27 21:34:58 +00003945 case CXCursor_CXXBaseSpecifier: {
3946 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3947 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003948 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003949 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003950
Douglas Gregor36897b02010-09-10 00:22:18 +00003951 case CXCursor_LabelRef:
3952 // FIXME: We end up faking the "parent" declaration here because we
3953 // don't want to make CXCursor larger.
3954 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003955 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3956 .getTranslationUnitDecl(),
3957 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003958
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003959 case CXCursor_OverloadedDeclRef:
3960 return C;
3961
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003962 default:
3963 // We would prefer to enumerate all non-reference cursor kinds here.
3964 llvm_unreachable("Unhandled reference cursor kind");
3965 break;
3966 }
3967 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003968
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003969 return clang_getNullCursor();
3970}
3971
Douglas Gregorb6998662010-01-19 19:34:47 +00003972CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003973 if (clang_isInvalid(C.kind))
3974 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003975
Ted Kremeneka60ed472010-11-16 08:15:36 +00003976 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003977
Douglas Gregorb6998662010-01-19 19:34:47 +00003978 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003979 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003980 C = clang_getCursorReferenced(C);
3981 WasReference = true;
3982 }
3983
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003984 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003985 return clang_getCursorReferenced(C);
3986
Douglas Gregorb6998662010-01-19 19:34:47 +00003987 if (!clang_isDeclaration(C.kind))
3988 return clang_getNullCursor();
3989
3990 Decl *D = getCursorDecl(C);
3991 if (!D)
3992 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003993
Douglas Gregorb6998662010-01-19 19:34:47 +00003994 switch (D->getKind()) {
3995 // Declaration kinds that don't really separate the notions of
3996 // declaration and definition.
3997 case Decl::Namespace:
3998 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003999 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004000 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004001 case Decl::TemplateTypeParm:
4002 case Decl::EnumConstant:
4003 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004004 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004005 case Decl::ObjCIvar:
4006 case Decl::ObjCAtDefsField:
4007 case Decl::ImplicitParam:
4008 case Decl::ParmVar:
4009 case Decl::NonTypeTemplateParm:
4010 case Decl::TemplateTemplateParm:
4011 case Decl::ObjCCategoryImpl:
4012 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004013 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004014 case Decl::LinkageSpec:
4015 case Decl::ObjCPropertyImpl:
4016 case Decl::FileScopeAsm:
4017 case Decl::StaticAssert:
4018 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004019 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004020 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004021 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004022 return C;
4023
4024 // Declaration kinds that don't make any sense here, but are
4025 // nonetheless harmless.
4026 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004027 break;
4028
4029 // Declaration kinds for which the definition is not resolvable.
4030 case Decl::UnresolvedUsingTypename:
4031 case Decl::UnresolvedUsingValue:
4032 break;
4033
4034 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004035 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004036 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004037
4038 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004039 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004040
4041 case Decl::Enum:
4042 case Decl::Record:
4043 case Decl::CXXRecord:
4044 case Decl::ClassTemplateSpecialization:
4045 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004046 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004047 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004048 return clang_getNullCursor();
4049
4050 case Decl::Function:
4051 case Decl::CXXMethod:
4052 case Decl::CXXConstructor:
4053 case Decl::CXXDestructor:
4054 case Decl::CXXConversion: {
4055 const FunctionDecl *Def = 0;
4056 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004057 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004058 return clang_getNullCursor();
4059 }
4060
4061 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004062 // Ask the variable if it has a definition.
4063 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004064 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004065 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004066 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004067
Douglas Gregorb6998662010-01-19 19:34:47 +00004068 case Decl::FunctionTemplate: {
4069 const FunctionDecl *Def = 0;
4070 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004071 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004072 return clang_getNullCursor();
4073 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004074
Douglas Gregorb6998662010-01-19 19:34:47 +00004075 case Decl::ClassTemplate: {
4076 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004077 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004078 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004079 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004080 return clang_getNullCursor();
4081 }
4082
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004083 case Decl::Using:
4084 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004085 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004086
4087 case Decl::UsingShadow:
4088 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004089 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004090 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004091
4092 case Decl::ObjCMethod: {
4093 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4094 if (Method->isThisDeclarationADefinition())
4095 return C;
4096
4097 // Dig out the method definition in the associated
4098 // @implementation, if we have it.
4099 // FIXME: The ASTs should make finding the definition easier.
4100 if (ObjCInterfaceDecl *Class
4101 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4102 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4103 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4104 Method->isInstanceMethod()))
4105 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004106 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004107
4108 return clang_getNullCursor();
4109 }
4110
4111 case Decl::ObjCCategory:
4112 if (ObjCCategoryImplDecl *Impl
4113 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004115 return clang_getNullCursor();
4116
4117 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004118 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4119 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004120 return clang_getNullCursor();
4121
Douglas Gregor375bb142011-12-27 22:43:10 +00004122 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004123 // There are two notions of a "definition" for an Objective-C
4124 // class: the interface and its implementation. When we resolved a
4125 // reference to an Objective-C class, produce the @interface as
4126 // the definition; when we were provided with the interface,
4127 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004128 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004129 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004130 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004131 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004132 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004133 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004134 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004135 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004136
Douglas Gregorb6998662010-01-19 19:34:47 +00004137 case Decl::ObjCProperty:
4138 // FIXME: We don't really know where to find the
4139 // ObjCPropertyImplDecls that implement this property.
4140 return clang_getNullCursor();
4141
4142 case Decl::ObjCCompatibleAlias:
4143 if (ObjCInterfaceDecl *Class
4144 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004145 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4146 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004147
Douglas Gregorb6998662010-01-19 19:34:47 +00004148 return clang_getNullCursor();
4149
Douglas Gregorb6998662010-01-19 19:34:47 +00004150 case Decl::Friend:
4151 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004152 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004153 return clang_getNullCursor();
4154
4155 case Decl::FriendTemplate:
4156 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004157 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004158 return clang_getNullCursor();
4159 }
4160
4161 return clang_getNullCursor();
4162}
4163
4164unsigned clang_isCursorDefinition(CXCursor C) {
4165 if (!clang_isDeclaration(C.kind))
4166 return 0;
4167
4168 return clang_getCursorDefinition(C) == C;
4169}
4170
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004171CXCursor clang_getCanonicalCursor(CXCursor C) {
4172 if (!clang_isDeclaration(C.kind))
4173 return C;
4174
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004175 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004176 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4177 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4178 return MakeCXCursor(CatD, getCursorTU(C));
4179
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004180 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4181 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4182 return MakeCXCursor(IFD, getCursorTU(C));
4183
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004184 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004185 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004186
4187 return C;
4188}
4189
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004190unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004191 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004192 return 0;
4193
4194 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4195 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4196 return E->getNumDecls();
4197
4198 if (OverloadedTemplateStorage *S
4199 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4200 return S->size();
4201
4202 Decl *D = Storage.get<Decl*>();
4203 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004204 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004205
4206 return 0;
4207}
4208
4209CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004210 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004211 return clang_getNullCursor();
4212
4213 if (index >= clang_getNumOverloadedDecls(cursor))
4214 return clang_getNullCursor();
4215
Ted Kremeneka60ed472010-11-16 08:15:36 +00004216 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004217 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4218 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004219 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004220
4221 if (OverloadedTemplateStorage *S
4222 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004223 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004224
4225 Decl *D = Storage.get<Decl*>();
4226 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4227 // FIXME: This is, unfortunately, linear time.
4228 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4229 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004230 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004231 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004232
4233 return clang_getNullCursor();
4234}
4235
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004236void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004237 const char **startBuf,
4238 const char **endBuf,
4239 unsigned *startLine,
4240 unsigned *startColumn,
4241 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004242 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004243 assert(getCursorDecl(C) && "CXCursor has null decl");
4244 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004245 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4246 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004247
Steve Naroff4ade6d62009-09-23 17:52:52 +00004248 SourceManager &SM = FD->getASTContext().getSourceManager();
4249 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4250 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4251 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4252 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4253 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4254 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4255}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004256
Douglas Gregor430d7a12011-07-25 17:48:11 +00004257
4258CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4259 unsigned PieceIndex) {
4260 RefNamePieces Pieces;
4261
4262 switch (C.kind) {
4263 case CXCursor_MemberRefExpr:
4264 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4265 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4266 E->getQualifierLoc().getSourceRange());
4267 break;
4268
4269 case CXCursor_DeclRefExpr:
4270 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4271 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4272 E->getQualifierLoc().getSourceRange(),
4273 E->getExplicitTemplateArgsOpt());
4274 break;
4275
4276 case CXCursor_CallExpr:
4277 if (CXXOperatorCallExpr *OCE =
4278 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4279 Expr *Callee = OCE->getCallee();
4280 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4281 Callee = ICE->getSubExpr();
4282
4283 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4284 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4285 DRE->getQualifierLoc().getSourceRange());
4286 }
4287 break;
4288
4289 default:
4290 break;
4291 }
4292
4293 if (Pieces.empty()) {
4294 if (PieceIndex == 0)
4295 return clang_getCursorExtent(C);
4296 } else if (PieceIndex < Pieces.size()) {
4297 SourceRange R = Pieces[PieceIndex];
4298 if (R.isValid())
4299 return cxloc::translateSourceRange(getCursorContext(C), R);
4300 }
4301
4302 return clang_getNullRange();
4303}
4304
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004305void clang_enableStackTraces(void) {
4306 llvm::sys::PrintStackTraceOnErrorSignal();
4307}
4308
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004309void clang_executeOnThread(void (*fn)(void*), void *user_data,
4310 unsigned stack_size) {
4311 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4312}
4313
Ted Kremenekfb480492010-01-13 21:46:36 +00004314} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004315
Ted Kremenekfb480492010-01-13 21:46:36 +00004316//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004317// Token-based Operations.
4318//===----------------------------------------------------------------------===//
4319
4320/* CXToken layout:
4321 * int_data[0]: a CXTokenKind
4322 * int_data[1]: starting token location
4323 * int_data[2]: token length
4324 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004325 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004326 * otherwise unused.
4327 */
4328extern "C" {
4329
4330CXTokenKind clang_getTokenKind(CXToken CXTok) {
4331 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4332}
4333
4334CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4335 switch (clang_getTokenKind(CXTok)) {
4336 case CXToken_Identifier:
4337 case CXToken_Keyword:
4338 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004339 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4340 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004341
4342 case CXToken_Literal: {
4343 // We have stashed the starting pointer in the ptr_data field. Use it.
4344 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004345 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004346 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004347
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004348 case CXToken_Punctuation:
4349 case CXToken_Comment:
4350 break;
4351 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004352
4353 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004354 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004355 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004356 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004357 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004358
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004359 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4360 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004361 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004362 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004363 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004364 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4365 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004366 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004367
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004368 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004369}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004370
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004371CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004372 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004373 if (!CXXUnit)
4374 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004375
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004376 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4377 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4378}
4379
4380CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004381 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004382 if (!CXXUnit)
4383 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004384
4385 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4387}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004388
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004389static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4390 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004391 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4392 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004393 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004394 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004395 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004396
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004397 // Cannot tokenize across files.
4398 if (BeginLocInfo.first != EndLocInfo.first)
4399 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004400
4401 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004402 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004403 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004404 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004405 if (Invalid)
4406 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004407
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004408 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4409 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004410 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004411 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004412
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004413 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004414 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004415 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004416 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004417 do {
4418 // Lex the next token
4419 Lex.LexFromRawLexer(Tok);
4420 if (Tok.is(tok::eof))
4421 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004422
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004423 // Initialize the CXToken.
4424 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004425
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004426 // - Common fields
4427 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4428 CXTok.int_data[2] = Tok.getLength();
4429 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004430
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004431 // - Kind-specific fields
4432 if (Tok.isLiteral()) {
4433 CXTok.int_data[0] = CXToken_Literal;
4434 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004435 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004436 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004437 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004438 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004439
David Chisnall096428b2010-10-13 21:44:48 +00004440 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004441 CXTok.int_data[0] = CXToken_Keyword;
4442 }
4443 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004444 CXTok.int_data[0] = Tok.is(tok::identifier)
4445 ? CXToken_Identifier
4446 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004447 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004448 CXTok.ptr_data = II;
4449 } else if (Tok.is(tok::comment)) {
4450 CXTok.int_data[0] = CXToken_Comment;
4451 CXTok.ptr_data = 0;
4452 } else {
4453 CXTok.int_data[0] = CXToken_Punctuation;
4454 CXTok.ptr_data = 0;
4455 }
4456 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004457 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004458 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004459}
4460
4461void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4462 CXToken **Tokens, unsigned *NumTokens) {
4463 if (Tokens)
4464 *Tokens = 0;
4465 if (NumTokens)
4466 *NumTokens = 0;
4467
4468 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4469 if (!CXXUnit || !Tokens || !NumTokens)
4470 return;
4471
4472 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4473
4474 SourceRange R = cxloc::translateCXSourceRange(Range);
4475 if (R.isInvalid())
4476 return;
4477
4478 SmallVector<CXToken, 32> CXTokens;
4479 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004480
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004481 if (CXTokens.empty())
4482 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004483
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004484 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4485 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4486 *NumTokens = CXTokens.size();
4487}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004488
Ted Kremenek6db61092010-05-05 00:55:15 +00004489void clang_disposeTokens(CXTranslationUnit TU,
4490 CXToken *Tokens, unsigned NumTokens) {
4491 free(Tokens);
4492}
4493
4494} // end: extern "C"
4495
4496//===----------------------------------------------------------------------===//
4497// Token annotation APIs.
4498//===----------------------------------------------------------------------===//
4499
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004500typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004501static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4502 CXCursor parent,
4503 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004504namespace {
4505class AnnotateTokensWorker {
4506 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004507 CXToken *Tokens;
4508 CXCursor *Cursors;
4509 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004510 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004511 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004512 CursorVisitor AnnotateVis;
4513 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004514 bool HasContextSensitiveKeywords;
4515
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004516 bool MoreTokens() const { return TokIdx < NumTokens; }
4517 unsigned NextToken() const { return TokIdx; }
4518 void AdvanceToken() { ++TokIdx; }
4519 SourceLocation GetTokenLoc(unsigned tokI) {
4520 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4521 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004522 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004523 return Tokens[tokI].int_data[3] != 0;
4524 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004525 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004526 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4527 }
4528
4529 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004530 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4531 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004532
Ted Kremenek6db61092010-05-05 00:55:15 +00004533public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004534 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004535 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004536 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004537 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004538 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004539 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004540 AnnotateTokensVisitor, this,
4541 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004542 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004543 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004544 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4545 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004546
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004547 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004548 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004549 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004550
4551 /// \brief Determine whether the annotator saw any cursors that have
4552 /// context-sensitive keywords.
4553 bool hasContextSensitiveKeywords() const {
4554 return HasContextSensitiveKeywords;
4555 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004556};
4557}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004558
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004559void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004560 // Walk the AST within the region of interest, annotating tokens
4561 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004562 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004563
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004564 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4565 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004566 if (Pos != Annotated.end() &&
4567 (clang_isInvalid(Cursors[I].kind) ||
4568 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004569 Cursors[I] = Pos->second;
4570 }
4571
4572 // Finish up annotating any tokens left.
4573 if (!MoreTokens())
4574 return;
4575
4576 const CXCursor &C = clang_getNullCursor();
4577 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004578 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4579 continue;
4580
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004581 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4582 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004583 }
4584}
4585
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004586/// \brief It annotates and advances tokens with a cursor until the comparison
4587//// between the cursor location and the source range is the same as
4588/// \arg compResult.
4589///
4590/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4591/// Pass RangeOverlap to annotate tokens inside a range.
4592void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4593 RangeComparisonResult compResult,
4594 SourceRange range) {
4595 while (MoreTokens()) {
4596 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004597 if (isFunctionMacroToken(I))
4598 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004599
4600 SourceLocation TokLoc = GetTokenLoc(I);
4601 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4602 Cursors[I] = updateC;
4603 AdvanceToken();
4604 continue;
4605 }
4606 break;
4607 }
4608}
4609
4610/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004611void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4612 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004613 RangeComparisonResult compResult,
4614 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004615 assert(MoreTokens());
4616 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004617 "Should be called only for macro arg tokens");
4618
4619 // This works differently than annotateAndAdvanceTokens; because expanded
4620 // macro arguments can have arbitrary translation-unit source order, we do not
4621 // advance the token index one by one until a token fails the range test.
4622 // We only advance once past all of the macro arg tokens if all of them
4623 // pass the range test. If one of them fails we keep the token index pointing
4624 // at the start of the macro arg tokens so that the failing token will be
4625 // annotated by a subsequent annotation try.
4626
4627 bool atLeastOneCompFail = false;
4628
4629 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004630 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4631 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004632 if (TokLoc.isFileID())
4633 continue; // not macro arg token, it's parens or comma.
4634 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4635 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4636 Cursors[I] = updateC;
4637 } else
4638 atLeastOneCompFail = true;
4639 }
4640
4641 if (!atLeastOneCompFail)
4642 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4643}
4644
Ted Kremenek6db61092010-05-05 00:55:15 +00004645enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004646AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004647 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004648 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004649 if (cursorRange.isInvalid())
4650 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004651
4652 if (!HasContextSensitiveKeywords) {
4653 // Objective-C properties can have context-sensitive keywords.
4654 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4655 if (ObjCPropertyDecl *Property
4656 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4657 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4658 }
4659 // Objective-C methods can have context-sensitive keywords.
4660 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4661 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4662 if (ObjCMethodDecl *Method
4663 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4664 if (Method->getObjCDeclQualifier())
4665 HasContextSensitiveKeywords = true;
4666 else {
4667 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4668 PEnd = Method->param_end();
4669 P != PEnd; ++P) {
4670 if ((*P)->getObjCDeclQualifier()) {
4671 HasContextSensitiveKeywords = true;
4672 break;
4673 }
4674 }
4675 }
4676 }
4677 }
4678 // C++ methods can have context-sensitive keywords.
4679 else if (cursor.kind == CXCursor_CXXMethod) {
4680 if (CXXMethodDecl *Method
4681 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4682 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4683 HasContextSensitiveKeywords = true;
4684 }
4685 }
4686 // C++ classes can have context-sensitive keywords.
4687 else if (cursor.kind == CXCursor_StructDecl ||
4688 cursor.kind == CXCursor_ClassDecl ||
4689 cursor.kind == CXCursor_ClassTemplate ||
4690 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4691 if (Decl *D = getCursorDecl(cursor))
4692 if (D->hasAttr<FinalAttr>())
4693 HasContextSensitiveKeywords = true;
4694 }
4695 }
4696
Douglas Gregor4419b672010-10-21 06:10:04 +00004697 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004698 // For macro expansions, just note where the beginning of the macro
4699 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004700 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004701 Annotated[Loc.int_data] = cursor;
4702 return CXChildVisit_Recurse;
4703 }
4704
Douglas Gregor4419b672010-10-21 06:10:04 +00004705 // Items in the preprocessing record are kept separate from items in
4706 // declarations, so we keep a separate token index.
4707 unsigned SavedTokIdx = TokIdx;
4708 TokIdx = PreprocessingTokIdx;
4709
4710 // Skip tokens up until we catch up to the beginning of the preprocessing
4711 // entry.
4712 while (MoreTokens()) {
4713 const unsigned I = NextToken();
4714 SourceLocation TokLoc = GetTokenLoc(I);
4715 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4716 case RangeBefore:
4717 AdvanceToken();
4718 continue;
4719 case RangeAfter:
4720 case RangeOverlap:
4721 break;
4722 }
4723 break;
4724 }
4725
4726 // Look at all of the tokens within this range.
4727 while (MoreTokens()) {
4728 const unsigned I = NextToken();
4729 SourceLocation TokLoc = GetTokenLoc(I);
4730 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4731 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004732 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004733 case RangeAfter:
4734 break;
4735 case RangeOverlap:
4736 Cursors[I] = cursor;
4737 AdvanceToken();
4738 continue;
4739 }
4740 break;
4741 }
4742
4743 // Save the preprocessing token index; restore the non-preprocessing
4744 // token index.
4745 PreprocessingTokIdx = TokIdx;
4746 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004747 return CXChildVisit_Recurse;
4748 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004749
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004750 if (cursorRange.isInvalid())
4751 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004752
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004753 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4754
Ted Kremeneka333c662010-05-12 05:29:33 +00004755 // Adjust the annotated range based specific declarations.
4756 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4757 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004758 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004759
4760 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004761 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004762 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4763 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004764 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004765 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4766 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004767 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004768
4769 if (StartLoc.isValid() && L.isValid() &&
4770 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4771 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004772 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004773
Ted Kremenek3f404602010-08-14 01:14:06 +00004774 // If the location of the cursor occurs within a macro instantiation, record
4775 // the spelling location of the cursor in our annotation map. We can then
4776 // paper over the token labelings during a post-processing step to try and
4777 // get cursor mappings for tokens that are the *arguments* of a macro
4778 // instantiation.
4779 if (L.isMacroID()) {
4780 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4781 // Only invalidate the old annotation if it isn't part of a preprocessing
4782 // directive. Here we assume that the default construction of CXCursor
4783 // results in CXCursor.kind being an initialized value (i.e., 0). If
4784 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004785
Ted Kremenek3f404602010-08-14 01:14:06 +00004786 CXCursor &oldC = Annotated[rawEncoding];
4787 if (!clang_isPreprocessing(oldC.kind))
4788 oldC = cursor;
4789 }
4790
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004791 const enum CXCursorKind K = clang_getCursorKind(parent);
4792 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004793 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4794 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004795
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004796 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004797
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004798 // Avoid having the cursor of an expression "overwrite" the annotation of the
4799 // variable declaration that it belongs to.
4800 // This can happen for C++ constructor expressions whose range generally
4801 // include the variable declaration, e.g.:
4802 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4803 if (clang_isExpression(cursorK)) {
4804 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004805 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004806 const unsigned I = NextToken();
4807 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4808 E->getLocStart() == D->getLocation() &&
4809 E->getLocStart() == GetTokenLoc(I)) {
4810 Cursors[I] = updateC;
4811 AdvanceToken();
4812 }
4813 }
4814 }
4815
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004816 // Visit children to get their cursor information.
4817 const unsigned BeforeChildren = NextToken();
4818 VisitChildren(cursor);
4819 const unsigned AfterChildren = NextToken();
4820
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004821 // Scan the tokens that are at the end of the cursor, but are not captured
4822 // but the child cursors.
4823 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004824
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004825 // Scan the tokens that are at the beginning of the cursor, but are not
4826 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004827 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4828 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4829 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004830
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004831 Cursors[I] = cursor;
4832 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004833
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004834 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004835}
4836
Ted Kremenek6db61092010-05-05 00:55:15 +00004837static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4838 CXCursor parent,
4839 CXClientData client_data) {
4840 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4841}
4842
Ted Kremenek6628a612011-03-18 22:51:30 +00004843namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004844
4845/// \brief Uses the macro expansions in the preprocessing record to find
4846/// and mark tokens that are macro arguments. This info is used by the
4847/// AnnotateTokensWorker.
4848class MarkMacroArgTokensVisitor {
4849 SourceManager &SM;
4850 CXToken *Tokens;
4851 unsigned NumTokens;
4852 unsigned CurIdx;
4853
4854public:
4855 MarkMacroArgTokensVisitor(SourceManager &SM,
4856 CXToken *tokens, unsigned numTokens)
4857 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4858
4859 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4860 if (cursor.kind != CXCursor_MacroExpansion)
4861 return CXChildVisit_Continue;
4862
4863 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4864 if (macroRange.getBegin() == macroRange.getEnd())
4865 return CXChildVisit_Continue; // it's not a function macro.
4866
4867 for (; CurIdx < NumTokens; ++CurIdx) {
4868 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4869 macroRange.getBegin()))
4870 break;
4871 }
4872
4873 if (CurIdx == NumTokens)
4874 return CXChildVisit_Break;
4875
4876 for (; CurIdx < NumTokens; ++CurIdx) {
4877 SourceLocation tokLoc = getTokenLoc(CurIdx);
4878 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4879 break;
4880
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004881 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004882 }
4883
4884 if (CurIdx == NumTokens)
4885 return CXChildVisit_Break;
4886
4887 return CXChildVisit_Continue;
4888 }
4889
4890private:
4891 SourceLocation getTokenLoc(unsigned tokI) {
4892 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4893 }
4894
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004895 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004896 // The third field is reserved and currently not used. Use it here
4897 // to mark macro arg expanded tokens with their expanded locations.
4898 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4899 }
4900};
4901
4902} // end anonymous namespace
4903
4904static CXChildVisitResult
4905MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4906 CXClientData client_data) {
4907 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4908 parent);
4909}
4910
4911namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004912 struct clang_annotateTokens_Data {
4913 CXTranslationUnit TU;
4914 ASTUnit *CXXUnit;
4915 CXToken *Tokens;
4916 unsigned NumTokens;
4917 CXCursor *Cursors;
4918 };
4919}
4920
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004921static void annotatePreprocessorTokens(CXTranslationUnit TU,
4922 SourceRange RegionOfInterest,
4923 AnnotateTokensData &Annotated) {
4924 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4925
4926 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4927 std::pair<FileID, unsigned> BeginLocInfo
4928 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4929 std::pair<FileID, unsigned> EndLocInfo
4930 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4931
4932 if (BeginLocInfo.first != EndLocInfo.first)
4933 return;
4934
4935 StringRef Buffer;
4936 bool Invalid = false;
4937 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4938 if (Buffer.empty() || Invalid)
4939 return;
4940
4941 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4942 CXXUnit->getASTContext().getLangOptions(),
4943 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4944 Buffer.end());
4945 Lex.SetCommentRetentionState(true);
4946
4947 // Lex tokens in raw mode until we hit the end of the range, to avoid
4948 // entering #includes or expanding macros.
4949 while (true) {
4950 Token Tok;
4951 Lex.LexFromRawLexer(Tok);
4952
4953 reprocess:
4954 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4955 // We have found a preprocessing directive. Gobble it up so that we
4956 // don't see it while preprocessing these tokens later, but keep track
4957 // of all of the token locations inside this preprocessing directive so
4958 // that we can annotate them appropriately.
4959 //
4960 // FIXME: Some simple tests here could identify macro definitions and
4961 // #undefs, to provide specific cursor kinds for those.
4962 SmallVector<SourceLocation, 32> Locations;
4963 do {
4964 Locations.push_back(Tok.getLocation());
4965 Lex.LexFromRawLexer(Tok);
4966 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4967
4968 using namespace cxcursor;
4969 CXCursor Cursor
4970 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4971 Locations.back()),
4972 TU);
4973 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4974 Annotated[Locations[I].getRawEncoding()] = Cursor;
4975 }
4976
4977 if (Tok.isAtStartOfLine())
4978 goto reprocess;
4979
4980 continue;
4981 }
4982
4983 if (Tok.is(tok::eof))
4984 break;
4985 }
4986}
4987
Ted Kremenekab979612010-11-11 08:05:23 +00004988// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004989static void clang_annotateTokensImpl(void *UserData) {
4990 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4991 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4992 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4993 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4994 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4995
4996 // Determine the region of interest, which contains all of the tokens.
4997 SourceRange RegionOfInterest;
4998 RegionOfInterest.setBegin(
4999 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5000 RegionOfInterest.setEnd(
5001 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5002 Tokens[NumTokens-1])));
5003
5004 // A mapping from the source locations found when re-lexing or traversing the
5005 // region of interest to the corresponding cursors.
5006 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005007
Ted Kremenek6628a612011-03-18 22:51:30 +00005008 // Relex the tokens within the source range to look for preprocessing
5009 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005010 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005011
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005012 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5013 // Search and mark tokens that are macro argument expansions.
5014 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5015 Tokens, NumTokens);
5016 CursorVisitor MacroArgMarker(TU,
5017 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005018 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005019 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005020 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005021 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5022 }
5023
Ted Kremenek6628a612011-03-18 22:51:30 +00005024 // Annotate all of the source locations in the region of interest that map to
5025 // a specific cursor.
5026 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5027 TU, RegionOfInterest);
5028
5029 // FIXME: We use a ridiculous stack size here because the data-recursion
5030 // algorithm uses a large stack frame than the non-data recursive version,
5031 // and AnnotationTokensWorker currently transforms the data-recursion
5032 // algorithm back into a traditional recursion by explicitly calling
5033 // VisitChildren(). We will need to remove this explicit recursive call.
5034 W.AnnotateTokens();
5035
5036 // If we ran into any entities that involve context-sensitive keywords,
5037 // take another pass through the tokens to mark them as such.
5038 if (W.hasContextSensitiveKeywords()) {
5039 for (unsigned I = 0; I != NumTokens; ++I) {
5040 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5041 continue;
5042
5043 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5044 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5045 if (ObjCPropertyDecl *Property
5046 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5047 if (Property->getPropertyAttributesAsWritten() != 0 &&
5048 llvm::StringSwitch<bool>(II->getName())
5049 .Case("readonly", true)
5050 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005051 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005052 .Case("readwrite", true)
5053 .Case("retain", true)
5054 .Case("copy", true)
5055 .Case("nonatomic", true)
5056 .Case("atomic", true)
5057 .Case("getter", true)
5058 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005059 .Case("strong", true)
5060 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005061 .Default(false))
5062 Tokens[I].int_data[0] = CXToken_Keyword;
5063 }
5064 continue;
5065 }
5066
5067 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5068 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5069 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5070 if (llvm::StringSwitch<bool>(II->getName())
5071 .Case("in", true)
5072 .Case("out", true)
5073 .Case("inout", true)
5074 .Case("oneway", true)
5075 .Case("bycopy", true)
5076 .Case("byref", true)
5077 .Default(false))
5078 Tokens[I].int_data[0] = CXToken_Keyword;
5079 continue;
5080 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005081
5082 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5083 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5084 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005085 continue;
5086 }
5087 }
5088 }
Ted Kremenekab979612010-11-11 08:05:23 +00005089}
5090
Ted Kremenek6db61092010-05-05 00:55:15 +00005091extern "C" {
5092
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005093void clang_annotateTokens(CXTranslationUnit TU,
5094 CXToken *Tokens, unsigned NumTokens,
5095 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005096
5097 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005098 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005099
Douglas Gregor4419b672010-10-21 06:10:04 +00005100 // Any token we don't specifically annotate will have a NULL cursor.
5101 CXCursor C = clang_getNullCursor();
5102 for (unsigned I = 0; I != NumTokens; ++I)
5103 Cursors[I] = C;
5104
Ted Kremeneka60ed472010-11-16 08:15:36 +00005105 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005106 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005107 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005108
Douglas Gregorbdf60622010-03-05 21:16:25 +00005109 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005110
5111 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005112 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005113 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005114 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005115 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5116 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005117}
Ted Kremenek6628a612011-03-18 22:51:30 +00005118
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005119} // end: extern "C"
5120
5121//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005122// Operations for querying linkage of a cursor.
5123//===----------------------------------------------------------------------===//
5124
5125extern "C" {
5126CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005127 if (!clang_isDeclaration(cursor.kind))
5128 return CXLinkage_Invalid;
5129
Ted Kremenek16b42592010-03-03 06:36:57 +00005130 Decl *D = cxcursor::getCursorDecl(cursor);
5131 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5132 switch (ND->getLinkage()) {
5133 case NoLinkage: return CXLinkage_NoLinkage;
5134 case InternalLinkage: return CXLinkage_Internal;
5135 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5136 case ExternalLinkage: return CXLinkage_External;
5137 };
5138
5139 return CXLinkage_Invalid;
5140}
5141} // end: extern "C"
5142
5143//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005144// Operations for querying language of a cursor.
5145//===----------------------------------------------------------------------===//
5146
5147static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005148 if (!D)
5149 return CXLanguage_C;
5150
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005151 switch (D->getKind()) {
5152 default:
5153 break;
5154 case Decl::ImplicitParam:
5155 case Decl::ObjCAtDefsField:
5156 case Decl::ObjCCategory:
5157 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005158 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005159 case Decl::ObjCImplementation:
5160 case Decl::ObjCInterface:
5161 case Decl::ObjCIvar:
5162 case Decl::ObjCMethod:
5163 case Decl::ObjCProperty:
5164 case Decl::ObjCPropertyImpl:
5165 case Decl::ObjCProtocol:
5166 return CXLanguage_ObjC;
5167 case Decl::CXXConstructor:
5168 case Decl::CXXConversion:
5169 case Decl::CXXDestructor:
5170 case Decl::CXXMethod:
5171 case Decl::CXXRecord:
5172 case Decl::ClassTemplate:
5173 case Decl::ClassTemplatePartialSpecialization:
5174 case Decl::ClassTemplateSpecialization:
5175 case Decl::Friend:
5176 case Decl::FriendTemplate:
5177 case Decl::FunctionTemplate:
5178 case Decl::LinkageSpec:
5179 case Decl::Namespace:
5180 case Decl::NamespaceAlias:
5181 case Decl::NonTypeTemplateParm:
5182 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005183 case Decl::TemplateTemplateParm:
5184 case Decl::TemplateTypeParm:
5185 case Decl::UnresolvedUsingTypename:
5186 case Decl::UnresolvedUsingValue:
5187 case Decl::Using:
5188 case Decl::UsingDirective:
5189 case Decl::UsingShadow:
5190 return CXLanguage_CPlusPlus;
5191 }
5192
5193 return CXLanguage_C;
5194}
5195
5196extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005197
5198enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5199 if (clang_isDeclaration(cursor.kind))
5200 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005201 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005202 return CXAvailability_Available;
5203
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005204 switch (D->getAvailability()) {
5205 case AR_Available:
5206 case AR_NotYetIntroduced:
5207 return CXAvailability_Available;
5208
5209 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005210 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005211
5212 case AR_Unavailable:
5213 return CXAvailability_NotAvailable;
5214 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005215 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005216
Douglas Gregor58ddb602010-08-23 23:00:57 +00005217 return CXAvailability_Available;
5218}
5219
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005220CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5221 if (clang_isDeclaration(cursor.kind))
5222 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5223
5224 return CXLanguage_Invalid;
5225}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005226
5227 /// \brief If the given cursor is the "templated" declaration
5228 /// descibing a class or function template, return the class or
5229 /// function template.
5230static Decl *maybeGetTemplateCursor(Decl *D) {
5231 if (!D)
5232 return 0;
5233
5234 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5235 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5236 return FunTmpl;
5237
5238 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5239 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5240 return ClassTmpl;
5241
5242 return D;
5243}
5244
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005245CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5246 if (clang_isDeclaration(cursor.kind)) {
5247 if (Decl *D = getCursorDecl(cursor)) {
5248 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005249 if (!DC)
5250 return clang_getNullCursor();
5251
5252 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5253 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005254 }
5255 }
5256
5257 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5258 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005259 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005260 }
5261
5262 return clang_getNullCursor();
5263}
5264
5265CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5266 if (clang_isDeclaration(cursor.kind)) {
5267 if (Decl *D = getCursorDecl(cursor)) {
5268 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005269 if (!DC)
5270 return clang_getNullCursor();
5271
5272 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5273 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005274 }
5275 }
5276
5277 // FIXME: Note that we can't easily compute the lexical context of a
5278 // statement or expression, so we return nothing.
5279 return clang_getNullCursor();
5280}
5281
Douglas Gregor9f592342010-10-01 20:25:15 +00005282void clang_getOverriddenCursors(CXCursor cursor,
5283 CXCursor **overridden,
5284 unsigned *num_overridden) {
5285 if (overridden)
5286 *overridden = 0;
5287 if (num_overridden)
5288 *num_overridden = 0;
5289 if (!overridden || !num_overridden)
5290 return;
5291
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005292 SmallVector<CXCursor, 8> Overridden;
5293 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005294
Ted Kremenek24077122011-11-14 23:51:37 +00005295 // Don't allocate memory if we have no overriden cursors.
5296 if (Overridden.size() == 0)
5297 return;
5298
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005299 *num_overridden = Overridden.size();
5300 *overridden = new CXCursor [Overridden.size()];
5301 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005302}
5303
5304void clang_disposeOverriddenCursors(CXCursor *overridden) {
5305 delete [] overridden;
5306}
5307
Douglas Gregorecdcb882010-10-20 22:00:55 +00005308CXFile clang_getIncludedFile(CXCursor cursor) {
5309 if (cursor.kind != CXCursor_InclusionDirective)
5310 return 0;
5311
5312 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5313 return (void *)ID->getFile();
5314}
5315
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005316} // end: extern "C"
5317
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005318
5319//===----------------------------------------------------------------------===//
5320// C++ AST instrospection.
5321//===----------------------------------------------------------------------===//
5322
5323extern "C" {
5324unsigned clang_CXXMethod_isStatic(CXCursor C) {
5325 if (!clang_isDeclaration(C.kind))
5326 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005327
5328 CXXMethodDecl *Method = 0;
5329 Decl *D = cxcursor::getCursorDecl(C);
5330 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5331 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5332 else
5333 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5334 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005335}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005336
Douglas Gregor211924b2011-05-12 15:17:24 +00005337unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5338 if (!clang_isDeclaration(C.kind))
5339 return 0;
5340
5341 CXXMethodDecl *Method = 0;
5342 Decl *D = cxcursor::getCursorDecl(C);
5343 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5344 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5345 else
5346 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5347 return (Method && Method->isVirtual()) ? 1 : 0;
5348}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005349} // end: extern "C"
5350
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005351//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005352// Attribute introspection.
5353//===----------------------------------------------------------------------===//
5354
5355extern "C" {
5356CXType clang_getIBOutletCollectionType(CXCursor C) {
5357 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005358 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005359
5360 IBOutletCollectionAttr *A =
5361 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5362
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005363 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005364}
5365} // end: extern "C"
5366
5367//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005368// Inspecting memory usage.
5369//===----------------------------------------------------------------------===//
5370
Ted Kremenekf7870022011-04-20 16:41:07 +00005371typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005372
Ted Kremenekf7870022011-04-20 16:41:07 +00005373static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5374 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005375 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005376 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005377 entries.push_back(entry);
5378}
5379
5380extern "C" {
5381
Ted Kremenekf7870022011-04-20 16:41:07 +00005382const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005383 const char *str = "";
5384 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005385 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005386 str = "ASTContext: expressions, declarations, and types";
5387 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005388 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005389 str = "ASTContext: identifiers";
5390 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005391 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005392 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005393 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005394 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005395 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005396 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005397 case CXTUResourceUsage_SourceManagerContentCache:
5398 str = "SourceManager: content cache allocator";
5399 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005400 case CXTUResourceUsage_AST_SideTables:
5401 str = "ASTContext: side tables";
5402 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005403 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5404 str = "SourceManager: malloc'ed memory buffers";
5405 break;
5406 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5407 str = "SourceManager: mmap'ed memory buffers";
5408 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005409 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5410 str = "ExternalASTSource: malloc'ed memory buffers";
5411 break;
5412 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5413 str = "ExternalASTSource: mmap'ed memory buffers";
5414 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005415 case CXTUResourceUsage_Preprocessor:
5416 str = "Preprocessor: malloc'ed memory";
5417 break;
5418 case CXTUResourceUsage_PreprocessingRecord:
5419 str = "Preprocessor: PreprocessingRecord";
5420 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005421 case CXTUResourceUsage_SourceManager_DataStructures:
5422 str = "SourceManager: data structures and tables";
5423 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005424 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5425 str = "Preprocessor: header search tables";
5426 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005427 }
5428 return str;
5429}
5430
Ted Kremenekf7870022011-04-20 16:41:07 +00005431CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005432 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005433 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005434 return usage;
5435 }
5436
5437 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5438 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5439 ASTContext &astContext = astUnit->getASTContext();
5440
5441 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005442 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005443 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005444
5445 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005446 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005447 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5448
5449 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005450 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005451 (unsigned long) astContext.Selectors.getTotalMemory());
5452
Ted Kremenekba29bd22011-04-28 04:53:38 +00005453 // How much memory is used by ASTContext's side tables?
5454 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5455 (unsigned long) astContext.getSideTableAllocatedMemory());
5456
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005457 // How much memory is used for caching global code completion results?
5458 unsigned long completionBytes = 0;
5459 if (GlobalCodeCompletionAllocator *completionAllocator =
5460 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005461 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005462 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005463 createCXTUResourceUsageEntry(*entries,
5464 CXTUResourceUsage_GlobalCompletionResults,
5465 completionBytes);
5466
5467 // How much memory is being used by SourceManager's content cache?
5468 createCXTUResourceUsageEntry(*entries,
5469 CXTUResourceUsage_SourceManagerContentCache,
5470 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005471
5472 // How much memory is being used by the MemoryBuffer's in SourceManager?
5473 const SourceManager::MemoryBufferSizes &srcBufs =
5474 astUnit->getSourceManager().getMemoryBufferSizes();
5475
5476 createCXTUResourceUsageEntry(*entries,
5477 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5478 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005479 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005480 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5481 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005482 createCXTUResourceUsageEntry(*entries,
5483 CXTUResourceUsage_SourceManager_DataStructures,
5484 (unsigned long) astContext.getSourceManager()
5485 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005486
5487 // How much memory is being used by the ExternalASTSource?
5488 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5489 const ExternalASTSource::MemoryBufferSizes &sizes =
5490 esrc->getMemoryBufferSizes();
5491
5492 createCXTUResourceUsageEntry(*entries,
5493 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5494 (unsigned long) sizes.malloc_bytes);
5495 createCXTUResourceUsageEntry(*entries,
5496 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5497 (unsigned long) sizes.mmap_bytes);
5498 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005499
5500 // How much memory is being used by the Preprocessor?
5501 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005502 createCXTUResourceUsageEntry(*entries,
5503 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005504 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005505
5506 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5507 createCXTUResourceUsageEntry(*entries,
5508 CXTUResourceUsage_PreprocessingRecord,
5509 pRec->getTotalMemory());
5510 }
5511
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005512 createCXTUResourceUsageEntry(*entries,
5513 CXTUResourceUsage_Preprocessor_HeaderSearch,
5514 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005515
Ted Kremenekf7870022011-04-20 16:41:07 +00005516 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005517 (unsigned) entries->size(),
5518 entries->size() ? &(*entries)[0] : 0 };
5519 entries.take();
5520 return usage;
5521}
5522
Ted Kremenekf7870022011-04-20 16:41:07 +00005523void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005524 if (usage.data)
5525 delete (MemUsageEntries*) usage.data;
5526}
5527
5528} // end extern "C"
5529
Douglas Gregor6df78732011-05-05 20:27:22 +00005530void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5531 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5532 for (unsigned I = 0; I != Usage.numEntries; ++I)
5533 fprintf(stderr, " %s: %lu\n",
5534 clang_getTUResourceUsageName(Usage.entries[I].kind),
5535 Usage.entries[I].amount);
5536
5537 clang_disposeCXTUResourceUsage(Usage);
5538}
5539
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005540//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005541// Misc. utility functions.
5542//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005543
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005544/// Default to using an 8 MB stack size on "safety" threads.
5545static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005546
5547namespace clang {
5548
5549bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005550 void (*Fn)(void*), void *UserData,
5551 unsigned Size) {
5552 if (!Size)
5553 Size = GetSafetyThreadStackSize();
5554 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005555 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5556 return CRC.RunSafely(Fn, UserData);
5557}
5558
5559unsigned GetSafetyThreadStackSize() {
5560 return SafetyStackThreadSize;
5561}
5562
5563void SetSafetyThreadStackSize(unsigned Value) {
5564 SafetyStackThreadSize = Value;
5565}
5566
5567}
5568
Ted Kremenek04bb7162010-01-22 22:44:15 +00005569extern "C" {
5570
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005571CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005572 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005573}
5574
5575} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005576