blob: f2e6b01329acc10f1ac2b0f2db9ba53517713837 [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) {
954 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
955 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
956 E = PID->protocol_end(); I != E; ++I, ++PL)
957 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
958 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000959
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000960 return VisitObjCContainerDecl(PID);
961}
962
Ted Kremenek23173d72010-05-18 21:09:07 +0000963bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000964 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000965 return true;
966
Ted Kremenek23173d72010-05-18 21:09:07 +0000967 // FIXME: This implements a workaround with @property declarations also being
968 // installed in the DeclContext for the @interface. Eventually this code
969 // should be removed.
970 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
971 if (!CDecl || !CDecl->IsClassExtension())
972 return false;
973
974 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
975 if (!ID)
976 return false;
977
978 IdentifierInfo *PropertyId = PD->getIdentifier();
979 ObjCPropertyDecl *prevDecl =
980 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
981
982 if (!prevDecl)
983 return false;
984
985 // Visit synthesized methods since they will be skipped when visiting
986 // the @interface.
987 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000988 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000989 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000990 return true;
991
992 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000993 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000994 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000995 return true;
996
997 return false;
998}
999
Douglas Gregorb1373d02010-01-20 20:59:29 +00001000bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Douglas Gregor375bb142011-12-27 22:43:10 +00001001 if (!D->isThisDeclarationADefinition()) {
1002 // Forward declaration is treated like a reference.
1003 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1004 }
1005
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001006 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001007 if (D->getSuperClass() &&
1008 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001009 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001010 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001013 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1014 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1015 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001016 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001017 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018
Douglas Gregora59e3902010-01-21 23:27:09 +00001019 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1023 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001024}
1025
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001027 // 'ID' could be null when dealing with invalid code.
1028 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1029 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1030 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001032 return VisitObjCImplDecl(D);
1033}
1034
1035bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1036#if 0
1037 // Issue callbacks for super class.
1038 // FIXME: No source location information!
1039 if (D->getSuperClass() &&
1040 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042 TU)))
1043 return true;
1044#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046 return VisitObjCImplDecl(D);
1047}
1048
1049bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1050 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1051 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1052 E = D->protocol_end();
1053 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001054 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001055 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001056
1057 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001058}
1059
Douglas Gregora4ffd852010-11-17 01:03:52 +00001060bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1061 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1062 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1063
1064 return false;
1065}
1066
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001067bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1068 return VisitDeclContext(D);
1069}
1070
Douglas Gregor69319002010-08-31 23:48:11 +00001071bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001072 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001073 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1074 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001075 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001076
1077 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1078 D->getTargetNameLoc(), TU));
1079}
1080
Douglas Gregor7e242562010-09-01 19:52:22 +00001081bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001082 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001083 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1084 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001085 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001086 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001087
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001088 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1089 return true;
1090
Douglas Gregor7e242562010-09-01 19:52:22 +00001091 return VisitDeclarationNameInfo(D->getNameInfo());
1092}
1093
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001094bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001095 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001096 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1097 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001098 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001099
1100 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1101 D->getIdentLocation(), TU));
1102}
1103
Douglas Gregor7e242562010-09-01 19:52:22 +00001104bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001106 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1107 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001108 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001109 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110
Douglas Gregor7e242562010-09-01 19:52:22 +00001111 return VisitDeclarationNameInfo(D->getNameInfo());
1112}
1113
1114bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1115 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001116 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001117 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1118 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119 return true;
1120
Douglas Gregor7e242562010-09-01 19:52:22 +00001121 return false;
1122}
1123
Douglas Gregor01829d32010-08-31 14:41:23 +00001124bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1125 switch (Name.getName().getNameKind()) {
1126 case clang::DeclarationName::Identifier:
1127 case clang::DeclarationName::CXXLiteralOperatorName:
1128 case clang::DeclarationName::CXXOperatorName:
1129 case clang::DeclarationName::CXXUsingDirective:
1130 return false;
1131
1132 case clang::DeclarationName::CXXConstructorName:
1133 case clang::DeclarationName::CXXDestructorName:
1134 case clang::DeclarationName::CXXConversionFunctionName:
1135 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1136 return Visit(TSInfo->getTypeLoc());
1137 return false;
1138
1139 case clang::DeclarationName::ObjCZeroArgSelector:
1140 case clang::DeclarationName::ObjCOneArgSelector:
1141 case clang::DeclarationName::ObjCMultiArgSelector:
1142 // FIXME: Per-identifier location info?
1143 return false;
1144 }
1145
1146 return false;
1147}
1148
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001149bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1150 SourceRange Range) {
1151 // FIXME: This whole routine is a hack to work around the lack of proper
1152 // source information in nested-name-specifiers (PR5791). Since we do have
1153 // a beginning source location, we can visit the first component of the
1154 // nested-name-specifier, if it's a single-token component.
1155 if (!NNS)
1156 return false;
1157
1158 // Get the first component in the nested-name-specifier.
1159 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1160 NNS = Prefix;
1161
1162 switch (NNS->getKind()) {
1163 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001164 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1165 TU));
1166
Douglas Gregor14aba762011-02-24 02:36:08 +00001167 case NestedNameSpecifier::NamespaceAlias:
1168 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1169 Range.getBegin(), TU));
1170
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001171 case NestedNameSpecifier::TypeSpec: {
1172 // If the type has a form where we know that the beginning of the source
1173 // range matches up with a reference cursor. Visit the appropriate reference
1174 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001175 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001176 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1177 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1178 if (const TagType *Tag = dyn_cast<TagType>(T))
1179 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1180 if (const TemplateSpecializationType *TST
1181 = dyn_cast<TemplateSpecializationType>(T))
1182 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1183 break;
1184 }
1185
1186 case NestedNameSpecifier::TypeSpecWithTemplate:
1187 case NestedNameSpecifier::Global:
1188 case NestedNameSpecifier::Identifier:
1189 break;
1190 }
1191
1192 return false;
1193}
1194
Douglas Gregordc355712011-02-25 00:36:19 +00001195bool
1196CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001197 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001198 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1199 Qualifiers.push_back(Qualifier);
1200
1201 while (!Qualifiers.empty()) {
1202 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1203 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1204 switch (NNS->getKind()) {
1205 case NestedNameSpecifier::Namespace:
1206 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
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::NamespaceAlias:
1214 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001215 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001216 TU)))
1217 return true;
1218
1219 break;
1220
1221 case NestedNameSpecifier::TypeSpec:
1222 case NestedNameSpecifier::TypeSpecWithTemplate:
1223 if (Visit(Q.getTypeLoc()))
1224 return true;
1225
1226 break;
1227
1228 case NestedNameSpecifier::Global:
1229 case NestedNameSpecifier::Identifier:
1230 break;
1231 }
1232 }
1233
1234 return false;
1235}
1236
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001237bool CursorVisitor::VisitTemplateParameters(
1238 const TemplateParameterList *Params) {
1239 if (!Params)
1240 return false;
1241
1242 for (TemplateParameterList::const_iterator P = Params->begin(),
1243 PEnd = Params->end();
1244 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001245 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001246 return true;
1247 }
1248
1249 return false;
1250}
1251
Douglas Gregor0b36e612010-08-31 20:37:03 +00001252bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1253 switch (Name.getKind()) {
1254 case TemplateName::Template:
1255 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1256
1257 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001258 // Visit the overloaded template set.
1259 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1260 return true;
1261
Douglas Gregor0b36e612010-08-31 20:37:03 +00001262 return false;
1263
1264 case TemplateName::DependentTemplate:
1265 // FIXME: Visit nested-name-specifier.
1266 return false;
1267
1268 case TemplateName::QualifiedTemplate:
1269 // FIXME: Visit nested-name-specifier.
1270 return Visit(MakeCursorTemplateRef(
1271 Name.getAsQualifiedTemplateName()->getDecl(),
1272 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001273
1274 case TemplateName::SubstTemplateTemplateParm:
1275 return Visit(MakeCursorTemplateRef(
1276 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1277 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001278
1279 case TemplateName::SubstTemplateTemplateParmPack:
1280 return Visit(MakeCursorTemplateRef(
1281 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1282 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001283 }
1284
1285 return false;
1286}
1287
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001288bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1289 switch (TAL.getArgument().getKind()) {
1290 case TemplateArgument::Null:
1291 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001292 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001293 return false;
1294
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001295 case TemplateArgument::Type:
1296 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1297 return Visit(TSInfo->getTypeLoc());
1298 return false;
1299
1300 case TemplateArgument::Declaration:
1301 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001302 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001303 return false;
1304
1305 case TemplateArgument::Expression:
1306 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001307 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001308 return false;
1309
1310 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001311 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001312 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1313 return true;
1314
Douglas Gregora7fc9012011-01-05 18:58:31 +00001315 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001316 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001317 }
1318
1319 return false;
1320}
1321
Ted Kremeneka0536d82010-05-07 01:04:29 +00001322bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1323 return VisitDeclContext(D);
1324}
1325
Douglas Gregor01829d32010-08-31 14:41:23 +00001326bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1327 return Visit(TL.getUnqualifiedLoc());
1328}
1329
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001330bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001331 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001332
1333 // Some builtin types (such as Objective-C's "id", "sel", and
1334 // "Class") have associated declarations. Create cursors for those.
1335 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001336 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001337
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001338 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001339 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001340 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001341#define BUILTIN_TYPE(Id, SingletonId)
1342#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1343#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1344#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1345#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1346#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001347 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001348
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001349 case BuiltinType::ObjCId:
1350 VisitType = Context.getObjCIdType();
1351 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001352
1353 case BuiltinType::ObjCClass:
1354 VisitType = Context.getObjCClassType();
1355 break;
1356
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001357 case BuiltinType::ObjCSel:
1358 VisitType = Context.getObjCSelType();
1359 break;
1360 }
1361
1362 if (!VisitType.isNull()) {
1363 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001364 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001365 TU));
1366 }
1367
1368 return false;
1369}
1370
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001371bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001372 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001373}
1374
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1376 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1377}
1378
1379bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001380 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001381 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001382
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001383 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1384}
1385
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001386bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001387 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001388}
1389
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1391 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1392 return true;
1393
John McCallc12c5bb2010-05-15 11:32:37 +00001394 return false;
1395}
1396
1397bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1398 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1399 return true;
1400
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001401 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1402 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1403 TU)))
1404 return true;
1405 }
1406
1407 return false;
1408}
1409
1410bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001411 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001412}
1413
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001414bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1415 return Visit(TL.getInnerLoc());
1416}
1417
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001418bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1419 return Visit(TL.getPointeeLoc());
1420}
1421
1422bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1423 return Visit(TL.getPointeeLoc());
1424}
1425
1426bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1427 return Visit(TL.getPointeeLoc());
1428}
1429
1430bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001431 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001432}
1433
1434bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001435 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001436}
1437
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001438bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1439 return Visit(TL.getModifiedLoc());
1440}
1441
Douglas Gregor01829d32010-08-31 14:41:23 +00001442bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1443 bool SkipResultType) {
1444 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001445 return true;
1446
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001447 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001448 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001449 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001450 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001451
1452 return false;
1453}
1454
1455bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1456 if (Visit(TL.getElementLoc()))
1457 return true;
1458
1459 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001460 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001461
1462 return false;
1463}
1464
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001465bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1466 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001467 // Visit the template name.
1468 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1469 TL.getTemplateNameLoc()))
1470 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001471
1472 // Visit the template arguments.
1473 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1474 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1475 return true;
1476
1477 return false;
1478}
1479
Douglas Gregor2332c112010-01-21 20:48:56 +00001480bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1481 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1482}
1483
1484bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1485 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1486 return Visit(TSInfo->getTypeLoc());
1487
1488 return false;
1489}
1490
Sean Huntca63c202011-05-24 22:41:36 +00001491bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1492 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1493 return Visit(TSInfo->getTypeLoc());
1494
1495 return false;
1496}
1497
Douglas Gregor2494dd02011-03-01 01:34:45 +00001498bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1499 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1500 return true;
1501
1502 return false;
1503}
1504
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001505bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1506 DependentTemplateSpecializationTypeLoc TL) {
1507 // Visit the nested-name-specifier, if there is one.
1508 if (TL.getQualifierLoc() &&
1509 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1510 return true;
1511
1512 // Visit the template arguments.
1513 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1514 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1515 return true;
1516
1517 return false;
1518}
1519
Douglas Gregor9e876872011-03-01 18:12:44 +00001520bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1521 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1522 return true;
1523
1524 return Visit(TL.getNamedTypeLoc());
1525}
1526
Douglas Gregor7536dd52010-12-20 02:24:11 +00001527bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1528 return Visit(TL.getPatternLoc());
1529}
1530
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001531bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1532 if (Expr *E = TL.getUnderlyingExpr())
1533 return Visit(MakeCXCursor(E, StmtParent, TU));
1534
1535 return false;
1536}
1537
1538bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1539 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1540}
1541
Eli Friedmanb001de72011-10-06 23:00:33 +00001542bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1543 return Visit(TL.getValueLoc());
1544}
1545
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001546#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1547bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1548 return Visit##PARENT##Loc(TL); \
1549}
1550
1551DEFAULT_TYPELOC_IMPL(Complex, Type)
1552DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1553DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1554DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1555DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1556DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1557DEFAULT_TYPELOC_IMPL(Vector, Type)
1558DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1559DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1560DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1561DEFAULT_TYPELOC_IMPL(Record, TagType)
1562DEFAULT_TYPELOC_IMPL(Enum, TagType)
1563DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1564DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1565DEFAULT_TYPELOC_IMPL(Auto, Type)
1566
Ted Kremenek3064ef92010-08-27 21:34:58 +00001567bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001568 // Visit the nested-name-specifier, if present.
1569 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1570 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1571 return true;
1572
John McCall5e1cdac2011-10-07 06:10:15 +00001573 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001574 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1575 E = D->bases_end(); I != E; ++I) {
1576 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1577 return true;
1578 }
1579 }
1580
1581 return VisitTagDecl(D);
1582}
1583
Ted Kremenek09dfa372010-02-18 05:46:33 +00001584bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001585 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1586 i != e; ++i)
1587 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001588 return true;
1589
1590 return false;
1591}
1592
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001593//===----------------------------------------------------------------------===//
1594// Data-recursive visitor methods.
1595//===----------------------------------------------------------------------===//
1596
Ted Kremenek28a71942010-11-13 00:36:47 +00001597namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001598#define DEF_JOB(NAME, DATA, KIND)\
1599class NAME : public VisitorJob {\
1600public:\
1601 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1602 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001603 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001604};
1605
1606DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1607DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001608DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001609DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001610DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001611 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001612DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001613#undef DEF_JOB
1614
1615class DeclVisit : public VisitorJob {
1616public:
1617 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1618 VisitorJob(parent, VisitorJob::DeclVisitKind,
1619 d, isFirst ? (void*) 1 : (void*) 0) {}
1620 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001621 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001622 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001623 Decl *get() const { return static_cast<Decl*>(data[0]); }
1624 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001625};
Ted Kremenek035dc412010-11-13 00:36:50 +00001626class TypeLocVisit : public VisitorJob {
1627public:
1628 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1629 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1630 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1631
1632 static bool classof(const VisitorJob *VJ) {
1633 return VJ->getKind() == TypeLocVisitKind;
1634 }
1635
Ted Kremenek82f3c502010-11-15 22:23:26 +00001636 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001637 QualType T = QualType::getFromOpaquePtr(data[0]);
1638 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001639 }
1640};
1641
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001642class LabelRefVisit : public VisitorJob {
1643public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001644 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1645 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001646 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001647
1648 static bool classof(const VisitorJob *VJ) {
1649 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1650 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001651 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001652 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001653 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001654};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001655
1656class NestedNameSpecifierLocVisit : public VisitorJob {
1657public:
1658 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1659 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1660 Qualifier.getNestedNameSpecifier(),
1661 Qualifier.getOpaqueData()) { }
1662
1663 static bool classof(const VisitorJob *VJ) {
1664 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1665 }
1666
1667 NestedNameSpecifierLoc get() const {
1668 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1669 data[1]);
1670 }
1671};
1672
Ted Kremenekf64d8032010-11-18 00:02:32 +00001673class DeclarationNameInfoVisit : public VisitorJob {
1674public:
1675 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1676 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1677 static bool classof(const VisitorJob *VJ) {
1678 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1679 }
1680 DeclarationNameInfo get() const {
1681 Stmt *S = static_cast<Stmt*>(data[0]);
1682 switch (S->getStmtClass()) {
1683 default:
1684 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001685 case clang::Stmt::MSDependentExistsStmtClass:
1686 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001687 case Stmt::CXXDependentScopeMemberExprClass:
1688 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1689 case Stmt::DependentScopeDeclRefExprClass:
1690 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1691 }
1692 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001693};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001694class MemberRefVisit : public VisitorJob {
1695public:
1696 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1697 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001698 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001699 static bool classof(const VisitorJob *VJ) {
1700 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1701 }
1702 FieldDecl *get() const {
1703 return static_cast<FieldDecl*>(data[0]);
1704 }
1705 SourceLocation getLoc() const {
1706 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1707 }
1708};
Ted Kremenek28a71942010-11-13 00:36:47 +00001709class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1710 VisitorWorkList &WL;
1711 CXCursor Parent;
1712public:
1713 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1714 : WL(wl), Parent(parent) {}
1715
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001716 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001717 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001718 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001719 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001720 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001721 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001722 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001723 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001724 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001725 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001726 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001727 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001728 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001729 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001730 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001731 void VisitCXXCatchStmt(CXXCatchStmt *S);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001732 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001733 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001734 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001735 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001736 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1737 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001738 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001739 void VisitIfStmt(IfStmt *If);
1740 void VisitInitListExpr(InitListExpr *IE);
1741 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001742 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001743 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001744 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1745 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001746 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001747 void VisitStmt(Stmt *S);
1748 void VisitSwitchStmt(SwitchStmt *S);
1749 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001750 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001751 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001752 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001753 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001754 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001755 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001756 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
John McCall4b9c2d22011-11-06 09:01:30 +00001757 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1758 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001759
Ted Kremenek28a71942010-11-13 00:36:47 +00001760private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001761 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001762 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001763 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001764 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001765 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001766 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001767 void AddTypeLoc(TypeSourceInfo *TI);
1768 void EnqueueChildren(Stmt *S);
1769};
1770} // end anonyous namespace
1771
Ted Kremenekf64d8032010-11-18 00:02:32 +00001772void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1773 // 'S' should always be non-null, since it comes from the
1774 // statement we are visiting.
1775 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1776}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001777
1778void
1779EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1780 if (Qualifier)
1781 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1782}
1783
Ted Kremenek28a71942010-11-13 00:36:47 +00001784void EnqueueVisitor::AddStmt(Stmt *S) {
1785 if (S)
1786 WL.push_back(StmtVisit(S, Parent));
1787}
Ted Kremenek035dc412010-11-13 00:36:50 +00001788void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001789 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001790 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001791}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001792void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001793 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001794 if (A)
1795 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001796 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001797}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001798void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1799 if (D)
1800 WL.push_back(MemberRefVisit(D, L, Parent));
1801}
Ted Kremenek28a71942010-11-13 00:36:47 +00001802void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1803 if (TI)
1804 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1805 }
1806void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001807 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001808 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001809 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001810 }
1811 if (size == WL.size())
1812 return;
1813 // Now reverse the entries we just added. This will match the DFS
1814 // ordering performed by the worklist.
1815 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1816 std::reverse(I, E);
1817}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001818void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1819 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1820}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001821void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1822 AddDecl(B->getBlockDecl());
1823}
Ted Kremenek28a71942010-11-13 00:36:47 +00001824void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1825 EnqueueChildren(E);
1826 AddTypeLoc(E->getTypeSourceInfo());
1827}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001828void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1829 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1830 E = S->body_rend(); I != E; ++I) {
1831 AddStmt(*I);
1832 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001833}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001834void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00001835VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1836 AddStmt(S->getSubStmt());
1837 AddDeclarationNameInfo(S);
1838 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1839 AddNestedNameSpecifierLoc(QualifierLoc);
1840}
1841
1842void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00001843VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1844 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1845 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001846 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1847 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001848 if (!E->isImplicitAccess())
1849 AddStmt(E->getBase());
1850}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001851void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1852 // Enqueue the initializer or constructor arguments.
1853 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1854 AddStmt(E->getConstructorArg(I-1));
1855 // Enqueue the array size, if any.
1856 AddStmt(E->getArraySize());
1857 // Enqueue the allocated type.
1858 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1859 // Enqueue the placement arguments.
1860 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1861 AddStmt(E->getPlacementArg(I-1));
1862}
Ted Kremenek28a71942010-11-13 00:36:47 +00001863void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001864 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1865 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001866 AddStmt(CE->getCallee());
1867 AddStmt(CE->getArg(0));
1868}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001869void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1870 // Visit the name of the type being destroyed.
1871 AddTypeLoc(E->getDestroyedTypeInfo());
1872 // Visit the scope type that looks disturbingly like the nested-name-specifier
1873 // but isn't.
1874 AddTypeLoc(E->getScopeTypeInfo());
1875 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001876 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1877 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001878 // Visit base expression.
1879 AddStmt(E->getBase());
1880}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001881void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1882 AddTypeLoc(E->getTypeSourceInfo());
1883}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001884void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1885 EnqueueChildren(E);
1886 AddTypeLoc(E->getTypeSourceInfo());
1887}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001888void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1889 EnqueueChildren(E);
1890 if (E->isTypeOperand())
1891 AddTypeLoc(E->getTypeOperandSourceInfo());
1892}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001893
1894void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1895 *E) {
1896 EnqueueChildren(E);
1897 AddTypeLoc(E->getTypeSourceInfo());
1898}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001899void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1900 EnqueueChildren(E);
1901 if (E->isTypeOperand())
1902 AddTypeLoc(E->getTypeOperandSourceInfo());
1903}
Argyrios Kyrtzidisdcbb2fb2011-12-03 03:49:44 +00001904
1905void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1906 EnqueueChildren(S);
1907 AddDecl(S->getExceptionDecl());
1908}
1909
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001910void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001911 if (DR->hasExplicitTemplateArgs()) {
1912 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1913 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001914 WL.push_back(DeclRefExprParts(DR, Parent));
1915}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001916void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1917 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1918 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001919 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001920}
Ted Kremenek035dc412010-11-13 00:36:50 +00001921void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1922 unsigned size = WL.size();
1923 bool isFirst = true;
1924 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1925 D != DEnd; ++D) {
1926 AddDecl(*D, isFirst);
1927 isFirst = false;
1928 }
1929 if (size == WL.size())
1930 return;
1931 // Now reverse the entries we just added. This will match the DFS
1932 // ordering performed by the worklist.
1933 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1934 std::reverse(I, E);
1935}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001936void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1937 AddStmt(E->getInit());
1938 typedef DesignatedInitExpr::Designator Designator;
1939 for (DesignatedInitExpr::reverse_designators_iterator
1940 D = E->designators_rbegin(), DEnd = E->designators_rend();
1941 D != DEnd; ++D) {
1942 if (D->isFieldDesignator()) {
1943 if (FieldDecl *Field = D->getField())
1944 AddMemberRef(Field, D->getFieldLoc());
1945 continue;
1946 }
1947 if (D->isArrayDesignator()) {
1948 AddStmt(E->getArrayIndex(*D));
1949 continue;
1950 }
1951 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1952 AddStmt(E->getArrayRangeEnd(*D));
1953 AddStmt(E->getArrayRangeStart(*D));
1954 }
1955}
Ted Kremenek28a71942010-11-13 00:36:47 +00001956void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1957 EnqueueChildren(E);
1958 AddTypeLoc(E->getTypeInfoAsWritten());
1959}
1960void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1961 AddStmt(FS->getBody());
1962 AddStmt(FS->getInc());
1963 AddStmt(FS->getCond());
1964 AddDecl(FS->getConditionVariable());
1965 AddStmt(FS->getInit());
1966}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001967void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1968 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1969}
Ted Kremenek28a71942010-11-13 00:36:47 +00001970void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1971 AddStmt(If->getElse());
1972 AddStmt(If->getThen());
1973 AddStmt(If->getCond());
1974 AddDecl(If->getConditionVariable());
1975}
1976void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1977 // We care about the syntactic form of the initializer list, only.
1978 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1979 IE = Syntactic;
1980 EnqueueChildren(IE);
1981}
1982void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001983 WL.push_back(MemberExprParts(M, Parent));
1984
1985 // If the base of the member access expression is an implicit 'this', don't
1986 // visit it.
1987 // FIXME: If we ever want to show these implicit accesses, this will be
1988 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001989 if (!M->isImplicitAccess())
1990 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001991}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001992void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1993 AddTypeLoc(E->getEncodedTypeSourceInfo());
1994}
Ted Kremenek28a71942010-11-13 00:36:47 +00001995void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1996 EnqueueChildren(M);
1997 AddTypeLoc(M->getClassReceiverTypeInfo());
1998}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001999void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2000 // Visit the components of the offsetof expression.
2001 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2002 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2003 const OffsetOfNode &Node = E->getComponent(I-1);
2004 switch (Node.getKind()) {
2005 case OffsetOfNode::Array:
2006 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2007 break;
2008 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002009 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002010 break;
2011 case OffsetOfNode::Identifier:
2012 case OffsetOfNode::Base:
2013 continue;
2014 }
2015 }
2016 // Visit the type into which we're computing the offset.
2017 AddTypeLoc(E->getTypeSourceInfo());
2018}
Ted Kremenek28a71942010-11-13 00:36:47 +00002019void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002020 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002021 WL.push_back(OverloadExprParts(E, Parent));
2022}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002023void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2024 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002025 EnqueueChildren(E);
2026 if (E->isArgumentType())
2027 AddTypeLoc(E->getArgumentTypeInfo());
2028}
Ted Kremenek28a71942010-11-13 00:36:47 +00002029void EnqueueVisitor::VisitStmt(Stmt *S) {
2030 EnqueueChildren(S);
2031}
2032void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2033 AddStmt(S->getBody());
2034 AddStmt(S->getCond());
2035 AddDecl(S->getConditionVariable());
2036}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002037
Ted Kremenek28a71942010-11-13 00:36:47 +00002038void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2039 AddStmt(W->getBody());
2040 AddStmt(W->getCond());
2041 AddDecl(W->getConditionVariable());
2042}
John Wiegley21ff2e52011-04-28 00:16:57 +00002043
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002044void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2045 AddTypeLoc(E->getQueriedTypeSourceInfo());
2046}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002047
2048void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002049 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002050 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002051}
2052
John Wiegley21ff2e52011-04-28 00:16:57 +00002053void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2054 AddTypeLoc(E->getQueriedTypeSourceInfo());
2055}
2056
John Wiegley55262202011-04-25 06:54:41 +00002057void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2058 EnqueueChildren(E);
2059}
2060
Ted Kremenek28a71942010-11-13 00:36:47 +00002061void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2062 VisitOverloadExpr(U);
2063 if (!U->isImplicitAccess())
2064 AddStmt(U->getBase());
2065}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002066void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2067 AddStmt(E->getSubExpr());
2068 AddTypeLoc(E->getWrittenTypeInfo());
2069}
Douglas Gregor94d96292011-01-19 20:34:17 +00002070void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2071 WL.push_back(SizeOfPackExprParts(E, Parent));
2072}
John McCall4b9c2d22011-11-06 09:01:30 +00002073void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2074 // If the opaque value has a source expression, just transparently
2075 // visit that. This is useful for (e.g.) pseudo-object expressions.
2076 if (Expr *SourceExpr = E->getSourceExpr())
2077 return Visit(SourceExpr);
John McCall4b9c2d22011-11-06 09:01:30 +00002078}
2079void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2080 // Treat the expression like its syntactic form.
2081 Visit(E->getSyntacticForm());
2082}
Ted Kremenek60458782010-11-12 21:34:16 +00002083
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002084void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002085 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002086}
2087
2088bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2089 if (RegionOfInterest.isValid()) {
2090 SourceRange Range = getRawCursorExtent(C);
2091 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2092 return false;
2093 }
2094 return true;
2095}
2096
2097bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2098 while (!WL.empty()) {
2099 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002100 VisitorJob LI = WL.back();
2101 WL.pop_back();
2102
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002103 // Set the Parent field, then back to its old value once we're done.
2104 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2105
2106 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002107 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002108 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002109 if (!D)
2110 continue;
2111
2112 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002113 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2114 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002115 return true;
2116
2117 continue;
2118 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002119 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002120 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002121 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2122 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2123 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2124 Arg != ArgEnd; ++Arg) {
2125 if (VisitTemplateArgumentLoc(*Arg))
2126 return true;
2127 }
2128 continue;
2129 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002130 case VisitorJob::TypeLocVisitKind: {
2131 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002132 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002133 return true;
2134 continue;
2135 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002136 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002137 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002138 if (LabelStmt *stmt = LS->getStmt()) {
2139 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2140 TU))) {
2141 return true;
2142 }
2143 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002144 continue;
2145 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002146
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002147 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2148 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2149 if (VisitNestedNameSpecifierLoc(V->get()))
2150 return true;
2151 continue;
2152 }
2153
Ted Kremenekf64d8032010-11-18 00:02:32 +00002154 case VisitorJob::DeclarationNameInfoVisitKind: {
2155 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2156 ->get()))
2157 return true;
2158 continue;
2159 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002160 case VisitorJob::MemberRefVisitKind: {
2161 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2162 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2163 return true;
2164 continue;
2165 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002166 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002167 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002168 if (!S)
2169 continue;
2170
Ted Kremenekf1107452010-11-12 18:26:56 +00002171 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002172 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002173 if (!IsInRegionOfInterest(Cursor))
2174 continue;
2175 switch (Visitor(Cursor, Parent, ClientData)) {
2176 case CXChildVisit_Break: return true;
2177 case CXChildVisit_Continue: break;
2178 case CXChildVisit_Recurse:
2179 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002180 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002181 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002182 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002183 }
2184 case VisitorJob::MemberExprPartsKind: {
2185 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002186 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002187
2188 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002189 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2190 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002191 return true;
2192
2193 // Visit the declaration name.
2194 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2195 return true;
2196
2197 // Visit the explicitly-specified template arguments, if any.
2198 if (M->hasExplicitTemplateArgs()) {
2199 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2200 *ArgEnd = Arg + M->getNumTemplateArgs();
2201 Arg != ArgEnd; ++Arg) {
2202 if (VisitTemplateArgumentLoc(*Arg))
2203 return true;
2204 }
2205 }
2206 continue;
2207 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002208 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002209 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002210 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002211 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2212 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002213 return true;
2214 // Visit declaration name.
2215 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2216 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002217 continue;
2218 }
Ted Kremenek60458782010-11-12 21:34:16 +00002219 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002220 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002221 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002222 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2223 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002224 return true;
2225 // Visit the declaration name.
2226 if (VisitDeclarationNameInfo(O->getNameInfo()))
2227 return true;
2228 // Visit the overloaded declaration reference.
2229 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2230 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002231 continue;
2232 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002233 case VisitorJob::SizeOfPackExprPartsKind: {
2234 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2235 NamedDecl *Pack = E->getPack();
2236 if (isa<TemplateTypeParmDecl>(Pack)) {
2237 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2238 E->getPackLoc(), TU)))
2239 return true;
2240
2241 continue;
2242 }
2243
2244 if (isa<TemplateTemplateParmDecl>(Pack)) {
2245 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2246 E->getPackLoc(), TU)))
2247 return true;
2248
2249 continue;
2250 }
2251
2252 // Non-type template parameter packs and function parameter packs are
2253 // treated like DeclRefExpr cursors.
2254 continue;
2255 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002256 }
2257 }
2258 return false;
2259}
2260
Ted Kremenekcdba6592010-11-18 00:42:18 +00002261bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002262 VisitorWorkList *WL = 0;
2263 if (!WorkListFreeList.empty()) {
2264 WL = WorkListFreeList.back();
2265 WL->clear();
2266 WorkListFreeList.pop_back();
2267 }
2268 else {
2269 WL = new VisitorWorkList();
2270 WorkListCache.push_back(WL);
2271 }
2272 EnqueueWorkList(*WL, S);
2273 bool result = RunVisitorWorkList(*WL);
2274 WorkListFreeList.push_back(WL);
2275 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002276}
2277
Francois Pichet48a8d142011-07-25 22:00:44 +00002278namespace {
2279typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2280RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2281 const DeclarationNameInfo &NI,
2282 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002283 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002284 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2285 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2286 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2287
2288 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2289
2290 RefNamePieces Pieces;
2291
2292 if (WantQualifier && QLoc.isValid())
2293 Pieces.push_back(QLoc);
2294
2295 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2296 Pieces.push_back(NI.getLoc());
2297
2298 if (WantTemplateArgs && TemplateArgs)
2299 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2300 TemplateArgs->RAngleLoc));
2301
2302 if (Kind == DeclarationName::CXXOperatorName) {
2303 Pieces.push_back(SourceLocation::getFromRawEncoding(
2304 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2305 Pieces.push_back(SourceLocation::getFromRawEncoding(
2306 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2307 }
2308
2309 if (WantSinglePiece) {
2310 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2311 Pieces.clear();
2312 Pieces.push_back(R);
2313 }
2314
2315 return Pieces;
2316}
2317}
2318
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002319//===----------------------------------------------------------------------===//
2320// Misc. API hooks.
2321//===----------------------------------------------------------------------===//
2322
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002323static llvm::sys::Mutex EnableMultithreadingMutex;
2324static bool EnabledMultithreading;
2325
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002326static void fatal_error_handler(void *user_data, const std::string& reason) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002327 // Write the result out to stderr avoiding errs() because raw_ostreams can
2328 // call report_fatal_error.
Argyrios Kyrtzidisdb7a8002011-12-15 06:51:30 +00002329 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002330 ::abort();
2331}
2332
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002333extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002334CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2335 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002336 // Disable pretty stack trace functionality, which will otherwise be a very
2337 // poor citizen of the world and set up all sorts of signal handlers.
2338 llvm::DisablePrettyStackTrace = true;
2339
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002340 // We use crash recovery to make some of our APIs more reliable, implicitly
2341 // enable it.
2342 llvm::CrashRecoveryContext::Enable();
2343
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002344 // Enable support for multithreading in LLVM.
2345 {
2346 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2347 if (!EnabledMultithreading) {
Argyrios Kyrtzidisfa39f5b2011-12-15 04:52:41 +00002348 llvm::install_fatal_error_handler(fatal_error_handler, 0);
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002349 llvm::llvm_start_multithreaded();
2350 EnabledMultithreading = true;
2351 }
2352 }
2353
Douglas Gregora030b7c2010-01-22 20:35:53 +00002354 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002355 if (excludeDeclarationsFromPCH)
2356 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002357 if (displayDiagnostics)
2358 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002359 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002360}
2361
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002362void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002363 if (CIdx)
2364 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002365}
2366
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002367void clang_toggleCrashRecovery(unsigned isEnabled) {
2368 if (isEnabled)
2369 llvm::CrashRecoveryContext::Enable();
2370 else
2371 llvm::CrashRecoveryContext::Disable();
2372}
2373
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002374CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002375 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002376 if (!CIdx)
2377 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002378
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002379 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002380 FileSystemOptions FileSystemOpts;
2381 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002382
David Blaikied6471f72011-09-25 23:23:43 +00002383 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002384 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002385 CXXIdx->getOnlyLocalDecls(),
2386 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002387 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002388}
2389
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002390unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002391 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002392 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002393}
2394
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002395CXTranslationUnit
2396clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2397 const char *source_filename,
2398 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002399 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002400 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002401 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002402 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002403 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002404 return clang_parseTranslationUnit(CIdx, source_filename,
2405 command_line_args, num_command_line_args,
2406 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002407 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002408}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002409
2410struct ParseTranslationUnitInfo {
2411 CXIndex CIdx;
2412 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002413 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002414 int num_command_line_args;
2415 struct CXUnsavedFile *unsaved_files;
2416 unsigned num_unsaved_files;
2417 unsigned options;
2418 CXTranslationUnit result;
2419};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002420static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002421 ParseTranslationUnitInfo *PTUI =
2422 static_cast<ParseTranslationUnitInfo*>(UserData);
2423 CXIndex CIdx = PTUI->CIdx;
2424 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002425 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002426 int num_command_line_args = PTUI->num_command_line_args;
2427 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2428 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2429 unsigned options = PTUI->options;
2430 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002431
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002432 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002433 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002434
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002435 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2436
Douglas Gregor44c181a2010-07-23 00:33:23 +00002437 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002438 // FIXME: Add a flag for modules.
2439 TranslationUnitKind TUKind
2440 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002441 bool CacheCodeCompetionResults
2442 = options & CXTranslationUnit_CacheCompletionResults;
2443
Douglas Gregor5352ac02010-01-28 00:27:43 +00002444 // Configure the diagnostics.
2445 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002446 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002447 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2448 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002449
Ted Kremenek25a11e12011-03-22 01:15:24 +00002450 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002451 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2452 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002453 DiagCleanup(Diags.getPtr());
2454
2455 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2456 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2457
2458 // Recover resources if we crash before exiting this function.
2459 llvm::CrashRecoveryContextCleanupRegistrar<
2460 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2461
Douglas Gregor4db64a42010-01-23 00:14:00 +00002462 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002463 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002464 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002465 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002466 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2467 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002468 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002469
Ted Kremenek25a11e12011-03-22 01:15:24 +00002470 llvm::OwningPtr<std::vector<const char *> >
2471 Args(new std::vector<const char*>());
2472
2473 // Recover resources if we crash before exiting this method.
2474 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2475 ArgsCleanup(Args.get());
2476
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002477 // Since the Clang C library is primarily used by batch tools dealing with
2478 // (often very broken) source code, where spell-checking can have a
2479 // significant negative impact on performance (particularly when
2480 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002481 // Only do this if we haven't found a spell-checking-related argument.
2482 bool FoundSpellCheckingArgument = false;
2483 for (int I = 0; I != num_command_line_args; ++I) {
2484 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2485 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2486 FoundSpellCheckingArgument = true;
2487 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002488 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002489 }
2490 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002491 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002492
Ted Kremenek25a11e12011-03-22 01:15:24 +00002493 Args->insert(Args->end(), command_line_args,
2494 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002495
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002496 // The 'source_filename' argument is optional. If the caller does not
2497 // specify it then it is assumed that the source file is specified
2498 // in the actual argument list.
2499 // Put the source file after command_line_args otherwise if '-x' flag is
2500 // present it will be unused.
2501 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002502 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002503
Douglas Gregor44c181a2010-07-23 00:33:23 +00002504 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002505 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002506 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002507 Args->push_back("-Xclang");
2508 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002509 NestedMacroExpansions
2510 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002511 }
2512
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002513 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002514 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002515 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2516 /* vector::data() not portable */,
2517 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002518 Diags,
2519 CXXIdx->getClangResourcesPath(),
2520 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002521 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002522 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002523 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002524 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002525 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002526 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002527 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002528 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002529
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002530 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002531 // Make sure to check that 'Unit' is non-NULL.
2532 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2533 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2534 DEnd = Unit->stored_diag_end();
2535 D != DEnd; ++D) {
2536 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2537 CXString Msg = clang_formatDiagnostic(&Diag,
2538 clang_defaultDiagnosticDisplayOptions());
2539 fprintf(stderr, "%s\n", clang_getCString(Msg));
2540 clang_disposeString(Msg);
2541 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002542#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002543 // On Windows, force a flush, since there may be multiple copies of
2544 // stderr and stdout in the file system, all with different buffers
2545 // but writing to the same device.
2546 fflush(stderr);
2547#endif
2548 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002549 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002550
Ted Kremeneka60ed472010-11-16 08:15:36 +00002551 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002552}
2553CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2554 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002555 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002556 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002557 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002558 unsigned num_unsaved_files,
2559 unsigned options) {
2560 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002561 num_command_line_args, unsaved_files,
2562 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002563 llvm::CrashRecoveryContext CRC;
2564
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002565 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002566 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2567 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2568 fprintf(stderr, " 'command_line_args' : [");
2569 for (int i = 0; i != num_command_line_args; ++i) {
2570 if (i)
2571 fprintf(stderr, ", ");
2572 fprintf(stderr, "'%s'", command_line_args[i]);
2573 }
2574 fprintf(stderr, "],\n");
2575 fprintf(stderr, " 'unsaved_files' : [");
2576 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2577 if (i)
2578 fprintf(stderr, ", ");
2579 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2580 unsaved_files[i].Length);
2581 }
2582 fprintf(stderr, "],\n");
2583 fprintf(stderr, " 'options' : %d,\n", options);
2584 fprintf(stderr, "}\n");
2585
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002586 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002587 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2588 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002589 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002590
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002591 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002592}
2593
Douglas Gregor19998442010-08-13 15:35:05 +00002594unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2595 return CXSaveTranslationUnit_None;
2596}
2597
2598int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2599 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002600 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002601 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002602
Douglas Gregor39c411f2011-07-06 16:43:36 +00002603 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002604 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2605 PrintLibclangResourceUsage(TU);
2606 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002607}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002608
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002609void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002610 if (CTUnit) {
2611 // If the translation unit has been marked as unsafe to free, just discard
2612 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002613 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002614 return;
2615
Ted Kremeneka60ed472010-11-16 08:15:36 +00002616 delete static_cast<ASTUnit *>(CTUnit->TUData);
2617 disposeCXStringPool(CTUnit->StringPool);
Ted Kremenek15322172011-11-10 08:43:12 +00002618 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002619 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002620 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002621}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002622
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002623unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2624 return CXReparse_None;
2625}
2626
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002627struct ReparseTranslationUnitInfo {
2628 CXTranslationUnit TU;
2629 unsigned num_unsaved_files;
2630 struct CXUnsavedFile *unsaved_files;
2631 unsigned options;
2632 int result;
2633};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002634
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002635static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002636 ReparseTranslationUnitInfo *RTUI =
2637 static_cast<ReparseTranslationUnitInfo*>(UserData);
2638 CXTranslationUnit TU = RTUI->TU;
Ted Kremenek15322172011-11-10 08:43:12 +00002639
2640 // Reset the associated diagnostics.
2641 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2642 TU->Diagnostics = 0;
2643
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002644 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2645 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2646 unsigned options = RTUI->options;
2647 (void) options;
2648 RTUI->result = 1;
2649
Douglas Gregorabc563f2010-07-19 21:46:24 +00002650 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002651 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002652
Ted Kremeneka60ed472010-11-16 08:15:36 +00002653 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002654 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002655
Ted Kremenek25a11e12011-03-22 01:15:24 +00002656 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2657 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2658
2659 // Recover resources if we crash before exiting this function.
2660 llvm::CrashRecoveryContextCleanupRegistrar<
2661 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2662
Douglas Gregorabc563f2010-07-19 21:46:24 +00002663 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002664 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002665 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002666 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002667 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2668 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002669 }
2670
Ted Kremenek4ee99262011-03-22 20:16:19 +00002671 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2672 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002673 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002674}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002675
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002676int clang_reparseTranslationUnit(CXTranslationUnit TU,
2677 unsigned num_unsaved_files,
2678 struct CXUnsavedFile *unsaved_files,
2679 unsigned options) {
2680 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2681 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002682
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002683 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002684 clang_reparseTranslationUnit_Impl(&RTUI);
2685 return RTUI.result;
2686 }
2687
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002688 llvm::CrashRecoveryContext CRC;
2689
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002690 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002691 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002692 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002693 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002694 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2695 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002696
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002697 return RTUI.result;
2698}
2699
Douglas Gregordf95a132010-08-09 20:45:32 +00002700
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002701CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002702 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002703 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002704
Ted Kremeneka60ed472010-11-16 08:15:36 +00002705 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002706 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002707}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002708
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002709CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002710 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002711 return Result;
2712}
2713
Ted Kremenekfb480492010-01-13 21:46:36 +00002714} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002715
Ted Kremenekfb480492010-01-13 21:46:36 +00002716//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002717// CXFile Operations.
2718//===----------------------------------------------------------------------===//
2719
2720extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002721CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002722 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002723 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002724
Steve Naroff88145032009-10-27 14:35:18 +00002725 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002726 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002727}
2728
2729time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002730 if (!SFile)
2731 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002732
Steve Naroff88145032009-10-27 14:35:18 +00002733 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2734 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002735}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002736
Douglas Gregorb9790342010-01-22 21:44:22 +00002737CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2738 if (!tu)
2739 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002740
Ted Kremeneka60ed472010-11-16 08:15:36 +00002741 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002742
Douglas Gregorb9790342010-01-22 21:44:22 +00002743 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002744 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002745}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002746
Douglas Gregordd3e5542011-05-04 00:14:37 +00002747unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2748 if (!tu || !file)
2749 return 0;
2750
2751 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2752 FileEntry *FEnt = static_cast<FileEntry *>(file);
2753 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2754 .isFileMultipleIncludeGuarded(FEnt);
2755}
2756
Ted Kremenekfb480492010-01-13 21:46:36 +00002757} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002758
Ted Kremenekfb480492010-01-13 21:46:36 +00002759//===----------------------------------------------------------------------===//
2760// CXCursor Operations.
2761//===----------------------------------------------------------------------===//
2762
Ted Kremenekfb480492010-01-13 21:46:36 +00002763static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002764 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002765 return getDeclFromExpr(CE->getSubExpr());
2766
Ted Kremenekfb480492010-01-13 21:46:36 +00002767 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2768 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002769 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2770 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002771 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2772 return ME->getMemberDecl();
2773 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2774 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002775 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002776 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
John McCall4b9c2d22011-11-06 09:01:30 +00002777 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2778 return getDeclFromExpr(POE->getSyntacticForm());
2779 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2780 if (Expr *Src = OVE->getSourceExpr())
2781 return getDeclFromExpr(Src);
Douglas Gregordb1314e2010-10-01 21:11:22 +00002782
Ted Kremenekfb480492010-01-13 21:46:36 +00002783 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2784 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002785 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002786 if (!CE->isElidable())
2787 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002788 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2789 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002790
Douglas Gregordb1314e2010-10-01 21:11:22 +00002791 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2792 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002793 if (SubstNonTypeTemplateParmPackExpr *NTTP
2794 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2795 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002796 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2797 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2798 isa<ParmVarDecl>(SizeOfPack->getPack()))
2799 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002800
Ted Kremenekfb480492010-01-13 21:46:36 +00002801 return 0;
2802}
2803
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002804static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002805 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2806 return getLocationFromExpr(CE->getSubExpr());
2807
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002808 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2809 return /*FIXME:*/Msg->getLeftLoc();
2810 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2811 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002812 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2813 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002814 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2815 return Member->getMemberLoc();
2816 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2817 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002818 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2819 return SizeOfPack->getPackLoc();
2820
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002821 return E->getLocStart();
2822}
2823
Ted Kremenekfb480492010-01-13 21:46:36 +00002824extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002825
2826unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002827 CXCursorVisitor visitor,
2828 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002829 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2830 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002831 return CursorVis.VisitChildren(parent);
2832}
2833
David Chisnall3387c652010-11-03 14:12:26 +00002834#ifndef __has_feature
2835#define __has_feature(x) 0
2836#endif
2837#if __has_feature(blocks)
2838typedef enum CXChildVisitResult
2839 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2840
2841static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2842 CXClientData client_data) {
2843 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2844 return block(cursor, parent);
2845}
2846#else
2847// If we are compiled with a compiler that doesn't have native blocks support,
2848// define and call the block manually, so the
2849typedef struct _CXChildVisitResult
2850{
2851 void *isa;
2852 int flags;
2853 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002854 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2855 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002856} *CXCursorVisitorBlock;
2857
2858static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2859 CXClientData client_data) {
2860 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2861 return block->invoke(block, cursor, parent);
2862}
2863#endif
2864
2865
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002866unsigned clang_visitChildrenWithBlock(CXCursor parent,
2867 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002868 return clang_visitChildren(parent, visitWithBlock, block);
2869}
2870
Douglas Gregor78205d42010-01-20 21:45:58 +00002871static CXString getDeclSpelling(Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00002872 if (!D)
2873 return createCXString("");
2874
2875 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002876 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002877 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00002878 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2879 return createCXString(Property->getIdentifier()->getName());
2880
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002881 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002882 }
2883
Douglas Gregor78205d42010-01-20 21:45:58 +00002884 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002885 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002886
Douglas Gregor78205d42010-01-20 21:45:58 +00002887 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2888 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2889 // and returns different names. NamedDecl returns the class name and
2890 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002891 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002892
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002893 if (isa<UsingDirectiveDecl>(D))
2894 return createCXString("");
2895
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002896 llvm::SmallString<1024> S;
2897 llvm::raw_svector_ostream os(S);
2898 ND->printName(os);
2899
2900 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002901}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002902
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002903CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002904 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002905 return clang_getTranslationUnitSpelling(
2906 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002907
Steve Narofff334b4e2009-09-02 18:26:48 +00002908 if (clang_isReference(C.kind)) {
2909 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002910 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002911 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002912 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002913 }
2914 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002915 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002916 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002917 }
2918 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002919 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002920 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002921 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002922 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002923 case CXCursor_CXXBaseSpecifier: {
2924 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2925 return createCXString(B->getType().getAsString());
2926 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002927 case CXCursor_TypeRef: {
2928 TypeDecl *Type = getCursorTypeRef(C).first;
2929 assert(Type && "Missing type decl");
2930
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002931 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2932 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002933 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002934 case CXCursor_TemplateRef: {
2935 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002936 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002937
2938 return createCXString(Template->getNameAsString());
2939 }
Douglas Gregor69319002010-08-31 23:48:11 +00002940
2941 case CXCursor_NamespaceRef: {
2942 NamedDecl *NS = getCursorNamespaceRef(C).first;
2943 assert(NS && "Missing namespace decl");
2944
2945 return createCXString(NS->getNameAsString());
2946 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002947
Douglas Gregora67e03f2010-09-09 21:42:20 +00002948 case CXCursor_MemberRef: {
2949 FieldDecl *Field = getCursorMemberRef(C).first;
2950 assert(Field && "Missing member decl");
2951
2952 return createCXString(Field->getNameAsString());
2953 }
2954
Douglas Gregor36897b02010-09-10 00:22:18 +00002955 case CXCursor_LabelRef: {
2956 LabelStmt *Label = getCursorLabelRef(C).first;
2957 assert(Label && "Missing label");
2958
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002959 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002960 }
2961
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002962 case CXCursor_OverloadedDeclRef: {
2963 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2964 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2965 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2966 return createCXString(ND->getNameAsString());
2967 return createCXString("");
2968 }
2969 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2970 return createCXString(E->getName().getAsString());
2971 OverloadedTemplateStorage *Ovl
2972 = Storage.get<OverloadedTemplateStorage*>();
2973 if (Ovl->size() == 0)
2974 return createCXString("");
2975 return createCXString((*Ovl->begin())->getNameAsString());
2976 }
2977
Daniel Dunbaracca7252009-11-30 20:42:49 +00002978 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002979 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002980 }
2981 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002982
2983 if (clang_isExpression(C.kind)) {
2984 Decl *D = getDeclFromExpr(getCursorExpr(C));
2985 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002986 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002987 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002988 }
2989
Douglas Gregor36897b02010-09-10 00:22:18 +00002990 if (clang_isStatement(C.kind)) {
2991 Stmt *S = getCursorStmt(C);
2992 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002993 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002994
2995 return createCXString("");
2996 }
2997
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00002998 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00002999 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003000 ->getNameStart());
3001
Douglas Gregor572feb22010-03-18 18:04:21 +00003002 if (C.kind == CXCursor_MacroDefinition)
3003 return createCXString(getCursorMacroDefinition(C)->getName()
3004 ->getNameStart());
3005
Douglas Gregorecdcb882010-10-20 22:00:55 +00003006 if (C.kind == CXCursor_InclusionDirective)
3007 return createCXString(getCursorInclusionDirective(C)->getFileName());
3008
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003009 if (clang_isDeclaration(C.kind))
3010 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003011
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003012 if (C.kind == CXCursor_AnnotateAttr) {
3013 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3014 return createCXString(AA->getAnnotation());
3015 }
3016
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003017 if (C.kind == CXCursor_AsmLabelAttr) {
3018 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3019 return createCXString(AA->getLabel());
3020 }
3021
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003022 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003023}
3024
Douglas Gregor358559d2010-10-02 22:49:11 +00003025CXString clang_getCursorDisplayName(CXCursor C) {
3026 if (!clang_isDeclaration(C.kind))
3027 return clang_getCursorSpelling(C);
3028
3029 Decl *D = getCursorDecl(C);
3030 if (!D)
3031 return createCXString("");
3032
Douglas Gregor30c42402011-09-27 22:38:19 +00003033 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003034 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3035 D = FunTmpl->getTemplatedDecl();
3036
3037 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3038 llvm::SmallString<64> Str;
3039 llvm::raw_svector_ostream OS(Str);
3040 OS << Function->getNameAsString();
3041 if (Function->getPrimaryTemplate())
3042 OS << "<>";
3043 OS << "(";
3044 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3045 if (I)
3046 OS << ", ";
3047 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3048 }
3049
3050 if (Function->isVariadic()) {
3051 if (Function->getNumParams())
3052 OS << ", ";
3053 OS << "...";
3054 }
3055 OS << ")";
3056 return createCXString(OS.str());
3057 }
3058
3059 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3060 llvm::SmallString<64> Str;
3061 llvm::raw_svector_ostream OS(Str);
3062 OS << ClassTemplate->getNameAsString();
3063 OS << "<";
3064 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3065 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3066 if (I)
3067 OS << ", ";
3068
3069 NamedDecl *Param = Params->getParam(I);
3070 if (Param->getIdentifier()) {
3071 OS << Param->getIdentifier()->getName();
3072 continue;
3073 }
3074
3075 // There is no parameter name, which makes this tricky. Try to come up
3076 // with something useful that isn't too long.
3077 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3078 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3079 else if (NonTypeTemplateParmDecl *NTTP
3080 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3081 OS << NTTP->getType().getAsString(Policy);
3082 else
3083 OS << "template<...> class";
3084 }
3085
3086 OS << ">";
3087 return createCXString(OS.str());
3088 }
3089
3090 if (ClassTemplateSpecializationDecl *ClassSpec
3091 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3092 // If the type was explicitly written, use that.
3093 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3094 return createCXString(TSInfo->getType().getAsString(Policy));
3095
3096 llvm::SmallString<64> Str;
3097 llvm::raw_svector_ostream OS(Str);
3098 OS << ClassSpec->getNameAsString();
3099 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003100 ClassSpec->getTemplateArgs().data(),
3101 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003102 Policy);
3103 return createCXString(OS.str());
3104 }
3105
3106 return clang_getCursorSpelling(C);
3107}
3108
Ted Kremeneke68fff62010-02-17 00:41:32 +00003109CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003110 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003111 case CXCursor_FunctionDecl:
3112 return createCXString("FunctionDecl");
3113 case CXCursor_TypedefDecl:
3114 return createCXString("TypedefDecl");
3115 case CXCursor_EnumDecl:
3116 return createCXString("EnumDecl");
3117 case CXCursor_EnumConstantDecl:
3118 return createCXString("EnumConstantDecl");
3119 case CXCursor_StructDecl:
3120 return createCXString("StructDecl");
3121 case CXCursor_UnionDecl:
3122 return createCXString("UnionDecl");
3123 case CXCursor_ClassDecl:
3124 return createCXString("ClassDecl");
3125 case CXCursor_FieldDecl:
3126 return createCXString("FieldDecl");
3127 case CXCursor_VarDecl:
3128 return createCXString("VarDecl");
3129 case CXCursor_ParmDecl:
3130 return createCXString("ParmDecl");
3131 case CXCursor_ObjCInterfaceDecl:
3132 return createCXString("ObjCInterfaceDecl");
3133 case CXCursor_ObjCCategoryDecl:
3134 return createCXString("ObjCCategoryDecl");
3135 case CXCursor_ObjCProtocolDecl:
3136 return createCXString("ObjCProtocolDecl");
3137 case CXCursor_ObjCPropertyDecl:
3138 return createCXString("ObjCPropertyDecl");
3139 case CXCursor_ObjCIvarDecl:
3140 return createCXString("ObjCIvarDecl");
3141 case CXCursor_ObjCInstanceMethodDecl:
3142 return createCXString("ObjCInstanceMethodDecl");
3143 case CXCursor_ObjCClassMethodDecl:
3144 return createCXString("ObjCClassMethodDecl");
3145 case CXCursor_ObjCImplementationDecl:
3146 return createCXString("ObjCImplementationDecl");
3147 case CXCursor_ObjCCategoryImplDecl:
3148 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003149 case CXCursor_CXXMethod:
3150 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003151 case CXCursor_UnexposedDecl:
3152 return createCXString("UnexposedDecl");
3153 case CXCursor_ObjCSuperClassRef:
3154 return createCXString("ObjCSuperClassRef");
3155 case CXCursor_ObjCProtocolRef:
3156 return createCXString("ObjCProtocolRef");
3157 case CXCursor_ObjCClassRef:
3158 return createCXString("ObjCClassRef");
3159 case CXCursor_TypeRef:
3160 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003161 case CXCursor_TemplateRef:
3162 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003163 case CXCursor_NamespaceRef:
3164 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003165 case CXCursor_MemberRef:
3166 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003167 case CXCursor_LabelRef:
3168 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003169 case CXCursor_OverloadedDeclRef:
3170 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003171 case CXCursor_IntegerLiteral:
3172 return createCXString("IntegerLiteral");
3173 case CXCursor_FloatingLiteral:
3174 return createCXString("FloatingLiteral");
3175 case CXCursor_ImaginaryLiteral:
3176 return createCXString("ImaginaryLiteral");
3177 case CXCursor_StringLiteral:
3178 return createCXString("StringLiteral");
3179 case CXCursor_CharacterLiteral:
3180 return createCXString("CharacterLiteral");
3181 case CXCursor_ParenExpr:
3182 return createCXString("ParenExpr");
3183 case CXCursor_UnaryOperator:
3184 return createCXString("UnaryOperator");
3185 case CXCursor_ArraySubscriptExpr:
3186 return createCXString("ArraySubscriptExpr");
3187 case CXCursor_BinaryOperator:
3188 return createCXString("BinaryOperator");
3189 case CXCursor_CompoundAssignOperator:
3190 return createCXString("CompoundAssignOperator");
3191 case CXCursor_ConditionalOperator:
3192 return createCXString("ConditionalOperator");
3193 case CXCursor_CStyleCastExpr:
3194 return createCXString("CStyleCastExpr");
3195 case CXCursor_CompoundLiteralExpr:
3196 return createCXString("CompoundLiteralExpr");
3197 case CXCursor_InitListExpr:
3198 return createCXString("InitListExpr");
3199 case CXCursor_AddrLabelExpr:
3200 return createCXString("AddrLabelExpr");
3201 case CXCursor_StmtExpr:
3202 return createCXString("StmtExpr");
3203 case CXCursor_GenericSelectionExpr:
3204 return createCXString("GenericSelectionExpr");
3205 case CXCursor_GNUNullExpr:
3206 return createCXString("GNUNullExpr");
3207 case CXCursor_CXXStaticCastExpr:
3208 return createCXString("CXXStaticCastExpr");
3209 case CXCursor_CXXDynamicCastExpr:
3210 return createCXString("CXXDynamicCastExpr");
3211 case CXCursor_CXXReinterpretCastExpr:
3212 return createCXString("CXXReinterpretCastExpr");
3213 case CXCursor_CXXConstCastExpr:
3214 return createCXString("CXXConstCastExpr");
3215 case CXCursor_CXXFunctionalCastExpr:
3216 return createCXString("CXXFunctionalCastExpr");
3217 case CXCursor_CXXTypeidExpr:
3218 return createCXString("CXXTypeidExpr");
3219 case CXCursor_CXXBoolLiteralExpr:
3220 return createCXString("CXXBoolLiteralExpr");
3221 case CXCursor_CXXNullPtrLiteralExpr:
3222 return createCXString("CXXNullPtrLiteralExpr");
3223 case CXCursor_CXXThisExpr:
3224 return createCXString("CXXThisExpr");
3225 case CXCursor_CXXThrowExpr:
3226 return createCXString("CXXThrowExpr");
3227 case CXCursor_CXXNewExpr:
3228 return createCXString("CXXNewExpr");
3229 case CXCursor_CXXDeleteExpr:
3230 return createCXString("CXXDeleteExpr");
3231 case CXCursor_UnaryExpr:
3232 return createCXString("UnaryExpr");
3233 case CXCursor_ObjCStringLiteral:
3234 return createCXString("ObjCStringLiteral");
3235 case CXCursor_ObjCEncodeExpr:
3236 return createCXString("ObjCEncodeExpr");
3237 case CXCursor_ObjCSelectorExpr:
3238 return createCXString("ObjCSelectorExpr");
3239 case CXCursor_ObjCProtocolExpr:
3240 return createCXString("ObjCProtocolExpr");
3241 case CXCursor_ObjCBridgedCastExpr:
3242 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003243 case CXCursor_BlockExpr:
3244 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003245 case CXCursor_PackExpansionExpr:
3246 return createCXString("PackExpansionExpr");
3247 case CXCursor_SizeOfPackExpr:
3248 return createCXString("SizeOfPackExpr");
3249 case CXCursor_UnexposedExpr:
3250 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003251 case CXCursor_DeclRefExpr:
3252 return createCXString("DeclRefExpr");
3253 case CXCursor_MemberRefExpr:
3254 return createCXString("MemberRefExpr");
3255 case CXCursor_CallExpr:
3256 return createCXString("CallExpr");
3257 case CXCursor_ObjCMessageExpr:
3258 return createCXString("ObjCMessageExpr");
3259 case CXCursor_UnexposedStmt:
3260 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003261 case CXCursor_DeclStmt:
3262 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003263 case CXCursor_LabelStmt:
3264 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003265 case CXCursor_CompoundStmt:
3266 return createCXString("CompoundStmt");
3267 case CXCursor_CaseStmt:
3268 return createCXString("CaseStmt");
3269 case CXCursor_DefaultStmt:
3270 return createCXString("DefaultStmt");
3271 case CXCursor_IfStmt:
3272 return createCXString("IfStmt");
3273 case CXCursor_SwitchStmt:
3274 return createCXString("SwitchStmt");
3275 case CXCursor_WhileStmt:
3276 return createCXString("WhileStmt");
3277 case CXCursor_DoStmt:
3278 return createCXString("DoStmt");
3279 case CXCursor_ForStmt:
3280 return createCXString("ForStmt");
3281 case CXCursor_GotoStmt:
3282 return createCXString("GotoStmt");
3283 case CXCursor_IndirectGotoStmt:
3284 return createCXString("IndirectGotoStmt");
3285 case CXCursor_ContinueStmt:
3286 return createCXString("ContinueStmt");
3287 case CXCursor_BreakStmt:
3288 return createCXString("BreakStmt");
3289 case CXCursor_ReturnStmt:
3290 return createCXString("ReturnStmt");
3291 case CXCursor_AsmStmt:
3292 return createCXString("AsmStmt");
3293 case CXCursor_ObjCAtTryStmt:
3294 return createCXString("ObjCAtTryStmt");
3295 case CXCursor_ObjCAtCatchStmt:
3296 return createCXString("ObjCAtCatchStmt");
3297 case CXCursor_ObjCAtFinallyStmt:
3298 return createCXString("ObjCAtFinallyStmt");
3299 case CXCursor_ObjCAtThrowStmt:
3300 return createCXString("ObjCAtThrowStmt");
3301 case CXCursor_ObjCAtSynchronizedStmt:
3302 return createCXString("ObjCAtSynchronizedStmt");
3303 case CXCursor_ObjCAutoreleasePoolStmt:
3304 return createCXString("ObjCAutoreleasePoolStmt");
3305 case CXCursor_ObjCForCollectionStmt:
3306 return createCXString("ObjCForCollectionStmt");
3307 case CXCursor_CXXCatchStmt:
3308 return createCXString("CXXCatchStmt");
3309 case CXCursor_CXXTryStmt:
3310 return createCXString("CXXTryStmt");
3311 case CXCursor_CXXForRangeStmt:
3312 return createCXString("CXXForRangeStmt");
3313 case CXCursor_SEHTryStmt:
3314 return createCXString("SEHTryStmt");
3315 case CXCursor_SEHExceptStmt:
3316 return createCXString("SEHExceptStmt");
3317 case CXCursor_SEHFinallyStmt:
3318 return createCXString("SEHFinallyStmt");
3319 case CXCursor_NullStmt:
3320 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003321 case CXCursor_InvalidFile:
3322 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003323 case CXCursor_InvalidCode:
3324 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003325 case CXCursor_NoDeclFound:
3326 return createCXString("NoDeclFound");
3327 case CXCursor_NotImplemented:
3328 return createCXString("NotImplemented");
3329 case CXCursor_TranslationUnit:
3330 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003331 case CXCursor_UnexposedAttr:
3332 return createCXString("UnexposedAttr");
3333 case CXCursor_IBActionAttr:
3334 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003335 case CXCursor_IBOutletAttr:
3336 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003337 case CXCursor_IBOutletCollectionAttr:
3338 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003339 case CXCursor_CXXFinalAttr:
3340 return createCXString("attribute(final)");
3341 case CXCursor_CXXOverrideAttr:
3342 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003343 case CXCursor_AnnotateAttr:
3344 return createCXString("attribute(annotate)");
Argyrios Kyrtzidis84b79642011-12-06 22:05:01 +00003345 case CXCursor_AsmLabelAttr:
3346 return createCXString("asm label");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003347 case CXCursor_PreprocessingDirective:
3348 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003349 case CXCursor_MacroDefinition:
3350 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003351 case CXCursor_MacroExpansion:
3352 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003353 case CXCursor_InclusionDirective:
3354 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003355 case CXCursor_Namespace:
3356 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003357 case CXCursor_LinkageSpec:
3358 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003359 case CXCursor_CXXBaseSpecifier:
3360 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003361 case CXCursor_Constructor:
3362 return createCXString("CXXConstructor");
3363 case CXCursor_Destructor:
3364 return createCXString("CXXDestructor");
3365 case CXCursor_ConversionFunction:
3366 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003367 case CXCursor_TemplateTypeParameter:
3368 return createCXString("TemplateTypeParameter");
3369 case CXCursor_NonTypeTemplateParameter:
3370 return createCXString("NonTypeTemplateParameter");
3371 case CXCursor_TemplateTemplateParameter:
3372 return createCXString("TemplateTemplateParameter");
3373 case CXCursor_FunctionTemplate:
3374 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003375 case CXCursor_ClassTemplate:
3376 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003377 case CXCursor_ClassTemplatePartialSpecialization:
3378 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003379 case CXCursor_NamespaceAlias:
3380 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003381 case CXCursor_UsingDirective:
3382 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003383 case CXCursor_UsingDeclaration:
3384 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003385 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003386 return createCXString("TypeAliasDecl");
3387 case CXCursor_ObjCSynthesizeDecl:
3388 return createCXString("ObjCSynthesizeDecl");
3389 case CXCursor_ObjCDynamicDecl:
3390 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003391 case CXCursor_CXXAccessSpecifier:
3392 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003393 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003394
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003395 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003396 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003397}
Steve Naroff89922f82009-08-31 00:59:03 +00003398
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003399struct GetCursorData {
3400 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003401 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003402 CXCursor &BestCursor;
3403
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003404 GetCursorData(SourceManager &SM,
3405 SourceLocation tokenBegin, CXCursor &outputCursor)
3406 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3407 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3408 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003409};
3410
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003411static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3412 CXCursor parent,
3413 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003414 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3415 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003416
3417 // If we point inside a macro argument we should provide info of what the
3418 // token is so use the actual cursor, don't replace it with a macro expansion
3419 // cursor.
3420 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3421 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003422
3423 if (clang_isDeclaration(cursor.kind)) {
3424 // Avoid having the implicit methods override the property decls.
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003425 if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003426 if (MD->isImplicit())
3427 return CXChildVisit_Break;
3428 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003429
3430 if (clang_isExpression(cursor.kind) &&
3431 clang_isDeclaration(BestCursor->kind)) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003432 if (Decl *D = getCursorDecl(*BestCursor)) {
3433 // Avoid having the cursor of an expression replace the declaration cursor
3434 // when the expression source range overlaps the declaration range.
3435 // This can happen for C++ constructor expressions whose range generally
3436 // include the variable declaration, e.g.:
3437 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3438 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3439 D->getLocation() == Data->TokenBeginLoc)
3440 return CXChildVisit_Break;
3441 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003442 }
3443
Douglas Gregor93798e22010-11-05 21:11:19 +00003444 // If our current best cursor is the construction of a temporary object,
3445 // don't replace that cursor with a type reference, because we want
3446 // clang_getCursor() to point at the constructor.
3447 if (clang_isExpression(BestCursor->kind) &&
3448 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003449 cursor.kind == CXCursor_TypeRef) {
3450 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3451 // as having the actual point on the type reference.
3452 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003453 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003454 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003455
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003456 *BestCursor = cursor;
3457 return CXChildVisit_Recurse;
3458}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003459
Douglas Gregorb9790342010-01-22 21:44:22 +00003460CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3461 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003462 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003463
Ted Kremeneka60ed472010-11-16 08:15:36 +00003464 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003465 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3466
Ted Kremeneka297de22010-01-25 22:34:44 +00003467 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003468 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003469
Douglas Gregor40749ee2010-11-03 00:35:38 +00003470 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003471 if (Logging) {
3472 CXFile SearchFile;
3473 unsigned SearchLine, SearchColumn;
3474 CXFile ResultFile;
3475 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003476 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3477 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003478 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3479
Chandler Carruth20174222011-08-31 16:53:37 +00003480 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3481 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3482 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003483 SearchFileName = clang_getFileName(SearchFile);
3484 ResultFileName = clang_getFileName(ResultFile);
3485 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003486 USR = clang_getCursorUSR(Result);
3487 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003488 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3489 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003490 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3491 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003492 clang_disposeString(SearchFileName);
3493 clang_disposeString(ResultFileName);
3494 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003495 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003496
3497 CXCursor Definition = clang_getCursorDefinition(Result);
3498 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3499 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3500 CXString DefinitionKindSpelling
3501 = clang_getCursorKindSpelling(Definition.kind);
3502 CXFile DefinitionFile;
3503 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003504 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3505 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003506 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3507 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3508 clang_getCString(DefinitionKindSpelling),
3509 clang_getCString(DefinitionFileName),
3510 DefinitionLine, DefinitionColumn);
3511 clang_disposeString(DefinitionFileName);
3512 clang_disposeString(DefinitionKindSpelling);
3513 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003514 }
3515
Ted Kremeneke68fff62010-02-17 00:41:32 +00003516 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003517}
3518
Ted Kremenek73885552009-11-17 19:28:59 +00003519CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003520 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003521}
3522
3523unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003524 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003525}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003526
Douglas Gregor9ce55842010-11-20 00:09:34 +00003527unsigned clang_hashCursor(CXCursor C) {
3528 unsigned Index = 0;
3529 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3530 Index = 1;
3531
3532 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3533 std::make_pair(C.kind, C.data[Index]));
3534}
3535
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003536unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003537 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3538}
3539
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003540unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003541 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3542}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003543
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003544unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003545 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3546}
3547
Douglas Gregor97b98722010-01-19 23:20:36 +00003548unsigned clang_isExpression(enum CXCursorKind K) {
3549 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3550}
3551
3552unsigned clang_isStatement(enum CXCursorKind K) {
3553 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3554}
3555
Douglas Gregor8be80e12011-07-06 03:00:34 +00003556unsigned clang_isAttribute(enum CXCursorKind K) {
3557 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3558}
3559
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003560unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3561 return K == CXCursor_TranslationUnit;
3562}
3563
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003564unsigned clang_isPreprocessing(enum CXCursorKind K) {
3565 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3566}
3567
Ted Kremenekad6eff62010-03-08 21:17:29 +00003568unsigned clang_isUnexposed(enum CXCursorKind K) {
3569 switch (K) {
3570 case CXCursor_UnexposedDecl:
3571 case CXCursor_UnexposedExpr:
3572 case CXCursor_UnexposedStmt:
3573 case CXCursor_UnexposedAttr:
3574 return true;
3575 default:
3576 return false;
3577 }
3578}
3579
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003580CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003581 return C.kind;
3582}
3583
Douglas Gregor98258af2010-01-18 22:46:11 +00003584CXSourceLocation clang_getCursorLocation(CXCursor C) {
3585 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003586 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003587 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003588 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3589 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003590 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003591 }
3592
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003593 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003594 std::pair<ObjCProtocolDecl *, SourceLocation> P
3595 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003596 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003597 }
3598
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003599 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003600 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3601 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003602 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003603 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003604
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003605 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003606 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003607 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003608 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003609
3610 case CXCursor_TemplateRef: {
3611 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3612 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3613 }
3614
Douglas Gregor69319002010-08-31 23:48:11 +00003615 case CXCursor_NamespaceRef: {
3616 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3617 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3618 }
3619
Douglas Gregora67e03f2010-09-09 21:42:20 +00003620 case CXCursor_MemberRef: {
3621 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3622 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3623 }
3624
Ted Kremenek3064ef92010-08-27 21:34:58 +00003625 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003626 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3627 if (!BaseSpec)
3628 return clang_getNullLocation();
3629
3630 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3631 return cxloc::translateSourceLocation(getCursorContext(C),
3632 TSInfo->getTypeLoc().getBeginLoc());
3633
3634 return cxloc::translateSourceLocation(getCursorContext(C),
3635 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003636 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003637
Douglas Gregor36897b02010-09-10 00:22:18 +00003638 case CXCursor_LabelRef: {
3639 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3640 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3641 }
3642
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003643 case CXCursor_OverloadedDeclRef:
3644 return cxloc::translateSourceLocation(getCursorContext(C),
3645 getCursorOverloadedDeclRef(C).second);
3646
Douglas Gregorf46034a2010-01-18 23:41:10 +00003647 default:
3648 // FIXME: Need a way to enumerate all non-reference cases.
3649 llvm_unreachable("Missed a reference kind");
3650 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003651 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003652
3653 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003654 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003655 getLocationFromExpr(getCursorExpr(C)));
3656
Douglas Gregor36897b02010-09-10 00:22:18 +00003657 if (clang_isStatement(C.kind))
3658 return cxloc::translateSourceLocation(getCursorContext(C),
3659 getCursorStmt(C)->getLocStart());
3660
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003661 if (C.kind == CXCursor_PreprocessingDirective) {
3662 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3663 return cxloc::translateSourceLocation(getCursorContext(C), L);
3664 }
Douglas Gregor48072312010-03-18 15:23:44 +00003665
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003666 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003667 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003668 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003669 return cxloc::translateSourceLocation(getCursorContext(C), L);
3670 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003671
3672 if (C.kind == CXCursor_MacroDefinition) {
3673 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3674 return cxloc::translateSourceLocation(getCursorContext(C), L);
3675 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003676
3677 if (C.kind == CXCursor_InclusionDirective) {
3678 SourceLocation L
3679 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3680 return cxloc::translateSourceLocation(getCursorContext(C), L);
3681 }
3682
Ted Kremenek9a700d22010-05-12 06:16:13 +00003683 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003684 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003685
Douglas Gregorf46034a2010-01-18 23:41:10 +00003686 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003687 if (!D)
3688 return clang_getNullLocation();
3689
Douglas Gregorf46034a2010-01-18 23:41:10 +00003690 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003691 // FIXME: Multiple variables declared in a single declaration
3692 // currently lack the information needed to correctly determine their
3693 // ranges when accounting for the type-specifier. We use context
3694 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3695 // and if so, whether it is the first decl.
3696 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3697 if (!cxcursor::isFirstInDeclGroup(C))
3698 Loc = VD->getLocation();
3699 }
3700
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003701 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003702}
Douglas Gregora7bde202010-01-19 00:34:46 +00003703
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003704} // end extern "C"
3705
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003706CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3707 assert(TU);
3708
3709 // Guard against an invalid SourceLocation, or we may assert in one
3710 // of the following calls.
3711 if (SLoc.isInvalid())
3712 return clang_getNullCursor();
3713
3714 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3715
3716 // Translate the given source location to make it point at the beginning of
3717 // the token under the cursor.
3718 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3719 CXXUnit->getASTContext().getLangOptions());
3720
3721 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3722 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003723 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003724 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3725 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003726 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003727 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003728 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003729 }
3730
3731 return Result;
3732}
3733
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003734static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003735 if (clang_isReference(C.kind)) {
3736 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003737 case CXCursor_ObjCSuperClassRef:
3738 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003739
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003740 case CXCursor_ObjCProtocolRef:
3741 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003742
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003743 case CXCursor_ObjCClassRef:
3744 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003745
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003746 case CXCursor_TypeRef:
3747 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003748
3749 case CXCursor_TemplateRef:
3750 return getCursorTemplateRef(C).second;
3751
Douglas Gregor69319002010-08-31 23:48:11 +00003752 case CXCursor_NamespaceRef:
3753 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003754
3755 case CXCursor_MemberRef:
3756 return getCursorMemberRef(C).second;
3757
Ted Kremenek3064ef92010-08-27 21:34:58 +00003758 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003759 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003760
Douglas Gregor36897b02010-09-10 00:22:18 +00003761 case CXCursor_LabelRef:
3762 return getCursorLabelRef(C).second;
3763
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003764 case CXCursor_OverloadedDeclRef:
3765 return getCursorOverloadedDeclRef(C).second;
3766
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003767 default:
3768 // FIXME: Need a way to enumerate all non-reference cases.
3769 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003770 }
3771 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003772
3773 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003774 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003775
3776 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003777 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003778
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003779 if (clang_isAttribute(C.kind))
3780 return getCursorAttr(C)->getRange();
3781
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003782 if (C.kind == CXCursor_PreprocessingDirective)
3783 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003784
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003785 if (C.kind == CXCursor_MacroExpansion) {
3786 ASTUnit *TU = getCursorASTUnit(C);
3787 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3788 return TU->mapRangeFromPreamble(Range);
3789 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003790
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003791 if (C.kind == CXCursor_MacroDefinition) {
3792 ASTUnit *TU = getCursorASTUnit(C);
3793 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3794 return TU->mapRangeFromPreamble(Range);
3795 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003796
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003797 if (C.kind == CXCursor_InclusionDirective) {
3798 ASTUnit *TU = getCursorASTUnit(C);
3799 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3800 return TU->mapRangeFromPreamble(Range);
3801 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003802
Ted Kremenek007a7c92010-11-01 23:26:51 +00003803 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3804 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003805 if (!D)
3806 return SourceRange();
3807
Ted Kremenek007a7c92010-11-01 23:26:51 +00003808 SourceRange R = D->getSourceRange();
3809 // FIXME: Multiple variables declared in a single declaration
3810 // currently lack the information needed to correctly determine their
3811 // ranges when accounting for the type-specifier. We use context
3812 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3813 // and if so, whether it is the first decl.
3814 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3815 if (!cxcursor::isFirstInDeclGroup(C))
3816 R.setBegin(VD->getLocation());
3817 }
3818 return R;
3819 }
Douglas Gregor66537982010-11-17 17:14:07 +00003820 return SourceRange();
3821}
3822
3823/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3824/// the decl-specifier-seq for declarations.
3825static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3826 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3827 Decl *D = cxcursor::getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003828 if (!D)
3829 return SourceRange();
3830
Douglas Gregor66537982010-11-17 17:14:07 +00003831 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003832
Douglas Gregor2494dd02011-03-01 01:34:45 +00003833 // Adjust the start of the location for declarations preceded by
3834 // declaration specifiers.
3835 SourceLocation StartLoc;
3836 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3837 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3838 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3839 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3840 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3841 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3842 }
3843
3844 if (StartLoc.isValid() && R.getBegin().isValid() &&
3845 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3846 R.setBegin(StartLoc);
3847
3848 // FIXME: Multiple variables declared in a single declaration
3849 // currently lack the information needed to correctly determine their
3850 // ranges when accounting for the type-specifier. We use context
3851 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3852 // and if so, whether it is the first decl.
3853 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3854 if (!cxcursor::isFirstInDeclGroup(C))
3855 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003856 }
3857
3858 return R;
3859 }
3860
3861 return getRawCursorExtent(C);
3862}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003863
3864extern "C" {
3865
3866CXSourceRange clang_getCursorExtent(CXCursor C) {
3867 SourceRange R = getRawCursorExtent(C);
3868 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003869 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003870
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003871 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003872}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003873
3874CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003875 if (clang_isInvalid(C.kind))
3876 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003877
Ted Kremeneka60ed472010-11-16 08:15:36 +00003878 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003879 if (clang_isDeclaration(C.kind)) {
3880 Decl *D = getCursorDecl(C);
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00003881 if (!D)
3882 return clang_getNullCursor();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003883 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003884 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003885 if (ObjCForwardProtocolDecl *Protocols
3886 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003887 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003888 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003889 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3890 return MakeCXCursor(Property, tu);
3891
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003892 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003893 }
3894
Douglas Gregor97b98722010-01-19 23:20:36 +00003895 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003896 Expr *E = getCursorExpr(C);
3897 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003898 if (D) {
3899 CXCursor declCursor = MakeCXCursor(D, tu);
3900 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
3901 declCursor);
3902 return declCursor;
3903 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003904
3905 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003906 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003907
Douglas Gregor97b98722010-01-19 23:20:36 +00003908 return clang_getNullCursor();
3909 }
3910
Douglas Gregor36897b02010-09-10 00:22:18 +00003911 if (clang_isStatement(C.kind)) {
3912 Stmt *S = getCursorStmt(C);
3913 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003914 if (LabelDecl *label = Goto->getLabel())
3915 if (LabelStmt *labelS = label->getStmt())
3916 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003917
3918 return clang_getNullCursor();
3919 }
3920
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003921 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003922 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003923 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003924 }
3925
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003926 if (!clang_isReference(C.kind))
3927 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003928
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003929 switch (C.kind) {
3930 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003931 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003932
3933 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003934 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003935
Douglas Gregor7723fec2011-12-15 20:29:51 +00003936 case CXCursor_ObjCClassRef: {
3937 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3938 if (ObjCInterfaceDecl *Def = Class->getDefinition())
3939 return MakeCXCursor(Def, tu);
3940
3941 return MakeCXCursor(Class, tu);
3942 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003943
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003944 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003945 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003946
3947 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003948 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003949
Douglas Gregor69319002010-08-31 23:48:11 +00003950 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003951 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003952
Douglas Gregora67e03f2010-09-09 21:42:20 +00003953 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003954 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003955
Ted Kremenek3064ef92010-08-27 21:34:58 +00003956 case CXCursor_CXXBaseSpecifier: {
3957 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3958 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003959 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003960 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003961
Douglas Gregor36897b02010-09-10 00:22:18 +00003962 case CXCursor_LabelRef:
3963 // FIXME: We end up faking the "parent" declaration here because we
3964 // don't want to make CXCursor larger.
3965 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003966 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3967 .getTranslationUnitDecl(),
3968 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003969
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003970 case CXCursor_OverloadedDeclRef:
3971 return C;
3972
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003973 default:
3974 // We would prefer to enumerate all non-reference cursor kinds here.
3975 llvm_unreachable("Unhandled reference cursor kind");
3976 break;
3977 }
3978 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003979
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003980 return clang_getNullCursor();
3981}
3982
Douglas Gregorb6998662010-01-19 19:34:47 +00003983CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003984 if (clang_isInvalid(C.kind))
3985 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003986
Ted Kremeneka60ed472010-11-16 08:15:36 +00003987 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003988
Douglas Gregorb6998662010-01-19 19:34:47 +00003989 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003990 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003991 C = clang_getCursorReferenced(C);
3992 WasReference = true;
3993 }
3994
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003995 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003996 return clang_getCursorReferenced(C);
3997
Douglas Gregorb6998662010-01-19 19:34:47 +00003998 if (!clang_isDeclaration(C.kind))
3999 return clang_getNullCursor();
4000
4001 Decl *D = getCursorDecl(C);
4002 if (!D)
4003 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004004
Douglas Gregorb6998662010-01-19 19:34:47 +00004005 switch (D->getKind()) {
4006 // Declaration kinds that don't really separate the notions of
4007 // declaration and definition.
4008 case Decl::Namespace:
4009 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004010 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004011 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004012 case Decl::TemplateTypeParm:
4013 case Decl::EnumConstant:
4014 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004015 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004016 case Decl::ObjCIvar:
4017 case Decl::ObjCAtDefsField:
4018 case Decl::ImplicitParam:
4019 case Decl::ParmVar:
4020 case Decl::NonTypeTemplateParm:
4021 case Decl::TemplateTemplateParm:
4022 case Decl::ObjCCategoryImpl:
4023 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004024 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004025 case Decl::LinkageSpec:
4026 case Decl::ObjCPropertyImpl:
4027 case Decl::FileScopeAsm:
4028 case Decl::StaticAssert:
4029 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004030 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004031 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregor15de72c2011-12-02 23:23:56 +00004032 case Decl::Import:
Douglas Gregorb6998662010-01-19 19:34:47 +00004033 return C;
4034
4035 // Declaration kinds that don't make any sense here, but are
4036 // nonetheless harmless.
4037 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004038 break;
4039
4040 // Declaration kinds for which the definition is not resolvable.
4041 case Decl::UnresolvedUsingTypename:
4042 case Decl::UnresolvedUsingValue:
4043 break;
4044
4045 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004046 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004047 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004048
4049 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004050 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004051
4052 case Decl::Enum:
4053 case Decl::Record:
4054 case Decl::CXXRecord:
4055 case Decl::ClassTemplateSpecialization:
4056 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004057 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004058 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004059 return clang_getNullCursor();
4060
4061 case Decl::Function:
4062 case Decl::CXXMethod:
4063 case Decl::CXXConstructor:
4064 case Decl::CXXDestructor:
4065 case Decl::CXXConversion: {
4066 const FunctionDecl *Def = 0;
4067 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004068 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004069 return clang_getNullCursor();
4070 }
4071
4072 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004073 // Ask the variable if it has a definition.
4074 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004075 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004076 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004077 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004078
Douglas Gregorb6998662010-01-19 19:34:47 +00004079 case Decl::FunctionTemplate: {
4080 const FunctionDecl *Def = 0;
4081 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004083 return clang_getNullCursor();
4084 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004085
Douglas Gregorb6998662010-01-19 19:34:47 +00004086 case Decl::ClassTemplate: {
4087 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004088 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004089 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004090 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004091 return clang_getNullCursor();
4092 }
4093
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004094 case Decl::Using:
4095 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004096 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004097
4098 case Decl::UsingShadow:
4099 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004100 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004101 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004102
4103 case Decl::ObjCMethod: {
4104 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4105 if (Method->isThisDeclarationADefinition())
4106 return C;
4107
4108 // Dig out the method definition in the associated
4109 // @implementation, if we have it.
4110 // FIXME: The ASTs should make finding the definition easier.
4111 if (ObjCInterfaceDecl *Class
4112 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4113 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4114 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4115 Method->isInstanceMethod()))
4116 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004117 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004118
4119 return clang_getNullCursor();
4120 }
4121
4122 case Decl::ObjCCategory:
4123 if (ObjCCategoryImplDecl *Impl
4124 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004125 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004126 return clang_getNullCursor();
4127
4128 case Decl::ObjCProtocol:
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00004129 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4130 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004131 return clang_getNullCursor();
4132
Douglas Gregor375bb142011-12-27 22:43:10 +00004133 case Decl::ObjCInterface: {
Douglas Gregorb6998662010-01-19 19:34:47 +00004134 // There are two notions of a "definition" for an Objective-C
4135 // class: the interface and its implementation. When we resolved a
4136 // reference to an Objective-C class, produce the @interface as
4137 // the definition; when we were provided with the interface,
4138 // produce the @implementation as the definition.
Douglas Gregor375bb142011-12-27 22:43:10 +00004139 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Douglas Gregorb6998662010-01-19 19:34:47 +00004140 if (WasReference) {
Douglas Gregor375bb142011-12-27 22:43:10 +00004141 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004142 return MakeCXCursor(Def, TU);
Douglas Gregor375bb142011-12-27 22:43:10 +00004143 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004144 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004145 return clang_getNullCursor();
Douglas Gregor375bb142011-12-27 22:43:10 +00004146 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004147
Douglas Gregorb6998662010-01-19 19:34:47 +00004148 case Decl::ObjCProperty:
4149 // FIXME: We don't really know where to find the
4150 // ObjCPropertyImplDecls that implement this property.
4151 return clang_getNullCursor();
4152
4153 case Decl::ObjCCompatibleAlias:
4154 if (ObjCInterfaceDecl *Class
4155 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Douglas Gregor7723fec2011-12-15 20:29:51 +00004156 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4157 return MakeCXCursor(Def, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004158
Douglas Gregorb6998662010-01-19 19:34:47 +00004159 return clang_getNullCursor();
4160
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004161 case Decl::ObjCForwardProtocol:
4162 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004163 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004164
Douglas Gregorb6998662010-01-19 19:34:47 +00004165 case Decl::Friend:
4166 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004167 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004168 return clang_getNullCursor();
4169
4170 case Decl::FriendTemplate:
4171 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004172 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004173 return clang_getNullCursor();
4174 }
4175
4176 return clang_getNullCursor();
4177}
4178
4179unsigned clang_isCursorDefinition(CXCursor C) {
4180 if (!clang_isDeclaration(C.kind))
4181 return 0;
4182
4183 return clang_getCursorDefinition(C) == C;
4184}
4185
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004186CXCursor clang_getCanonicalCursor(CXCursor C) {
4187 if (!clang_isDeclaration(C.kind))
4188 return C;
4189
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004190 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004191 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4192 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4193 return MakeCXCursor(CatD, getCursorTU(C));
4194
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004195 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4196 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4197 return MakeCXCursor(IFD, getCursorTU(C));
4198
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004199 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004200 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004201
4202 return C;
4203}
4204
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004205unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004206 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004207 return 0;
4208
4209 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4210 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4211 return E->getNumDecls();
4212
4213 if (OverloadedTemplateStorage *S
4214 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4215 return S->size();
4216
4217 Decl *D = Storage.get<Decl*>();
4218 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004219 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004220 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4221 return Protocols->protocol_size();
4222
4223 return 0;
4224}
4225
4226CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004227 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004228 return clang_getNullCursor();
4229
4230 if (index >= clang_getNumOverloadedDecls(cursor))
4231 return clang_getNullCursor();
4232
Ted Kremeneka60ed472010-11-16 08:15:36 +00004233 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004234 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4235 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004236 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004237
4238 if (OverloadedTemplateStorage *S
4239 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004240 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004241
4242 Decl *D = Storage.get<Decl*>();
4243 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4244 // FIXME: This is, unfortunately, linear time.
4245 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4246 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004247 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004248 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004249 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004250 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004251
4252 return clang_getNullCursor();
4253}
4254
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004255void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004256 const char **startBuf,
4257 const char **endBuf,
4258 unsigned *startLine,
4259 unsigned *startColumn,
4260 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004261 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004262 assert(getCursorDecl(C) && "CXCursor has null decl");
4263 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004264 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4265 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004266
Steve Naroff4ade6d62009-09-23 17:52:52 +00004267 SourceManager &SM = FD->getASTContext().getSourceManager();
4268 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4269 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4270 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4271 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4272 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4273 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4274}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004275
Douglas Gregor430d7a12011-07-25 17:48:11 +00004276
4277CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4278 unsigned PieceIndex) {
4279 RefNamePieces Pieces;
4280
4281 switch (C.kind) {
4282 case CXCursor_MemberRefExpr:
4283 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4284 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4285 E->getQualifierLoc().getSourceRange());
4286 break;
4287
4288 case CXCursor_DeclRefExpr:
4289 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4290 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4291 E->getQualifierLoc().getSourceRange(),
4292 E->getExplicitTemplateArgsOpt());
4293 break;
4294
4295 case CXCursor_CallExpr:
4296 if (CXXOperatorCallExpr *OCE =
4297 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4298 Expr *Callee = OCE->getCallee();
4299 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4300 Callee = ICE->getSubExpr();
4301
4302 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4303 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4304 DRE->getQualifierLoc().getSourceRange());
4305 }
4306 break;
4307
4308 default:
4309 break;
4310 }
4311
4312 if (Pieces.empty()) {
4313 if (PieceIndex == 0)
4314 return clang_getCursorExtent(C);
4315 } else if (PieceIndex < Pieces.size()) {
4316 SourceRange R = Pieces[PieceIndex];
4317 if (R.isValid())
4318 return cxloc::translateSourceRange(getCursorContext(C), R);
4319 }
4320
4321 return clang_getNullRange();
4322}
4323
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004324void clang_enableStackTraces(void) {
4325 llvm::sys::PrintStackTraceOnErrorSignal();
4326}
4327
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004328void clang_executeOnThread(void (*fn)(void*), void *user_data,
4329 unsigned stack_size) {
4330 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4331}
4332
Ted Kremenekfb480492010-01-13 21:46:36 +00004333} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004334
Ted Kremenekfb480492010-01-13 21:46:36 +00004335//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004336// Token-based Operations.
4337//===----------------------------------------------------------------------===//
4338
4339/* CXToken layout:
4340 * int_data[0]: a CXTokenKind
4341 * int_data[1]: starting token location
4342 * int_data[2]: token length
4343 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004344 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004345 * otherwise unused.
4346 */
4347extern "C" {
4348
4349CXTokenKind clang_getTokenKind(CXToken CXTok) {
4350 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4351}
4352
4353CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4354 switch (clang_getTokenKind(CXTok)) {
4355 case CXToken_Identifier:
4356 case CXToken_Keyword:
4357 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004358 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4359 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004360
4361 case CXToken_Literal: {
4362 // We have stashed the starting pointer in the ptr_data field. Use it.
4363 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004364 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004365 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004366
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004367 case CXToken_Punctuation:
4368 case CXToken_Comment:
4369 break;
4370 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004371
4372 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004373 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004374 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004375 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004376 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004377
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004378 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4379 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004380 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004381 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004382 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004383 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4384 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004385 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004387 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004388}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004389
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004390CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004391 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004392 if (!CXXUnit)
4393 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004394
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004395 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4396 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4397}
4398
4399CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004400 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004401 if (!CXXUnit)
4402 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004403
4404 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004405 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4406}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004407
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004408static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4409 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004410 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4411 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004412 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004413 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004414 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004415
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004416 // Cannot tokenize across files.
4417 if (BeginLocInfo.first != EndLocInfo.first)
4418 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004419
4420 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004421 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004422 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004423 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004424 if (Invalid)
4425 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004426
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004427 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4428 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004429 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004430 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004431
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004432 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004433 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004434 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004435 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004436 do {
4437 // Lex the next token
4438 Lex.LexFromRawLexer(Tok);
4439 if (Tok.is(tok::eof))
4440 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004441
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004442 // Initialize the CXToken.
4443 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004444
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004445 // - Common fields
4446 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4447 CXTok.int_data[2] = Tok.getLength();
4448 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004449
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004450 // - Kind-specific fields
4451 if (Tok.isLiteral()) {
4452 CXTok.int_data[0] = CXToken_Literal;
4453 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004454 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004455 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004456 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004457 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004458
David Chisnall096428b2010-10-13 21:44:48 +00004459 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004460 CXTok.int_data[0] = CXToken_Keyword;
4461 }
4462 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004463 CXTok.int_data[0] = Tok.is(tok::identifier)
4464 ? CXToken_Identifier
4465 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004466 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004467 CXTok.ptr_data = II;
4468 } else if (Tok.is(tok::comment)) {
4469 CXTok.int_data[0] = CXToken_Comment;
4470 CXTok.ptr_data = 0;
4471 } else {
4472 CXTok.int_data[0] = CXToken_Punctuation;
4473 CXTok.ptr_data = 0;
4474 }
4475 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004476 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004477 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004478}
4479
4480void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4481 CXToken **Tokens, unsigned *NumTokens) {
4482 if (Tokens)
4483 *Tokens = 0;
4484 if (NumTokens)
4485 *NumTokens = 0;
4486
4487 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4488 if (!CXXUnit || !Tokens || !NumTokens)
4489 return;
4490
4491 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4492
4493 SourceRange R = cxloc::translateCXSourceRange(Range);
4494 if (R.isInvalid())
4495 return;
4496
4497 SmallVector<CXToken, 32> CXTokens;
4498 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004499
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004500 if (CXTokens.empty())
4501 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004502
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004503 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4504 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4505 *NumTokens = CXTokens.size();
4506}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004507
Ted Kremenek6db61092010-05-05 00:55:15 +00004508void clang_disposeTokens(CXTranslationUnit TU,
4509 CXToken *Tokens, unsigned NumTokens) {
4510 free(Tokens);
4511}
4512
4513} // end: extern "C"
4514
4515//===----------------------------------------------------------------------===//
4516// Token annotation APIs.
4517//===----------------------------------------------------------------------===//
4518
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004519typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004520static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4521 CXCursor parent,
4522 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004523namespace {
4524class AnnotateTokensWorker {
4525 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004526 CXToken *Tokens;
4527 CXCursor *Cursors;
4528 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004529 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004530 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004531 CursorVisitor AnnotateVis;
4532 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004533 bool HasContextSensitiveKeywords;
4534
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004535 bool MoreTokens() const { return TokIdx < NumTokens; }
4536 unsigned NextToken() const { return TokIdx; }
4537 void AdvanceToken() { ++TokIdx; }
4538 SourceLocation GetTokenLoc(unsigned tokI) {
4539 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4540 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004541 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004542 return Tokens[tokI].int_data[3] != 0;
4543 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004544 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004545 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4546 }
4547
4548 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004549 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4550 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004551
Ted Kremenek6db61092010-05-05 00:55:15 +00004552public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004553 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004554 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004555 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004556 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004557 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004558 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004559 AnnotateTokensVisitor, this,
4560 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004561 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004562 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004563 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4564 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004565
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004566 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004567 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004568 void AnnotateTokens();
Douglas Gregorf5251602011-03-08 17:10:18 +00004569
4570 /// \brief Determine whether the annotator saw any cursors that have
4571 /// context-sensitive keywords.
4572 bool hasContextSensitiveKeywords() const {
4573 return HasContextSensitiveKeywords;
4574 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004575};
4576}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004577
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004578void AnnotateTokensWorker::AnnotateTokens() {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004579 // Walk the AST within the region of interest, annotating tokens
4580 // along the way.
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004581 AnnotateVis.visitFileRegion();
Ted Kremenek11949cb2010-05-05 00:55:17 +00004582
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004583 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4584 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004585 if (Pos != Annotated.end() &&
4586 (clang_isInvalid(Cursors[I].kind) ||
4587 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004588 Cursors[I] = Pos->second;
4589 }
4590
4591 // Finish up annotating any tokens left.
4592 if (!MoreTokens())
4593 return;
4594
4595 const CXCursor &C = clang_getNullCursor();
4596 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
Argyrios Kyrtzidis03ee2dd2011-11-16 08:58:57 +00004597 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4598 continue;
4599
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004600 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4601 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004602 }
4603}
4604
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004605/// \brief It annotates and advances tokens with a cursor until the comparison
4606//// between the cursor location and the source range is the same as
4607/// \arg compResult.
4608///
4609/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4610/// Pass RangeOverlap to annotate tokens inside a range.
4611void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4612 RangeComparisonResult compResult,
4613 SourceRange range) {
4614 while (MoreTokens()) {
4615 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004616 if (isFunctionMacroToken(I))
4617 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004618
4619 SourceLocation TokLoc = GetTokenLoc(I);
4620 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4621 Cursors[I] = updateC;
4622 AdvanceToken();
4623 continue;
4624 }
4625 break;
4626 }
4627}
4628
4629/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004630void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4631 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004632 RangeComparisonResult compResult,
4633 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004634 assert(MoreTokens());
4635 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004636 "Should be called only for macro arg tokens");
4637
4638 // This works differently than annotateAndAdvanceTokens; because expanded
4639 // macro arguments can have arbitrary translation-unit source order, we do not
4640 // advance the token index one by one until a token fails the range test.
4641 // We only advance once past all of the macro arg tokens if all of them
4642 // pass the range test. If one of them fails we keep the token index pointing
4643 // at the start of the macro arg tokens so that the failing token will be
4644 // annotated by a subsequent annotation try.
4645
4646 bool atLeastOneCompFail = false;
4647
4648 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004649 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4650 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004651 if (TokLoc.isFileID())
4652 continue; // not macro arg token, it's parens or comma.
4653 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4654 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4655 Cursors[I] = updateC;
4656 } else
4657 atLeastOneCompFail = true;
4658 }
4659
4660 if (!atLeastOneCompFail)
4661 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4662}
4663
Ted Kremenek6db61092010-05-05 00:55:15 +00004664enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004665AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004666 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004667 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004668 if (cursorRange.isInvalid())
4669 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004670
4671 if (!HasContextSensitiveKeywords) {
4672 // Objective-C properties can have context-sensitive keywords.
4673 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4674 if (ObjCPropertyDecl *Property
4675 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4676 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4677 }
4678 // Objective-C methods can have context-sensitive keywords.
4679 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4680 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4681 if (ObjCMethodDecl *Method
4682 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4683 if (Method->getObjCDeclQualifier())
4684 HasContextSensitiveKeywords = true;
4685 else {
4686 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4687 PEnd = Method->param_end();
4688 P != PEnd; ++P) {
4689 if ((*P)->getObjCDeclQualifier()) {
4690 HasContextSensitiveKeywords = true;
4691 break;
4692 }
4693 }
4694 }
4695 }
4696 }
4697 // C++ methods can have context-sensitive keywords.
4698 else if (cursor.kind == CXCursor_CXXMethod) {
4699 if (CXXMethodDecl *Method
4700 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4701 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4702 HasContextSensitiveKeywords = true;
4703 }
4704 }
4705 // C++ classes can have context-sensitive keywords.
4706 else if (cursor.kind == CXCursor_StructDecl ||
4707 cursor.kind == CXCursor_ClassDecl ||
4708 cursor.kind == CXCursor_ClassTemplate ||
4709 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4710 if (Decl *D = getCursorDecl(cursor))
4711 if (D->hasAttr<FinalAttr>())
4712 HasContextSensitiveKeywords = true;
4713 }
4714 }
4715
Douglas Gregor4419b672010-10-21 06:10:04 +00004716 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004717 // For macro expansions, just note where the beginning of the macro
4718 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004719 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004720 Annotated[Loc.int_data] = cursor;
4721 return CXChildVisit_Recurse;
4722 }
4723
Douglas Gregor4419b672010-10-21 06:10:04 +00004724 // Items in the preprocessing record are kept separate from items in
4725 // declarations, so we keep a separate token index.
4726 unsigned SavedTokIdx = TokIdx;
4727 TokIdx = PreprocessingTokIdx;
4728
4729 // Skip tokens up until we catch up to the beginning of the preprocessing
4730 // entry.
4731 while (MoreTokens()) {
4732 const unsigned I = NextToken();
4733 SourceLocation TokLoc = GetTokenLoc(I);
4734 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4735 case RangeBefore:
4736 AdvanceToken();
4737 continue;
4738 case RangeAfter:
4739 case RangeOverlap:
4740 break;
4741 }
4742 break;
4743 }
4744
4745 // Look at all of the tokens within this range.
4746 while (MoreTokens()) {
4747 const unsigned I = NextToken();
4748 SourceLocation TokLoc = GetTokenLoc(I);
4749 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4750 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004751 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004752 case RangeAfter:
4753 break;
4754 case RangeOverlap:
4755 Cursors[I] = cursor;
4756 AdvanceToken();
4757 continue;
4758 }
4759 break;
4760 }
4761
4762 // Save the preprocessing token index; restore the non-preprocessing
4763 // token index.
4764 PreprocessingTokIdx = TokIdx;
4765 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004766 return CXChildVisit_Recurse;
4767 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004768
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004769 if (cursorRange.isInvalid())
4770 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004771
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004772 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4773
Ted Kremeneka333c662010-05-12 05:29:33 +00004774 // Adjust the annotated range based specific declarations.
4775 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4776 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004777 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004778
4779 SourceLocation StartLoc;
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004780 if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004781 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4782 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00004783 } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004784 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4785 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004786 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004787
4788 if (StartLoc.isValid() && L.isValid() &&
4789 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4790 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004791 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004792
Ted Kremenek3f404602010-08-14 01:14:06 +00004793 // If the location of the cursor occurs within a macro instantiation, record
4794 // the spelling location of the cursor in our annotation map. We can then
4795 // paper over the token labelings during a post-processing step to try and
4796 // get cursor mappings for tokens that are the *arguments* of a macro
4797 // instantiation.
4798 if (L.isMacroID()) {
4799 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4800 // Only invalidate the old annotation if it isn't part of a preprocessing
4801 // directive. Here we assume that the default construction of CXCursor
4802 // results in CXCursor.kind being an initialized value (i.e., 0). If
4803 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004804
Ted Kremenek3f404602010-08-14 01:14:06 +00004805 CXCursor &oldC = Annotated[rawEncoding];
4806 if (!clang_isPreprocessing(oldC.kind))
4807 oldC = cursor;
4808 }
4809
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004810 const enum CXCursorKind K = clang_getCursorKind(parent);
4811 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004812 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4813 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004814
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004815 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004816
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004817 // Avoid having the cursor of an expression "overwrite" the annotation of the
4818 // variable declaration that it belongs to.
4819 // This can happen for C++ constructor expressions whose range generally
4820 // include the variable declaration, e.g.:
4821 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4822 if (clang_isExpression(cursorK)) {
4823 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004824 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004825 const unsigned I = NextToken();
4826 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4827 E->getLocStart() == D->getLocation() &&
4828 E->getLocStart() == GetTokenLoc(I)) {
4829 Cursors[I] = updateC;
4830 AdvanceToken();
4831 }
4832 }
4833 }
4834
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004835 // Visit children to get their cursor information.
4836 const unsigned BeforeChildren = NextToken();
4837 VisitChildren(cursor);
4838 const unsigned AfterChildren = NextToken();
4839
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004840 // Scan the tokens that are at the end of the cursor, but are not captured
4841 // but the child cursors.
4842 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004843
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004844 // Scan the tokens that are at the beginning of the cursor, but are not
4845 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004846 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4847 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4848 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004849
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004850 Cursors[I] = cursor;
4851 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004852
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004853 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004854}
4855
Ted Kremenek6db61092010-05-05 00:55:15 +00004856static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4857 CXCursor parent,
4858 CXClientData client_data) {
4859 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4860}
4861
Ted Kremenek6628a612011-03-18 22:51:30 +00004862namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004863
4864/// \brief Uses the macro expansions in the preprocessing record to find
4865/// and mark tokens that are macro arguments. This info is used by the
4866/// AnnotateTokensWorker.
4867class MarkMacroArgTokensVisitor {
4868 SourceManager &SM;
4869 CXToken *Tokens;
4870 unsigned NumTokens;
4871 unsigned CurIdx;
4872
4873public:
4874 MarkMacroArgTokensVisitor(SourceManager &SM,
4875 CXToken *tokens, unsigned numTokens)
4876 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4877
4878 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4879 if (cursor.kind != CXCursor_MacroExpansion)
4880 return CXChildVisit_Continue;
4881
4882 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4883 if (macroRange.getBegin() == macroRange.getEnd())
4884 return CXChildVisit_Continue; // it's not a function macro.
4885
4886 for (; CurIdx < NumTokens; ++CurIdx) {
4887 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4888 macroRange.getBegin()))
4889 break;
4890 }
4891
4892 if (CurIdx == NumTokens)
4893 return CXChildVisit_Break;
4894
4895 for (; CurIdx < NumTokens; ++CurIdx) {
4896 SourceLocation tokLoc = getTokenLoc(CurIdx);
4897 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4898 break;
4899
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004900 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004901 }
4902
4903 if (CurIdx == NumTokens)
4904 return CXChildVisit_Break;
4905
4906 return CXChildVisit_Continue;
4907 }
4908
4909private:
4910 SourceLocation getTokenLoc(unsigned tokI) {
4911 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4912 }
4913
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004914 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004915 // The third field is reserved and currently not used. Use it here
4916 // to mark macro arg expanded tokens with their expanded locations.
4917 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4918 }
4919};
4920
4921} // end anonymous namespace
4922
4923static CXChildVisitResult
4924MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4925 CXClientData client_data) {
4926 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4927 parent);
4928}
4929
4930namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004931 struct clang_annotateTokens_Data {
4932 CXTranslationUnit TU;
4933 ASTUnit *CXXUnit;
4934 CXToken *Tokens;
4935 unsigned NumTokens;
4936 CXCursor *Cursors;
4937 };
4938}
4939
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004940static void annotatePreprocessorTokens(CXTranslationUnit TU,
4941 SourceRange RegionOfInterest,
4942 AnnotateTokensData &Annotated) {
4943 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4944
4945 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4946 std::pair<FileID, unsigned> BeginLocInfo
4947 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4948 std::pair<FileID, unsigned> EndLocInfo
4949 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4950
4951 if (BeginLocInfo.first != EndLocInfo.first)
4952 return;
4953
4954 StringRef Buffer;
4955 bool Invalid = false;
4956 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4957 if (Buffer.empty() || Invalid)
4958 return;
4959
4960 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4961 CXXUnit->getASTContext().getLangOptions(),
4962 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4963 Buffer.end());
4964 Lex.SetCommentRetentionState(true);
4965
4966 // Lex tokens in raw mode until we hit the end of the range, to avoid
4967 // entering #includes or expanding macros.
4968 while (true) {
4969 Token Tok;
4970 Lex.LexFromRawLexer(Tok);
4971
4972 reprocess:
4973 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4974 // We have found a preprocessing directive. Gobble it up so that we
4975 // don't see it while preprocessing these tokens later, but keep track
4976 // of all of the token locations inside this preprocessing directive so
4977 // that we can annotate them appropriately.
4978 //
4979 // FIXME: Some simple tests here could identify macro definitions and
4980 // #undefs, to provide specific cursor kinds for those.
4981 SmallVector<SourceLocation, 32> Locations;
4982 do {
4983 Locations.push_back(Tok.getLocation());
4984 Lex.LexFromRawLexer(Tok);
4985 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4986
4987 using namespace cxcursor;
4988 CXCursor Cursor
4989 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4990 Locations.back()),
4991 TU);
4992 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4993 Annotated[Locations[I].getRawEncoding()] = Cursor;
4994 }
4995
4996 if (Tok.isAtStartOfLine())
4997 goto reprocess;
4998
4999 continue;
5000 }
5001
5002 if (Tok.is(tok::eof))
5003 break;
5004 }
5005}
5006
Ted Kremenekab979612010-11-11 08:05:23 +00005007// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005008static void clang_annotateTokensImpl(void *UserData) {
5009 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5010 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5011 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5012 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5013 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5014
5015 // Determine the region of interest, which contains all of the tokens.
5016 SourceRange RegionOfInterest;
5017 RegionOfInterest.setBegin(
5018 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5019 RegionOfInterest.setEnd(
5020 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5021 Tokens[NumTokens-1])));
5022
5023 // A mapping from the source locations found when re-lexing or traversing the
5024 // region of interest to the corresponding cursors.
5025 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005026
Ted Kremenek6628a612011-03-18 22:51:30 +00005027 // Relex the tokens within the source range to look for preprocessing
5028 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005029 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005030
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005031 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5032 // Search and mark tokens that are macro argument expansions.
5033 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5034 Tokens, NumTokens);
5035 CursorVisitor MacroArgMarker(TU,
5036 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005037 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005038 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005039 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005040 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5041 }
5042
Ted Kremenek6628a612011-03-18 22:51:30 +00005043 // Annotate all of the source locations in the region of interest that map to
5044 // a specific cursor.
5045 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5046 TU, RegionOfInterest);
5047
5048 // FIXME: We use a ridiculous stack size here because the data-recursion
5049 // algorithm uses a large stack frame than the non-data recursive version,
5050 // and AnnotationTokensWorker currently transforms the data-recursion
5051 // algorithm back into a traditional recursion by explicitly calling
5052 // VisitChildren(). We will need to remove this explicit recursive call.
5053 W.AnnotateTokens();
5054
5055 // If we ran into any entities that involve context-sensitive keywords,
5056 // take another pass through the tokens to mark them as such.
5057 if (W.hasContextSensitiveKeywords()) {
5058 for (unsigned I = 0; I != NumTokens; ++I) {
5059 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5060 continue;
5061
5062 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5063 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5064 if (ObjCPropertyDecl *Property
5065 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5066 if (Property->getPropertyAttributesAsWritten() != 0 &&
5067 llvm::StringSwitch<bool>(II->getName())
5068 .Case("readonly", true)
5069 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005070 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005071 .Case("readwrite", true)
5072 .Case("retain", true)
5073 .Case("copy", true)
5074 .Case("nonatomic", true)
5075 .Case("atomic", true)
5076 .Case("getter", true)
5077 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005078 .Case("strong", true)
5079 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005080 .Default(false))
5081 Tokens[I].int_data[0] = CXToken_Keyword;
5082 }
5083 continue;
5084 }
5085
5086 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5087 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5088 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5089 if (llvm::StringSwitch<bool>(II->getName())
5090 .Case("in", true)
5091 .Case("out", true)
5092 .Case("inout", true)
5093 .Case("oneway", true)
5094 .Case("bycopy", true)
5095 .Case("byref", true)
5096 .Default(false))
5097 Tokens[I].int_data[0] = CXToken_Keyword;
5098 continue;
5099 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005100
5101 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5102 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5103 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005104 continue;
5105 }
5106 }
5107 }
Ted Kremenekab979612010-11-11 08:05:23 +00005108}
5109
Ted Kremenek6db61092010-05-05 00:55:15 +00005110extern "C" {
5111
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005112void clang_annotateTokens(CXTranslationUnit TU,
5113 CXToken *Tokens, unsigned NumTokens,
5114 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005115
5116 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005117 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005118
Douglas Gregor4419b672010-10-21 06:10:04 +00005119 // Any token we don't specifically annotate will have a NULL cursor.
5120 CXCursor C = clang_getNullCursor();
5121 for (unsigned I = 0; I != NumTokens; ++I)
5122 Cursors[I] = C;
5123
Ted Kremeneka60ed472010-11-16 08:15:36 +00005124 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005125 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005126 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005127
Douglas Gregorbdf60622010-03-05 21:16:25 +00005128 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005129
5130 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005131 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005132 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005133 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005134 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5135 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005136}
Ted Kremenek6628a612011-03-18 22:51:30 +00005137
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005138} // end: extern "C"
5139
5140//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005141// Operations for querying linkage of a cursor.
5142//===----------------------------------------------------------------------===//
5143
5144extern "C" {
5145CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005146 if (!clang_isDeclaration(cursor.kind))
5147 return CXLinkage_Invalid;
5148
Ted Kremenek16b42592010-03-03 06:36:57 +00005149 Decl *D = cxcursor::getCursorDecl(cursor);
5150 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5151 switch (ND->getLinkage()) {
5152 case NoLinkage: return CXLinkage_NoLinkage;
5153 case InternalLinkage: return CXLinkage_Internal;
5154 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5155 case ExternalLinkage: return CXLinkage_External;
5156 };
5157
5158 return CXLinkage_Invalid;
5159}
5160} // end: extern "C"
5161
5162//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005163// Operations for querying language of a cursor.
5164//===----------------------------------------------------------------------===//
5165
5166static CXLanguageKind getDeclLanguage(const Decl *D) {
Argyrios Kyrtzidis16ed0e62011-12-10 02:36:25 +00005167 if (!D)
5168 return CXLanguage_C;
5169
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005170 switch (D->getKind()) {
5171 default:
5172 break;
5173 case Decl::ImplicitParam:
5174 case Decl::ObjCAtDefsField:
5175 case Decl::ObjCCategory:
5176 case Decl::ObjCCategoryImpl:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005177 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005178 case Decl::ObjCForwardProtocol:
5179 case Decl::ObjCImplementation:
5180 case Decl::ObjCInterface:
5181 case Decl::ObjCIvar:
5182 case Decl::ObjCMethod:
5183 case Decl::ObjCProperty:
5184 case Decl::ObjCPropertyImpl:
5185 case Decl::ObjCProtocol:
5186 return CXLanguage_ObjC;
5187 case Decl::CXXConstructor:
5188 case Decl::CXXConversion:
5189 case Decl::CXXDestructor:
5190 case Decl::CXXMethod:
5191 case Decl::CXXRecord:
5192 case Decl::ClassTemplate:
5193 case Decl::ClassTemplatePartialSpecialization:
5194 case Decl::ClassTemplateSpecialization:
5195 case Decl::Friend:
5196 case Decl::FriendTemplate:
5197 case Decl::FunctionTemplate:
5198 case Decl::LinkageSpec:
5199 case Decl::Namespace:
5200 case Decl::NamespaceAlias:
5201 case Decl::NonTypeTemplateParm:
5202 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005203 case Decl::TemplateTemplateParm:
5204 case Decl::TemplateTypeParm:
5205 case Decl::UnresolvedUsingTypename:
5206 case Decl::UnresolvedUsingValue:
5207 case Decl::Using:
5208 case Decl::UsingDirective:
5209 case Decl::UsingShadow:
5210 return CXLanguage_CPlusPlus;
5211 }
5212
5213 return CXLanguage_C;
5214}
5215
5216extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005217
5218enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5219 if (clang_isDeclaration(cursor.kind))
5220 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005221 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005222 return CXAvailability_Available;
5223
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005224 switch (D->getAvailability()) {
5225 case AR_Available:
5226 case AR_NotYetIntroduced:
5227 return CXAvailability_Available;
5228
5229 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005230 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005231
5232 case AR_Unavailable:
5233 return CXAvailability_NotAvailable;
5234 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005235 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005236
Douglas Gregor58ddb602010-08-23 23:00:57 +00005237 return CXAvailability_Available;
5238}
5239
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005240CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5241 if (clang_isDeclaration(cursor.kind))
5242 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5243
5244 return CXLanguage_Invalid;
5245}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005246
5247 /// \brief If the given cursor is the "templated" declaration
5248 /// descibing a class or function template, return the class or
5249 /// function template.
5250static Decl *maybeGetTemplateCursor(Decl *D) {
5251 if (!D)
5252 return 0;
5253
5254 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5255 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5256 return FunTmpl;
5257
5258 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5259 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5260 return ClassTmpl;
5261
5262 return D;
5263}
5264
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005265CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5266 if (clang_isDeclaration(cursor.kind)) {
5267 if (Decl *D = getCursorDecl(cursor)) {
5268 DeclContext *DC = D->getDeclContext();
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 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5278 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005279 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005280 }
5281
5282 return clang_getNullCursor();
5283}
5284
5285CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5286 if (clang_isDeclaration(cursor.kind)) {
5287 if (Decl *D = getCursorDecl(cursor)) {
5288 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005289 if (!DC)
5290 return clang_getNullCursor();
5291
5292 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5293 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005294 }
5295 }
5296
5297 // FIXME: Note that we can't easily compute the lexical context of a
5298 // statement or expression, so we return nothing.
5299 return clang_getNullCursor();
5300}
5301
Douglas Gregor9f592342010-10-01 20:25:15 +00005302void clang_getOverriddenCursors(CXCursor cursor,
5303 CXCursor **overridden,
5304 unsigned *num_overridden) {
5305 if (overridden)
5306 *overridden = 0;
5307 if (num_overridden)
5308 *num_overridden = 0;
5309 if (!overridden || !num_overridden)
5310 return;
5311
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005312 SmallVector<CXCursor, 8> Overridden;
5313 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005314
Ted Kremenek24077122011-11-14 23:51:37 +00005315 // Don't allocate memory if we have no overriden cursors.
5316 if (Overridden.size() == 0)
5317 return;
5318
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005319 *num_overridden = Overridden.size();
5320 *overridden = new CXCursor [Overridden.size()];
5321 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005322}
5323
5324void clang_disposeOverriddenCursors(CXCursor *overridden) {
5325 delete [] overridden;
5326}
5327
Douglas Gregorecdcb882010-10-20 22:00:55 +00005328CXFile clang_getIncludedFile(CXCursor cursor) {
5329 if (cursor.kind != CXCursor_InclusionDirective)
5330 return 0;
5331
5332 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5333 return (void *)ID->getFile();
5334}
5335
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005336} // end: extern "C"
5337
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005338
5339//===----------------------------------------------------------------------===//
5340// C++ AST instrospection.
5341//===----------------------------------------------------------------------===//
5342
5343extern "C" {
5344unsigned clang_CXXMethod_isStatic(CXCursor C) {
5345 if (!clang_isDeclaration(C.kind))
5346 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005347
5348 CXXMethodDecl *Method = 0;
5349 Decl *D = cxcursor::getCursorDecl(C);
5350 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5351 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5352 else
5353 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5354 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005355}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005356
Douglas Gregor211924b2011-05-12 15:17:24 +00005357unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5358 if (!clang_isDeclaration(C.kind))
5359 return 0;
5360
5361 CXXMethodDecl *Method = 0;
5362 Decl *D = cxcursor::getCursorDecl(C);
5363 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5364 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5365 else
5366 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5367 return (Method && Method->isVirtual()) ? 1 : 0;
5368}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005369} // end: extern "C"
5370
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005371//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005372// Attribute introspection.
5373//===----------------------------------------------------------------------===//
5374
5375extern "C" {
5376CXType clang_getIBOutletCollectionType(CXCursor C) {
5377 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005378 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005379
5380 IBOutletCollectionAttr *A =
5381 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5382
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005383 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005384}
5385} // end: extern "C"
5386
5387//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005388// Inspecting memory usage.
5389//===----------------------------------------------------------------------===//
5390
Ted Kremenekf7870022011-04-20 16:41:07 +00005391typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005392
Ted Kremenekf7870022011-04-20 16:41:07 +00005393static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5394 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005395 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005396 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005397 entries.push_back(entry);
5398}
5399
5400extern "C" {
5401
Ted Kremenekf7870022011-04-20 16:41:07 +00005402const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005403 const char *str = "";
5404 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005405 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005406 str = "ASTContext: expressions, declarations, and types";
5407 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005408 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005409 str = "ASTContext: identifiers";
5410 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005411 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005412 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005413 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005414 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005415 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005416 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005417 case CXTUResourceUsage_SourceManagerContentCache:
5418 str = "SourceManager: content cache allocator";
5419 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005420 case CXTUResourceUsage_AST_SideTables:
5421 str = "ASTContext: side tables";
5422 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005423 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5424 str = "SourceManager: malloc'ed memory buffers";
5425 break;
5426 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5427 str = "SourceManager: mmap'ed memory buffers";
5428 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005429 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5430 str = "ExternalASTSource: malloc'ed memory buffers";
5431 break;
5432 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5433 str = "ExternalASTSource: mmap'ed memory buffers";
5434 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005435 case CXTUResourceUsage_Preprocessor:
5436 str = "Preprocessor: malloc'ed memory";
5437 break;
5438 case CXTUResourceUsage_PreprocessingRecord:
5439 str = "Preprocessor: PreprocessingRecord";
5440 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005441 case CXTUResourceUsage_SourceManager_DataStructures:
5442 str = "SourceManager: data structures and tables";
5443 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005444 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5445 str = "Preprocessor: header search tables";
5446 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005447 }
5448 return str;
5449}
5450
Ted Kremenekf7870022011-04-20 16:41:07 +00005451CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005452 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005453 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005454 return usage;
5455 }
5456
5457 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5458 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5459 ASTContext &astContext = astUnit->getASTContext();
5460
5461 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005462 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005463 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005464
5465 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005466 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005467 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5468
5469 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005470 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005471 (unsigned long) astContext.Selectors.getTotalMemory());
5472
Ted Kremenekba29bd22011-04-28 04:53:38 +00005473 // How much memory is used by ASTContext's side tables?
5474 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5475 (unsigned long) astContext.getSideTableAllocatedMemory());
5476
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005477 // How much memory is used for caching global code completion results?
5478 unsigned long completionBytes = 0;
5479 if (GlobalCodeCompletionAllocator *completionAllocator =
5480 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005481 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005482 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005483 createCXTUResourceUsageEntry(*entries,
5484 CXTUResourceUsage_GlobalCompletionResults,
5485 completionBytes);
5486
5487 // How much memory is being used by SourceManager's content cache?
5488 createCXTUResourceUsageEntry(*entries,
5489 CXTUResourceUsage_SourceManagerContentCache,
5490 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005491
5492 // How much memory is being used by the MemoryBuffer's in SourceManager?
5493 const SourceManager::MemoryBufferSizes &srcBufs =
5494 astUnit->getSourceManager().getMemoryBufferSizes();
5495
5496 createCXTUResourceUsageEntry(*entries,
5497 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5498 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005499 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005500 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5501 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005502 createCXTUResourceUsageEntry(*entries,
5503 CXTUResourceUsage_SourceManager_DataStructures,
5504 (unsigned long) astContext.getSourceManager()
5505 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005506
5507 // How much memory is being used by the ExternalASTSource?
5508 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5509 const ExternalASTSource::MemoryBufferSizes &sizes =
5510 esrc->getMemoryBufferSizes();
5511
5512 createCXTUResourceUsageEntry(*entries,
5513 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5514 (unsigned long) sizes.malloc_bytes);
5515 createCXTUResourceUsageEntry(*entries,
5516 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5517 (unsigned long) sizes.mmap_bytes);
5518 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005519
5520 // How much memory is being used by the Preprocessor?
5521 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005522 createCXTUResourceUsageEntry(*entries,
5523 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005524 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005525
5526 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5527 createCXTUResourceUsageEntry(*entries,
5528 CXTUResourceUsage_PreprocessingRecord,
5529 pRec->getTotalMemory());
5530 }
5531
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005532 createCXTUResourceUsageEntry(*entries,
5533 CXTUResourceUsage_Preprocessor_HeaderSearch,
5534 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005535
Ted Kremenekf7870022011-04-20 16:41:07 +00005536 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005537 (unsigned) entries->size(),
5538 entries->size() ? &(*entries)[0] : 0 };
5539 entries.take();
5540 return usage;
5541}
5542
Ted Kremenekf7870022011-04-20 16:41:07 +00005543void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005544 if (usage.data)
5545 delete (MemUsageEntries*) usage.data;
5546}
5547
5548} // end extern "C"
5549
Douglas Gregor6df78732011-05-05 20:27:22 +00005550void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5551 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5552 for (unsigned I = 0; I != Usage.numEntries; ++I)
5553 fprintf(stderr, " %s: %lu\n",
5554 clang_getTUResourceUsageName(Usage.entries[I].kind),
5555 Usage.entries[I].amount);
5556
5557 clang_disposeCXTUResourceUsage(Usage);
5558}
5559
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005560//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005561// Misc. utility functions.
5562//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005563
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005564/// Default to using an 8 MB stack size on "safety" threads.
5565static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005566
5567namespace clang {
5568
5569bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005570 void (*Fn)(void*), void *UserData,
5571 unsigned Size) {
5572 if (!Size)
5573 Size = GetSafetyThreadStackSize();
5574 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005575 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5576 return CRC.RunSafely(Fn, UserData);
5577}
5578
5579unsigned GetSafetyThreadStackSize() {
5580 return SafetyStackThreadSize;
5581}
5582
5583void SetSafetyThreadStackSize(unsigned Value) {
5584 SafetyStackThreadSize = Value;
5585}
5586
5587}
5588
Ted Kremenek04bb7162010-01-22 22:44:15 +00005589extern "C" {
5590
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005591CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005592 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005593}
5594
5595} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005596