blob: 8deb85c99c21bbf9ac359673ef8c3ba409446951 [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"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000033#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000034#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000035#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000036#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000037#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000038#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000039#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000040#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000041#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000042#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000043#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000044#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000045#include "llvm/Support/Mutex.h"
46#include "llvm/Support/Program.h"
47#include "llvm/Support/Signals.h"
48#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000049#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000050
Steve Naroff50398192009-08-28 15:28:48 +000051using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000052using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000053using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000054using namespace clang::cxtu;
Steve Naroff50398192009-08-28 15:28:48 +000055
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000056CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000057 if (!TU)
58 return 0;
59 CXTranslationUnit D = new CXTranslationUnitImpl();
60 D->TUData = TU;
61 D->StringPool = createCXStringPool();
62 return D;
63}
64
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +000065cxtu::CXTUOwner::~CXTUOwner() {
66 if (TU)
67 clang_disposeTranslationUnit(TU);
68}
69
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070/// \brief The result of comparing two source ranges.
71enum RangeComparisonResult {
72 /// \brief Either the ranges overlap or one of the ranges is invalid.
73 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075 /// \brief The first range ends before the second range starts.
76 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000077
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 /// \brief The first range starts after the second range ends.
79 RangeAfter
80};
81
Ted Kremenekf0e23e82010-02-17 00:41:40 +000082/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000084static RangeComparisonResult RangeCompare(SourceManager &SM,
85 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 SourceRange R2) {
87 assert(R1.isValid() && "First range is invalid?");
88 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000089 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000090 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000091 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000092 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000093 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000094 return RangeAfter;
95 return RangeOverlap;
96}
97
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098/// \brief Determine if a source location falls within, before, or after a
99/// a given source range.
100static RangeComparisonResult LocationCompare(SourceManager &SM,
101 SourceLocation L, SourceRange R) {
102 assert(R.isValid() && "First range is invalid?");
103 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000104 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000105 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000106 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
107 return RangeBefore;
108 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
109 return RangeAfter;
110 return RangeOverlap;
111}
112
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000113/// \brief Translate a Clang source range into a CIndex source range.
114///
115/// Clang internally represents ranges where the end location points to the
116/// start of the token at the end. However, for external clients it is more
117/// useful to have a CXSourceRange be a proper half-open interval. This routine
118/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000119CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000120 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000121 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000122 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000123 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000124 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000125 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000126 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000127 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000128 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000129 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000130 }
131
132 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
133 R.getBegin().getRawEncoding(),
134 EndLoc.getRawEncoding() };
135 return Result;
136}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000137
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000138//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000139// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000140//===----------------------------------------------------------------------===//
141
Steve Naroff89922f82009-08-31 00:59:03 +0000142namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000143
144class VisitorJob {
145public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000146 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000147 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000148 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 ExplicitTemplateArgsVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000150 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000151 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000152 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000153protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000154 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000155 CXCursor parent;
156 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000157 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
158 : parent(C), K(k) {
159 data[0] = d1;
160 data[1] = d2;
161 data[2] = d3;
162 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000163public:
164 Kind getKind() const { return K; }
165 const CXCursor &getParent() const { return parent; }
166 static bool classof(VisitorJob *VJ) { return true; }
167};
168
Chris Lattner5f9e2722011-07-23 10:55:15 +0000169typedef SmallVector<VisitorJob, 10> VisitorWorkList;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000170
Douglas Gregorb1373d02010-01-20 20:59:29 +0000171// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000172class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000173 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000174{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000176 CXTranslationUnit TU;
177 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000179 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000180 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000181
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182 /// \brief The declaration that serves at the parent of any statement or
183 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000184 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000186 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000187 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000188
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000189 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000190 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000191
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000192 /// \brief Whether we should visit the preprocessing record entries last,
193 /// after visiting other declarations.
194 bool VisitPreprocessorLast;
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000195
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000196 /// \brief Whether we should visit declarations or preprocessing record
197 /// entries that are #included inside the \arg RegionOfInterest.
198 bool VisitIncludedEntities;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000199
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200 /// \brief When valid, a source range to which the cursor should restrict
201 /// its search.
202 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000203
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000204 // FIXME: Eventually remove. This part of a hack to support proper
205 // iteration over all Decls contained lexically within an ObjC container.
206 DeclContext::decl_iterator *DI_current;
207 DeclContext::decl_iterator DE_current;
208
Ted Kremenekd1ded662010-11-15 23:31:32 +0000209 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000210 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
211 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000212
Douglas Gregorb1373d02010-01-20 20:59:29 +0000213 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000214 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215
216 /// \brief Determine whether this particular source range comes before, comes
217 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000219 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
221
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000222 void visitDeclsFromFileRegion(FileID File, unsigned Offset, unsigned Length);
223
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000224 class SetParentRAII {
225 CXCursor &Parent;
226 Decl *&StmtParent;
227 CXCursor OldParent;
228
229 public:
230 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
231 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
232 {
233 Parent = NewParent;
234 if (clang_isDeclaration(Parent.kind))
235 StmtParent = getCursorDecl(Parent);
236 }
237
238 ~SetParentRAII() {
239 Parent = OldParent;
240 if (clang_isDeclaration(Parent.kind))
241 StmtParent = getCursorDecl(Parent);
242 }
243 };
244
Steve Naroff89922f82009-08-31 00:59:03 +0000245public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000246 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
247 CXClientData ClientData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000248 bool VisitPreprocessorLast,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000249 bool VisitIncludedPreprocessingEntries = false,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000250 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000251 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
252 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor08e0bc12011-09-10 00:09:20 +0000253 VisitPreprocessorLast(VisitPreprocessorLast),
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000254 VisitIncludedEntities(VisitIncludedPreprocessingEntries),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000255 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000256 {
257 Parent.kind = CXCursor_NoDeclFound;
258 Parent.data[0] = 0;
259 Parent.data[1] = 0;
260 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000261 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000262 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000263
Ted Kremenekd1ded662010-11-15 23:31:32 +0000264 ~CursorVisitor() {
265 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000266 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000267 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
268 delete *I;
269 }
270 }
271
Ted Kremeneka60ed472010-11-16 08:15:36 +0000272 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
273 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000274
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000275 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000276
277 /// \brief Visit declarations and preprocessed entities for the file region
278 /// designated by \see RegionOfInterest.
279 void visitFileRegion();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000280
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000281 bool visitPreprocessedEntitiesInRegion();
282
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000283 bool shouldVisitIncludedEntities() const {
284 return VisitIncludedEntities;
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000285 }
286
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000287 template<typename InputIterator>
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000288 bool visitPreprocessedEntities(InputIterator First, InputIterator Last,
289 PreprocessingRecord &PPRec,
290 FileID FID = FileID());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000291
Douglas Gregorb1373d02010-01-20 20:59:29 +0000292 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000293
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000294 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000295 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000296 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000297 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000298 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000299 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000300 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000301 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
302 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000303 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000304 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000305 bool VisitClassTemplatePartialSpecializationDecl(
306 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000307 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000308 bool VisitEnumConstantDecl(EnumConstantDecl *D);
309 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
310 bool VisitFunctionDecl(FunctionDecl *ND);
311 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000312 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000313 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000314 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000315 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000316 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000317 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
318 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
319 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
320 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000321 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000322 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
323 bool VisitObjCImplDecl(ObjCImplDecl *D);
324 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
325 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000326 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
327 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
328 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000329 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000330 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000331 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000332 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000333 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000334 bool VisitUsingDecl(UsingDecl *D);
335 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
336 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000337
Douglas Gregor01829d32010-08-31 14:41:23 +0000338 // Name visitor
339 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000340 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000341 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000342
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000343 // Template visitors
344 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000345 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000346 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
347
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000348 // Type visitors
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000349#define ABSTRACT_TYPELOC(CLASS, PARENT)
350#define TYPELOC(CLASS, PARENT) \
351 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
352#include "clang/AST/TypeLocNodes.def"
353
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000354 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000355 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000356 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
357
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000358 // Data-recursive visitor functions.
359 bool IsInRegionOfInterest(CXCursor C);
360 bool RunVisitorWorkList(VisitorWorkList &WL);
361 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000362 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000363};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000364
Ted Kremenekab188932010-01-05 19:32:54 +0000365} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000366
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000367static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000368static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
369
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000370
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000372 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000373}
374
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375/// \brief Visit the given cursor and, if requested by the visitor,
376/// its children.
377///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000378/// \param Cursor the cursor to visit.
379///
380/// \param CheckRegionOfInterest if true, then the caller already checked that
381/// this cursor is within the region of interest.
382///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383/// \returns true if the visitation should be aborted, false if it
384/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000386 if (clang_isInvalid(Cursor.kind))
387 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000388
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389 if (clang_isDeclaration(Cursor.kind)) {
390 Decl *D = getCursorDecl(Cursor);
391 assert(D && "Invalid declaration cursor");
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000392 // Ignore implicit declarations, unless it's an objc method because
393 // currently we should report implicit methods for properties when indexing.
394 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 return false;
396 }
397
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000398 // If we have a range of interest, and this cursor doesn't intersect with it,
399 // we're done.
400 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000401 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000402 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000403 return false;
404 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000405
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406 switch (Visitor(Cursor, Parent, ClientData)) {
407 case CXChildVisit_Break:
408 return true;
409
410 case CXChildVisit_Continue:
411 return false;
412
413 case CXChildVisit_Recurse:
414 return VisitChildren(Cursor);
415 }
416
Douglas Gregorfd643772010-01-25 16:45:46 +0000417 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418}
419
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000420static bool visitPreprocessedEntitiesInRange(SourceRange R,
421 PreprocessingRecord &PPRec,
422 CursorVisitor &Visitor) {
423 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
424 FileID FID;
425
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +0000426 if (!Visitor.shouldVisitIncludedEntities()) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000427 // If the begin/end of the range lie in the same FileID, do the optimization
428 // where we skip preprocessed entities that do not come from the same FileID.
429 FID = SM.getFileID(R.getBegin());
430 if (FID != SM.getFileID(R.getEnd()))
431 FID = FileID();
432 }
433
434 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
435 Entities = PPRec.getPreprocessedEntitiesInRange(R);
436 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
437 PPRec, FID);
438}
439
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000440void CursorVisitor::visitFileRegion() {
441 if (RegionOfInterest.isInvalid())
442 return;
443
444 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
445 SourceManager &SM = Unit->getSourceManager();
446
447 std::pair<FileID, unsigned>
448 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
449 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
450
451 if (End.first != Begin.first) {
452 // If the end does not reside in the same file, try to recover by
453 // picking the end of the file of begin location.
454 End.first = Begin.first;
455 End.second = SM.getFileIDSize(Begin.first);
456 }
457
458 assert(Begin.first == End.first);
459 if (Begin.second > End.second)
460 return;
461
462 FileID File = Begin.first;
463 unsigned Offset = Begin.second;
464 unsigned Length = End.second - Begin.second;
465
466 if (!VisitPreprocessorLast &&
467 Unit->getPreprocessor().getPreprocessingRecord())
468 visitPreprocessedEntitiesInRegion();
469
470 visitDeclsFromFileRegion(File, Offset, Length);
471
472 if (VisitPreprocessorLast &&
473 Unit->getPreprocessor().getPreprocessingRecord())
474 visitPreprocessedEntitiesInRegion();
475}
476
477void CursorVisitor::visitDeclsFromFileRegion(FileID File,
478 unsigned Offset, unsigned Length) {
479 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
480 SourceManager &SM = Unit->getSourceManager();
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000481 SourceRange Range = RegionOfInterest;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000482
483 SmallVector<Decl *, 16> Decls;
484 Unit->findFileRegionDecls(File, Offset, Length, Decls);
485
486 // If we didn't find any file level decls for the file, try looking at the
487 // file that it was included from.
488 while (Decls.empty()) {
489 bool Invalid = false;
490 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
491 if (Invalid)
492 return;
493
494 SourceLocation Outer;
495 if (SLEntry.isFile())
496 Outer = SLEntry.getFile().getIncludeLoc();
497 else
498 Outer = SLEntry.getExpansion().getExpansionLocStart();
499 if (Outer.isInvalid())
500 return;
501
502 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
503 Length = 0;
504 Unit->findFileRegionDecls(File, Offset, Length, Decls);
505 }
506
507 assert(!Decls.empty());
508
509 bool VisitedAtLeastOnce = false;
510 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
511 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
512 Decl *D = *DIt;
513
514 // We handle forward decls via ObjCClassDecl.
515 if (ObjCInterfaceDecl *InterD = dyn_cast<ObjCInterfaceDecl>(D)) {
516 if (InterD->isForwardDecl())
517 continue;
518 // An interface that started as a forward decl may have changed location
519 // because its @interface was parsed.
520 if (InterD->isInitiallyForwardDecl() &&
521 !SM.isInFileID(SM.getFileLoc(InterD->getLocation()), File))
522 continue;
523 }
524
525 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
526 if (CompRes == RangeBefore)
527 continue;
528 if (CompRes == RangeAfter)
529 break;
530
531 assert(CompRes == RangeOverlap);
532 VisitedAtLeastOnce = true;
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000533 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000534 break;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000535 }
536
537 if (VisitedAtLeastOnce)
538 return;
539
540 // No Decls overlapped with the range. Move up the lexical context until there
541 // is a context that contains the range or we reach the translation unit
542 // level.
543 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
544 : (*(DIt-1))->getLexicalDeclContext();
545
546 while (DC && !DC->isTranslationUnit()) {
547 Decl *D = cast<Decl>(DC);
548 SourceRange CurDeclRange = D->getSourceRange();
549 if (CurDeclRange.isInvalid())
550 break;
551
552 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidisba986172011-11-03 19:02:28 +0000553 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +0000554 break;
555 }
556
557 DC = D->getLexicalDeclContext();
558 }
559}
560
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000561bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000562 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000563 = *AU->getPreprocessor().getPreprocessingRecord();
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000564 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000565
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000566 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000567 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000568 SourceLocation B = MappedRange.getBegin();
569 SourceLocation E = MappedRange.getEnd();
570
571 if (AU->isInPreambleFileID(B)) {
572 if (SM.isLoadedSourceLocation(E))
573 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
574 PPRec, *this);
575
576 // Beginning of range lies in the preamble but it also extends beyond
577 // it into the main file. Split the range into 2 parts, one covering
578 // the preamble and another covering the main file. This allows subsequent
579 // calls to visitPreprocessedEntitiesInRange to accept a source range that
580 // lies in the same FileID, allowing it to skip preprocessed entities that
581 // do not come from the same FileID.
582 bool breaked =
583 visitPreprocessedEntitiesInRange(
584 SourceRange(B, AU->getEndOfPreambleFileID()),
585 PPRec, *this);
586 if (breaked) return true;
587 return visitPreprocessedEntitiesInRange(
588 SourceRange(AU->getStartOfMainFileID(), E),
589 PPRec, *this);
590 }
591
592 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000593 }
594
Douglas Gregor788f5a12010-03-20 00:41:21 +0000595 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000596 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
597
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000598 if (OnlyLocalDecls)
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000599 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
600 PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000601
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000602 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000603}
604
605template<typename InputIterator>
606bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000607 InputIterator Last,
608 PreprocessingRecord &PPRec,
609 FileID FID) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000610 for (; First != Last; ++First) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000611 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
612 continue;
613
614 PreprocessedEntity *PPE = *First;
615 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000616 if (Visit(MakeMacroExpansionCursor(ME, TU)))
617 return true;
618
619 continue;
620 }
621
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000622 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000623 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
624 return true;
625
626 continue;
627 }
628
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +0000629 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000630 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
631 return true;
632
633 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000634 }
635 }
636
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000637 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000638}
639
Douglas Gregorb1373d02010-01-20 20:59:29 +0000640/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000641///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000642/// \returns true if the visitation should be aborted, false if it
643/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000644bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000645 if (clang_isReference(Cursor.kind) &&
646 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000647 // By definition, references have no children.
648 return false;
649 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000650
651 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000652 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000653 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000654
Douglas Gregorb1373d02010-01-20 20:59:29 +0000655 if (clang_isDeclaration(Cursor.kind)) {
656 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000657 if (!D)
658 return false;
659
Ted Kremenek539311e2010-02-18 18:47:01 +0000660 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000661 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000662
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000663 if (clang_isStatement(Cursor.kind)) {
664 if (Stmt *S = getCursorStmt(Cursor))
665 return Visit(S);
666
667 return false;
668 }
669
670 if (clang_isExpression(Cursor.kind)) {
671 if (Expr *E = getCursorExpr(Cursor))
672 return Visit(E);
673
674 return false;
675 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000676
Douglas Gregorb1373d02010-01-20 20:59:29 +0000677 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000678 CXTranslationUnit tu = getCursorTU(Cursor);
679 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000680
681 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
682 for (unsigned I = 0; I != 2; ++I) {
683 if (VisitOrder[I]) {
684 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
685 RegionOfInterest.isInvalid()) {
686 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
687 TLEnd = CXXUnit->top_level_end();
688 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000689 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000690 return true;
691 }
692 } else if (VisitDeclContext(
693 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000694 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000695 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000696 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000697
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000698 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000699 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
700 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000701 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000702
Douglas Gregor7b691f332010-01-20 21:13:59 +0000703 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000704 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000705
Douglas Gregorc314aa42011-03-02 19:17:03 +0000706 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
707 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
708 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
709 return Visit(BaseTSInfo->getTypeLoc());
710 }
711 }
712 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000713
714 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
715 IBOutletCollectionAttr *A =
716 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
717 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
718 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
719 A->getInterfaceLoc(), TU));
720 }
721
Douglas Gregorb1373d02010-01-20 20:59:29 +0000722 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000723 return false;
724}
725
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000726bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000727 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
728 if (Visit(TSInfo->getTypeLoc()))
729 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000730
Ted Kremenek664cffd2010-07-22 11:30:19 +0000731 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000732 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000733
734 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000735}
736
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000737llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
738 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000739 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000740 if (Range.isInvalid())
741 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000742
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000743 switch (CompareRegionOfInterest(Range)) {
744 case RangeBefore:
745 // This declaration comes before the region of interest; skip it.
746 return llvm::Optional<bool>();
747
748 case RangeAfter:
749 // This declaration comes after the region of interest; we're done.
750 return false;
751
752 case RangeOverlap:
753 // This declaration overlaps the region of interest; visit it.
754 break;
755 }
756 }
757 return true;
758}
759
760bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
761 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
762
763 // FIXME: Eventually remove. This part of a hack to support proper
764 // iteration over all Decls contained lexically within an ObjC container.
765 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
766 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
767
768 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000769 Decl *D = *I;
770 if (D->getLexicalDeclContext() != DC)
771 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000772 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000773 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
774 if (!V.hasValue())
775 continue;
776 if (!V.getValue())
777 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000778 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000779 return true;
780 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000781 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000782}
783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
785 llvm_unreachable("Translation units are visited directly by Visit()");
786 return false;
787}
788
Richard Smith162e1c12011-04-15 14:24:37 +0000789bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
790 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
791 return Visit(TSInfo->getTypeLoc());
792
793 return false;
794}
795
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
797 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
798 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000799
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000800 return false;
801}
802
803bool CursorVisitor::VisitTagDecl(TagDecl *D) {
804 return VisitDeclContext(D);
805}
806
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000807bool CursorVisitor::VisitClassTemplateSpecializationDecl(
808 ClassTemplateSpecializationDecl *D) {
809 bool ShouldVisitBody = false;
810 switch (D->getSpecializationKind()) {
811 case TSK_Undeclared:
812 case TSK_ImplicitInstantiation:
813 // Nothing to visit
814 return false;
815
816 case TSK_ExplicitInstantiationDeclaration:
817 case TSK_ExplicitInstantiationDefinition:
818 break;
819
820 case TSK_ExplicitSpecialization:
821 ShouldVisitBody = true;
822 break;
823 }
824
825 // Visit the template arguments used in the specialization.
826 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
827 TypeLoc TL = SpecType->getTypeLoc();
828 if (TemplateSpecializationTypeLoc *TSTLoc
829 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
830 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
831 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
832 return true;
833 }
834 }
835
836 if (ShouldVisitBody && VisitCXXRecordDecl(D))
837 return true;
838
839 return false;
840}
841
Douglas Gregor74dbe642010-08-31 19:31:58 +0000842bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
843 ClassTemplatePartialSpecializationDecl *D) {
844 // FIXME: Visit the "outer" template parameter lists on the TagDecl
845 // before visiting these template parameters.
846 if (VisitTemplateParameters(D->getTemplateParameters()))
847 return true;
848
849 // Visit the partial specialization arguments.
850 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
851 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
852 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
853 return true;
854
855 return VisitCXXRecordDecl(D);
856}
857
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000858bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000859 // Visit the default argument.
860 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
861 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
862 if (Visit(DefArg->getTypeLoc()))
863 return true;
864
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000865 return false;
866}
867
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000868bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
869 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000870 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000871 return false;
872}
873
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000874bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
875 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
876 if (Visit(TSInfo->getTypeLoc()))
877 return true;
878
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000879 // Visit the nested-name-specifier, if present.
880 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
881 if (VisitNestedNameSpecifierLoc(QualifierLoc))
882 return true;
883
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000884 return false;
885}
886
Douglas Gregora67e03f2010-09-09 21:42:20 +0000887/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000888static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
889 CXXCtorInitializer const * const *X
890 = static_cast<CXXCtorInitializer const * const *>(Xp);
891 CXXCtorInitializer const * const *Y
892 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000893
894 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
895 return -1;
896 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
897 return 1;
898 else
899 return 0;
900}
901
Douglas Gregorb1373d02010-01-20 20:59:29 +0000902bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000903 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
904 // Visit the function declaration's syntactic components in the order
905 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000906 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000907 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
908
909 // If we have a function declared directly (without the use of a typedef),
910 // visit just the return type. Otherwise, just visit the function's type
911 // now.
912 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
913 (!FTL && Visit(TL)))
914 return true;
915
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000916 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000917 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
918 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000919 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000920
921 // Visit the declaration name.
922 if (VisitDeclarationNameInfo(ND->getNameInfo()))
923 return true;
924
925 // FIXME: Visit explicitly-specified template arguments!
926
927 // Visit the function parameters, if we have a function type.
928 if (FTL && VisitFunctionTypeLoc(*FTL, true))
929 return true;
930
931 // FIXME: Attributes?
932 }
933
Sean Hunt10620eb2011-05-06 20:44:56 +0000934 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000935 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
936 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000937 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000938 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
939 IEnd = Constructor->init_end();
940 I != IEnd; ++I) {
941 if (!(*I)->isWritten())
942 continue;
943
944 WrittenInits.push_back(*I);
945 }
946
947 // Sort the initializers in source order
948 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000949 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000950
951 // Visit the initializers in source order
952 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000953 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000954 if (Init->isAnyMemberInitializer()) {
955 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000956 Init->getMemberLocation(), TU)))
957 return true;
Douglas Gregor76852c22011-11-01 01:16:03 +0000958 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
959 if (Visit(TInfo->getTypeLoc()))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000960 return true;
961 }
962
963 // Visit the initializer value.
964 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000965 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000966 return true;
967 }
968 }
969
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000970 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000971 return true;
972 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000973
Douglas Gregorb1373d02010-01-20 20:59:29 +0000974 return false;
975}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000976
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000977bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
978 if (VisitDeclaratorDecl(D))
979 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000980
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000981 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000982 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000983
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000984 return false;
985}
986
987bool CursorVisitor::VisitVarDecl(VarDecl *D) {
988 if (VisitDeclaratorDecl(D))
989 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000991 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000992 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000994 return false;
995}
996
Douglas Gregor84b51d72010-09-01 20:16:53 +0000997bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
998 if (VisitDeclaratorDecl(D))
999 return true;
1000
1001 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
1002 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001003 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +00001004
1005 return false;
1006}
1007
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001008bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1009 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
1010 // before visiting these template parameters.
1011 if (VisitTemplateParameters(D->getTemplateParameters()))
1012 return true;
1013
1014 return VisitFunctionDecl(D->getTemplatedDecl());
1015}
1016
Douglas Gregor39d6f072010-08-31 19:02:00 +00001017bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1018 // FIXME: Visit the "outer" template parameter lists on the TagDecl
1019 // before visiting these template parameters.
1020 if (VisitTemplateParameters(D->getTemplateParameters()))
1021 return true;
1022
1023 return VisitCXXRecordDecl(D->getTemplatedDecl());
1024}
1025
Douglas Gregor84b51d72010-09-01 20:16:53 +00001026bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1027 if (VisitTemplateParameters(D->getTemplateParameters()))
1028 return true;
1029
1030 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
1031 VisitTemplateArgumentLoc(D->getDefaultArgument()))
1032 return true;
1033
1034 return false;
1035}
1036
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001037bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +00001038 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
1039 if (Visit(TSInfo->getTypeLoc()))
1040 return true;
1041
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043 PEnd = ND->param_end();
1044 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001045 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046 return true;
1047 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001049 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001050 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001051 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001053 return false;
1054}
1055
Ted Kremenekd8c370c2010-11-02 23:10:24 +00001056namespace {
1057 struct ContainerDeclsSort {
1058 SourceManager &SM;
1059 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
1060 bool operator()(Decl *A, Decl *B) {
1061 SourceLocation L_A = A->getLocStart();
1062 SourceLocation L_B = B->getLocStart();
1063 assert(L_A.isValid() && L_B.isValid());
1064 return SM.isBeforeInTranslationUnit(L_A, L_B);
1065 }
1066 };
1067}
1068
Douglas Gregora59e3902010-01-21 23:27:09 +00001069bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +00001070 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1071 // an @implementation can lexically contain Decls that are not properly
1072 // nested in the AST. When we identify such cases, we need to retrofit
1073 // this nesting here.
1074 if (!DI_current)
1075 return VisitDeclContext(D);
1076
1077 // Scan the Decls that immediately come after the container
1078 // in the current DeclContext. If any fall within the
1079 // container's lexical region, stash them into a vector
1080 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001081 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +00001082 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +00001083 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +00001084 if (EndLoc.isValid()) {
1085 DeclContext::decl_iterator next = *DI_current;
1086 while (++next != DE_current) {
1087 Decl *D_next = *next;
1088 if (!D_next)
1089 break;
1090 SourceLocation L = D_next->getLocStart();
1091 if (!L.isValid())
1092 break;
1093 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1094 *DI_current = next;
1095 DeclsInContainer.push_back(D_next);
1096 continue;
1097 }
1098 break;
1099 }
1100 }
1101
1102 // The common case.
1103 if (DeclsInContainer.empty())
1104 return VisitDeclContext(D);
1105
1106 // Get all the Decls in the DeclContext, and sort them with the
1107 // additional ones we've collected. Then visit them.
1108 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
1109 I!=E; ++I) {
1110 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +00001111 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
1112 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +00001113 continue;
1114 DeclsInContainer.push_back(subDecl);
1115 }
1116
1117 // Now sort the Decls so that they appear in lexical order.
1118 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1119 ContainerDeclsSort(SM));
1120
1121 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001122 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +00001123 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001124 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +00001125 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
1126 if (!V.hasValue())
1127 continue;
1128 if (!V.getValue())
1129 return false;
1130 if (Visit(Cursor, true))
1131 return true;
1132 }
1133 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001134}
1135
Douglas Gregorb1373d02010-01-20 20:59:29 +00001136bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001137 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1138 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001139 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001140
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001141 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1142 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1143 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001144 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001145 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001146
Douglas Gregora59e3902010-01-21 23:27:09 +00001147 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001148}
1149
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001150bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1151 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1152 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1153 E = PID->protocol_end(); I != E; ++I, ++PL)
1154 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1155 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001156
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001157 return VisitObjCContainerDecl(PID);
1158}
1159
Ted Kremenek23173d72010-05-18 21:09:07 +00001160bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001161 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001162 return true;
1163
Ted Kremenek23173d72010-05-18 21:09:07 +00001164 // FIXME: This implements a workaround with @property declarations also being
1165 // installed in the DeclContext for the @interface. Eventually this code
1166 // should be removed.
1167 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1168 if (!CDecl || !CDecl->IsClassExtension())
1169 return false;
1170
1171 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1172 if (!ID)
1173 return false;
1174
1175 IdentifierInfo *PropertyId = PD->getIdentifier();
1176 ObjCPropertyDecl *prevDecl =
1177 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1178
1179 if (!prevDecl)
1180 return false;
1181
1182 // Visit synthesized methods since they will be skipped when visiting
1183 // the @interface.
1184 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001185 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001186 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001187 return true;
1188
1189 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001190 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001191 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +00001192 return true;
1193
1194 return false;
1195}
1196
Douglas Gregorb1373d02010-01-20 20:59:29 +00001197bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001198 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001199 if (D->getSuperClass() &&
1200 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001201 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001202 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001203 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001204
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001205 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1206 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1207 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001208 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001209 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001210
Douglas Gregora59e3902010-01-21 23:27:09 +00001211 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001212}
1213
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001214bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1215 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001216}
1217
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001218bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001219 // 'ID' could be null when dealing with invalid code.
1220 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1221 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1222 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001223
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001224 return VisitObjCImplDecl(D);
1225}
1226
1227bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1228#if 0
1229 // Issue callbacks for super class.
1230 // FIXME: No source location information!
1231 if (D->getSuperClass() &&
1232 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001233 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001234 TU)))
1235 return true;
1236#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001237
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001238 return VisitObjCImplDecl(D);
1239}
1240
1241bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1242 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1243 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1244 E = D->protocol_end();
1245 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001246 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001247 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001248
1249 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001250}
1251
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001252bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001253 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1254 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001255 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001256 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001257}
1258
Douglas Gregora4ffd852010-11-17 01:03:52 +00001259bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1260 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1261 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1262
1263 return false;
1264}
1265
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001266bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1267 return VisitDeclContext(D);
1268}
1269
Douglas Gregor69319002010-08-31 23:48:11 +00001270bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001271 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001272 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1273 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001274 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001275
1276 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1277 D->getTargetNameLoc(), TU));
1278}
1279
Douglas Gregor7e242562010-09-01 19:52:22 +00001280bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001281 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001282 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1283 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001284 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001285 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001286
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001287 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1288 return true;
1289
Douglas Gregor7e242562010-09-01 19:52:22 +00001290 return VisitDeclarationNameInfo(D->getNameInfo());
1291}
1292
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001293bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001294 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001295 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1296 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001297 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001298
1299 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1300 D->getIdentLocation(), TU));
1301}
1302
Douglas Gregor7e242562010-09-01 19:52:22 +00001303bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001304 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001305 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1306 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001307 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001308 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001309
Douglas Gregor7e242562010-09-01 19:52:22 +00001310 return VisitDeclarationNameInfo(D->getNameInfo());
1311}
1312
1313bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1314 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001315 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001316 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1317 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001318 return true;
1319
Douglas Gregor7e242562010-09-01 19:52:22 +00001320 return false;
1321}
1322
Douglas Gregor01829d32010-08-31 14:41:23 +00001323bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1324 switch (Name.getName().getNameKind()) {
1325 case clang::DeclarationName::Identifier:
1326 case clang::DeclarationName::CXXLiteralOperatorName:
1327 case clang::DeclarationName::CXXOperatorName:
1328 case clang::DeclarationName::CXXUsingDirective:
1329 return false;
1330
1331 case clang::DeclarationName::CXXConstructorName:
1332 case clang::DeclarationName::CXXDestructorName:
1333 case clang::DeclarationName::CXXConversionFunctionName:
1334 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1335 return Visit(TSInfo->getTypeLoc());
1336 return false;
1337
1338 case clang::DeclarationName::ObjCZeroArgSelector:
1339 case clang::DeclarationName::ObjCOneArgSelector:
1340 case clang::DeclarationName::ObjCMultiArgSelector:
1341 // FIXME: Per-identifier location info?
1342 return false;
1343 }
1344
1345 return false;
1346}
1347
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001348bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1349 SourceRange Range) {
1350 // FIXME: This whole routine is a hack to work around the lack of proper
1351 // source information in nested-name-specifiers (PR5791). Since we do have
1352 // a beginning source location, we can visit the first component of the
1353 // nested-name-specifier, if it's a single-token component.
1354 if (!NNS)
1355 return false;
1356
1357 // Get the first component in the nested-name-specifier.
1358 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1359 NNS = Prefix;
1360
1361 switch (NNS->getKind()) {
1362 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001363 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1364 TU));
1365
Douglas Gregor14aba762011-02-24 02:36:08 +00001366 case NestedNameSpecifier::NamespaceAlias:
1367 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1368 Range.getBegin(), TU));
1369
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001370 case NestedNameSpecifier::TypeSpec: {
1371 // If the type has a form where we know that the beginning of the source
1372 // range matches up with a reference cursor. Visit the appropriate reference
1373 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001374 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001375 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1376 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1377 if (const TagType *Tag = dyn_cast<TagType>(T))
1378 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1379 if (const TemplateSpecializationType *TST
1380 = dyn_cast<TemplateSpecializationType>(T))
1381 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1382 break;
1383 }
1384
1385 case NestedNameSpecifier::TypeSpecWithTemplate:
1386 case NestedNameSpecifier::Global:
1387 case NestedNameSpecifier::Identifier:
1388 break;
1389 }
1390
1391 return false;
1392}
1393
Douglas Gregordc355712011-02-25 00:36:19 +00001394bool
1395CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001396 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001397 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1398 Qualifiers.push_back(Qualifier);
1399
1400 while (!Qualifiers.empty()) {
1401 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1402 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1403 switch (NNS->getKind()) {
1404 case NestedNameSpecifier::Namespace:
1405 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001406 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001407 TU)))
1408 return true;
1409
1410 break;
1411
1412 case NestedNameSpecifier::NamespaceAlias:
1413 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001414 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001415 TU)))
1416 return true;
1417
1418 break;
1419
1420 case NestedNameSpecifier::TypeSpec:
1421 case NestedNameSpecifier::TypeSpecWithTemplate:
1422 if (Visit(Q.getTypeLoc()))
1423 return true;
1424
1425 break;
1426
1427 case NestedNameSpecifier::Global:
1428 case NestedNameSpecifier::Identifier:
1429 break;
1430 }
1431 }
1432
1433 return false;
1434}
1435
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001436bool CursorVisitor::VisitTemplateParameters(
1437 const TemplateParameterList *Params) {
1438 if (!Params)
1439 return false;
1440
1441 for (TemplateParameterList::const_iterator P = Params->begin(),
1442 PEnd = Params->end();
1443 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001444 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001445 return true;
1446 }
1447
1448 return false;
1449}
1450
Douglas Gregor0b36e612010-08-31 20:37:03 +00001451bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1452 switch (Name.getKind()) {
1453 case TemplateName::Template:
1454 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1455
1456 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001457 // Visit the overloaded template set.
1458 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1459 return true;
1460
Douglas Gregor0b36e612010-08-31 20:37:03 +00001461 return false;
1462
1463 case TemplateName::DependentTemplate:
1464 // FIXME: Visit nested-name-specifier.
1465 return false;
1466
1467 case TemplateName::QualifiedTemplate:
1468 // FIXME: Visit nested-name-specifier.
1469 return Visit(MakeCursorTemplateRef(
1470 Name.getAsQualifiedTemplateName()->getDecl(),
1471 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001472
1473 case TemplateName::SubstTemplateTemplateParm:
1474 return Visit(MakeCursorTemplateRef(
1475 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1476 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001477
1478 case TemplateName::SubstTemplateTemplateParmPack:
1479 return Visit(MakeCursorTemplateRef(
1480 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1481 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001482 }
1483
1484 return false;
1485}
1486
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001487bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1488 switch (TAL.getArgument().getKind()) {
1489 case TemplateArgument::Null:
1490 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001491 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001492 return false;
1493
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001494 case TemplateArgument::Type:
1495 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1496 return Visit(TSInfo->getTypeLoc());
1497 return false;
1498
1499 case TemplateArgument::Declaration:
1500 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001501 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001502 return false;
1503
1504 case TemplateArgument::Expression:
1505 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001506 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001507 return false;
1508
1509 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001510 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001511 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1512 return true;
1513
Douglas Gregora7fc9012011-01-05 18:58:31 +00001514 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001515 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001516 }
1517
1518 return false;
1519}
1520
Ted Kremeneka0536d82010-05-07 01:04:29 +00001521bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1522 return VisitDeclContext(D);
1523}
1524
Douglas Gregor01829d32010-08-31 14:41:23 +00001525bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1526 return Visit(TL.getUnqualifiedLoc());
1527}
1528
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001529bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001530 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001531
1532 // Some builtin types (such as Objective-C's "id", "sel", and
1533 // "Class") have associated declarations. Create cursors for those.
1534 QualType VisitType;
John McCalle0a22d02011-10-18 21:02:43 +00001535 switch (TL.getTypePtr()->getKind()) {
John McCall2dde35b2011-10-18 22:28:37 +00001536
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001537 case BuiltinType::Void:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001538 case BuiltinType::NullPtr:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001539 case BuiltinType::Dependent:
John McCall2dde35b2011-10-18 22:28:37 +00001540#define BUILTIN_TYPE(Id, SingletonId)
1541#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1542#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1543#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1544#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1545#include "clang/AST/BuiltinTypes.def"
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001546 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001547
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001548 case BuiltinType::ObjCId:
1549 VisitType = Context.getObjCIdType();
1550 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001551
1552 case BuiltinType::ObjCClass:
1553 VisitType = Context.getObjCClassType();
1554 break;
1555
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001556 case BuiltinType::ObjCSel:
1557 VisitType = Context.getObjCSelType();
1558 break;
1559 }
1560
1561 if (!VisitType.isNull()) {
1562 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001563 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001564 TU));
1565 }
1566
1567 return false;
1568}
1569
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001570bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001571 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001572}
1573
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001574bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1575 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1576}
1577
1578bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001579 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001580 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001581
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001582 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1583}
1584
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001585bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001586 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001587}
1588
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001589bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1590 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1591 return true;
1592
John McCallc12c5bb2010-05-15 11:32:37 +00001593 return false;
1594}
1595
1596bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1597 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1598 return true;
1599
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001600 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1601 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1602 TU)))
1603 return true;
1604 }
1605
1606 return false;
1607}
1608
1609bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001610 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001611}
1612
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001613bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1614 return Visit(TL.getInnerLoc());
1615}
1616
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001617bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1618 return Visit(TL.getPointeeLoc());
1619}
1620
1621bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1622 return Visit(TL.getPointeeLoc());
1623}
1624
1625bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1626 return Visit(TL.getPointeeLoc());
1627}
1628
1629bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001630 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001631}
1632
1633bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001634 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001635}
1636
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001637bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1638 return Visit(TL.getModifiedLoc());
1639}
1640
Douglas Gregor01829d32010-08-31 14:41:23 +00001641bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1642 bool SkipResultType) {
1643 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001644 return true;
1645
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001646 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001647 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001648 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001649 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001650
1651 return false;
1652}
1653
1654bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1655 if (Visit(TL.getElementLoc()))
1656 return true;
1657
1658 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001659 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001660
1661 return false;
1662}
1663
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001664bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1665 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001666 // Visit the template name.
1667 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1668 TL.getTemplateNameLoc()))
1669 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001670
1671 // Visit the template arguments.
1672 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1673 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1674 return true;
1675
1676 return false;
1677}
1678
Douglas Gregor2332c112010-01-21 20:48:56 +00001679bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1680 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1681}
1682
1683bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1684 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1685 return Visit(TSInfo->getTypeLoc());
1686
1687 return false;
1688}
1689
Sean Huntca63c202011-05-24 22:41:36 +00001690bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1691 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1692 return Visit(TSInfo->getTypeLoc());
1693
1694 return false;
1695}
1696
Douglas Gregor2494dd02011-03-01 01:34:45 +00001697bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1698 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1699 return true;
1700
1701 return false;
1702}
1703
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001704bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1705 DependentTemplateSpecializationTypeLoc TL) {
1706 // Visit the nested-name-specifier, if there is one.
1707 if (TL.getQualifierLoc() &&
1708 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1709 return true;
1710
1711 // Visit the template arguments.
1712 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1713 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1714 return true;
1715
1716 return false;
1717}
1718
Douglas Gregor9e876872011-03-01 18:12:44 +00001719bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1720 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1721 return true;
1722
1723 return Visit(TL.getNamedTypeLoc());
1724}
1725
Douglas Gregor7536dd52010-12-20 02:24:11 +00001726bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1727 return Visit(TL.getPatternLoc());
1728}
1729
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001730bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1731 if (Expr *E = TL.getUnderlyingExpr())
1732 return Visit(MakeCXCursor(E, StmtParent, TU));
1733
1734 return false;
1735}
1736
1737bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1738 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1739}
1740
Eli Friedmanb001de72011-10-06 23:00:33 +00001741bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1742 return Visit(TL.getValueLoc());
1743}
1744
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001745#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1746bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1747 return Visit##PARENT##Loc(TL); \
1748}
1749
1750DEFAULT_TYPELOC_IMPL(Complex, Type)
1751DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1752DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1753DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1754DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1755DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1756DEFAULT_TYPELOC_IMPL(Vector, Type)
1757DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1758DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1759DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1760DEFAULT_TYPELOC_IMPL(Record, TagType)
1761DEFAULT_TYPELOC_IMPL(Enum, TagType)
1762DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1763DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1764DEFAULT_TYPELOC_IMPL(Auto, Type)
1765
Ted Kremenek3064ef92010-08-27 21:34:58 +00001766bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001767 // Visit the nested-name-specifier, if present.
1768 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1769 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1770 return true;
1771
John McCall5e1cdac2011-10-07 06:10:15 +00001772 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001773 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1774 E = D->bases_end(); I != E; ++I) {
1775 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1776 return true;
1777 }
1778 }
1779
1780 return VisitTagDecl(D);
1781}
1782
Ted Kremenek09dfa372010-02-18 05:46:33 +00001783bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001784 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1785 i != e; ++i)
1786 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001787 return true;
1788
1789 return false;
1790}
1791
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001792//===----------------------------------------------------------------------===//
1793// Data-recursive visitor methods.
1794//===----------------------------------------------------------------------===//
1795
Ted Kremenek28a71942010-11-13 00:36:47 +00001796namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001797#define DEF_JOB(NAME, DATA, KIND)\
1798class NAME : public VisitorJob {\
1799public:\
1800 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1801 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001802 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001803};
1804
1805DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1806DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001807DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001808DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001809DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001810 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001811DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001812#undef DEF_JOB
1813
1814class DeclVisit : public VisitorJob {
1815public:
1816 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1817 VisitorJob(parent, VisitorJob::DeclVisitKind,
1818 d, isFirst ? (void*) 1 : (void*) 0) {}
1819 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001820 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001821 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001822 Decl *get() const { return static_cast<Decl*>(data[0]); }
1823 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001824};
Ted Kremenek035dc412010-11-13 00:36:50 +00001825class TypeLocVisit : public VisitorJob {
1826public:
1827 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1828 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1829 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1830
1831 static bool classof(const VisitorJob *VJ) {
1832 return VJ->getKind() == TypeLocVisitKind;
1833 }
1834
Ted Kremenek82f3c502010-11-15 22:23:26 +00001835 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001836 QualType T = QualType::getFromOpaquePtr(data[0]);
1837 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001838 }
1839};
1840
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001841class LabelRefVisit : public VisitorJob {
1842public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001843 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1844 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001845 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001846
1847 static bool classof(const VisitorJob *VJ) {
1848 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1849 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001850 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001851 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001852 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001853};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001854
1855class NestedNameSpecifierLocVisit : public VisitorJob {
1856public:
1857 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1858 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1859 Qualifier.getNestedNameSpecifier(),
1860 Qualifier.getOpaqueData()) { }
1861
1862 static bool classof(const VisitorJob *VJ) {
1863 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1864 }
1865
1866 NestedNameSpecifierLoc get() const {
1867 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1868 data[1]);
1869 }
1870};
1871
Ted Kremenekf64d8032010-11-18 00:02:32 +00001872class DeclarationNameInfoVisit : public VisitorJob {
1873public:
1874 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1875 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1876 static bool classof(const VisitorJob *VJ) {
1877 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1878 }
1879 DeclarationNameInfo get() const {
1880 Stmt *S = static_cast<Stmt*>(data[0]);
1881 switch (S->getStmtClass()) {
1882 default:
1883 llvm_unreachable("Unhandled Stmt");
Douglas Gregorba0513d2011-10-25 01:33:02 +00001884 case clang::Stmt::MSDependentExistsStmtClass:
1885 return cast<MSDependentExistsStmt>(S)->getNameInfo();
Ted Kremenekf64d8032010-11-18 00:02:32 +00001886 case Stmt::CXXDependentScopeMemberExprClass:
1887 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1888 case Stmt::DependentScopeDeclRefExprClass:
1889 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1890 }
1891 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001892};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001893class MemberRefVisit : public VisitorJob {
1894public:
1895 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1896 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001897 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001898 static bool classof(const VisitorJob *VJ) {
1899 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1900 }
1901 FieldDecl *get() const {
1902 return static_cast<FieldDecl*>(data[0]);
1903 }
1904 SourceLocation getLoc() const {
1905 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1906 }
1907};
Ted Kremenek28a71942010-11-13 00:36:47 +00001908class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1909 VisitorWorkList &WL;
1910 CXCursor Parent;
1911public:
1912 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1913 : WL(wl), Parent(parent) {}
1914
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001915 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001916 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001917 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001918 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001919 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Douglas Gregorba0513d2011-10-25 01:33:02 +00001920 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001921 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001922 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001923 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001924 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001925 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001926 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001927 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001928 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001929 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001930 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001931 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001932 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001933 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001934 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1935 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001936 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001937 void VisitIfStmt(IfStmt *If);
1938 void VisitInitListExpr(InitListExpr *IE);
1939 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001940 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001941 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001942 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1943 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001944 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001945 void VisitStmt(Stmt *S);
1946 void VisitSwitchStmt(SwitchStmt *S);
1947 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001948 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001949 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001950 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001951 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001952 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001953 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001954 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001955
Ted Kremenek28a71942010-11-13 00:36:47 +00001956private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001957 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001958 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001959 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001960 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001961 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001962 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001963 void AddTypeLoc(TypeSourceInfo *TI);
1964 void EnqueueChildren(Stmt *S);
1965};
1966} // end anonyous namespace
1967
Ted Kremenekf64d8032010-11-18 00:02:32 +00001968void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1969 // 'S' should always be non-null, since it comes from the
1970 // statement we are visiting.
1971 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1972}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001973
1974void
1975EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1976 if (Qualifier)
1977 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1978}
1979
Ted Kremenek28a71942010-11-13 00:36:47 +00001980void EnqueueVisitor::AddStmt(Stmt *S) {
1981 if (S)
1982 WL.push_back(StmtVisit(S, Parent));
1983}
Ted Kremenek035dc412010-11-13 00:36:50 +00001984void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001985 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001986 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001987}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001988void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001989 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001990 if (A)
1991 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001992 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001993}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001994void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1995 if (D)
1996 WL.push_back(MemberRefVisit(D, L, Parent));
1997}
Ted Kremenek28a71942010-11-13 00:36:47 +00001998void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1999 if (TI)
2000 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2001 }
2002void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00002003 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00002004 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002005 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00002006 }
2007 if (size == WL.size())
2008 return;
2009 // Now reverse the entries we just added. This will match the DFS
2010 // ordering performed by the worklist.
2011 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2012 std::reverse(I, E);
2013}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002014void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
2015 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2016}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002017void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
2018 AddDecl(B->getBlockDecl());
2019}
Ted Kremenek28a71942010-11-13 00:36:47 +00002020void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
2021 EnqueueChildren(E);
2022 AddTypeLoc(E->getTypeSourceInfo());
2023}
Ted Kremenek083c7e22010-11-13 05:38:03 +00002024void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
2025 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
2026 E = S->body_rend(); I != E; ++I) {
2027 AddStmt(*I);
2028 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00002029}
Ted Kremenekf64d8032010-11-18 00:02:32 +00002030void EnqueueVisitor::
Douglas Gregorba0513d2011-10-25 01:33:02 +00002031VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
2032 AddStmt(S->getSubStmt());
2033 AddDeclarationNameInfo(S);
2034 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2035 AddNestedNameSpecifierLoc(QualifierLoc);
2036}
2037
2038void EnqueueVisitor::
Ted Kremenekf64d8032010-11-18 00:02:32 +00002039VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
2040 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2041 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002042 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2043 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00002044 if (!E->isImplicitAccess())
2045 AddStmt(E->getBase());
2046}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00002047void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
2048 // Enqueue the initializer or constructor arguments.
2049 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
2050 AddStmt(E->getConstructorArg(I-1));
2051 // Enqueue the array size, if any.
2052 AddStmt(E->getArraySize());
2053 // Enqueue the allocated type.
2054 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2055 // Enqueue the placement arguments.
2056 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2057 AddStmt(E->getPlacementArg(I-1));
2058}
Ted Kremenek28a71942010-11-13 00:36:47 +00002059void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00002060 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2061 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00002062 AddStmt(CE->getCallee());
2063 AddStmt(CE->getArg(0));
2064}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002065void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
2066 // Visit the name of the type being destroyed.
2067 AddTypeLoc(E->getDestroyedTypeInfo());
2068 // Visit the scope type that looks disturbingly like the nested-name-specifier
2069 // but isn't.
2070 AddTypeLoc(E->getScopeTypeInfo());
2071 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002072 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2073 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002074 // Visit base expression.
2075 AddStmt(E->getBase());
2076}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002077void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
2078 AddTypeLoc(E->getTypeSourceInfo());
2079}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002080void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
2081 EnqueueChildren(E);
2082 AddTypeLoc(E->getTypeSourceInfo());
2083}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00002084void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
2085 EnqueueChildren(E);
2086 if (E->isTypeOperand())
2087 AddTypeLoc(E->getTypeOperandSourceInfo());
2088}
Ted Kremenek55b933a2010-11-17 00:50:36 +00002089
2090void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
2091 *E) {
2092 EnqueueChildren(E);
2093 AddTypeLoc(E->getTypeSourceInfo());
2094}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00002095void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
2096 EnqueueChildren(E);
2097 if (E->isTypeOperand())
2098 AddTypeLoc(E->getTypeOperandSourceInfo());
2099}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002100void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002101 if (DR->hasExplicitTemplateArgs()) {
2102 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
2103 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002104 WL.push_back(DeclRefExprParts(DR, Parent));
2105}
Ted Kremenekf64d8032010-11-18 00:02:32 +00002106void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
2107 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2108 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00002109 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00002110}
Ted Kremenek035dc412010-11-13 00:36:50 +00002111void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
2112 unsigned size = WL.size();
2113 bool isFirst = true;
2114 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2115 D != DEnd; ++D) {
2116 AddDecl(*D, isFirst);
2117 isFirst = false;
2118 }
2119 if (size == WL.size())
2120 return;
2121 // Now reverse the entries we just added. This will match the DFS
2122 // ordering performed by the worklist.
2123 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2124 std::reverse(I, E);
2125}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002126void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
2127 AddStmt(E->getInit());
2128 typedef DesignatedInitExpr::Designator Designator;
2129 for (DesignatedInitExpr::reverse_designators_iterator
2130 D = E->designators_rbegin(), DEnd = E->designators_rend();
2131 D != DEnd; ++D) {
2132 if (D->isFieldDesignator()) {
2133 if (FieldDecl *Field = D->getField())
2134 AddMemberRef(Field, D->getFieldLoc());
2135 continue;
2136 }
2137 if (D->isArrayDesignator()) {
2138 AddStmt(E->getArrayIndex(*D));
2139 continue;
2140 }
2141 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2142 AddStmt(E->getArrayRangeEnd(*D));
2143 AddStmt(E->getArrayRangeStart(*D));
2144 }
2145}
Ted Kremenek28a71942010-11-13 00:36:47 +00002146void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
2147 EnqueueChildren(E);
2148 AddTypeLoc(E->getTypeInfoAsWritten());
2149}
2150void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2151 AddStmt(FS->getBody());
2152 AddStmt(FS->getInc());
2153 AddStmt(FS->getCond());
2154 AddDecl(FS->getConditionVariable());
2155 AddStmt(FS->getInit());
2156}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002157void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2158 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2159}
Ted Kremenek28a71942010-11-13 00:36:47 +00002160void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2161 AddStmt(If->getElse());
2162 AddStmt(If->getThen());
2163 AddStmt(If->getCond());
2164 AddDecl(If->getConditionVariable());
2165}
2166void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2167 // We care about the syntactic form of the initializer list, only.
2168 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2169 IE = Syntactic;
2170 EnqueueChildren(IE);
2171}
2172void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002173 WL.push_back(MemberExprParts(M, Parent));
2174
2175 // If the base of the member access expression is an implicit 'this', don't
2176 // visit it.
2177 // FIXME: If we ever want to show these implicit accesses, this will be
2178 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002179 if (!M->isImplicitAccess())
2180 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002181}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002182void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2183 AddTypeLoc(E->getEncodedTypeSourceInfo());
2184}
Ted Kremenek28a71942010-11-13 00:36:47 +00002185void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2186 EnqueueChildren(M);
2187 AddTypeLoc(M->getClassReceiverTypeInfo());
2188}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002189void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2190 // Visit the components of the offsetof expression.
2191 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2192 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2193 const OffsetOfNode &Node = E->getComponent(I-1);
2194 switch (Node.getKind()) {
2195 case OffsetOfNode::Array:
2196 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2197 break;
2198 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002199 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002200 break;
2201 case OffsetOfNode::Identifier:
2202 case OffsetOfNode::Base:
2203 continue;
2204 }
2205 }
2206 // Visit the type into which we're computing the offset.
2207 AddTypeLoc(E->getTypeSourceInfo());
2208}
Ted Kremenek28a71942010-11-13 00:36:47 +00002209void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002210 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002211 WL.push_back(OverloadExprParts(E, Parent));
2212}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002213void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2214 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002215 EnqueueChildren(E);
2216 if (E->isArgumentType())
2217 AddTypeLoc(E->getArgumentTypeInfo());
2218}
Ted Kremenek28a71942010-11-13 00:36:47 +00002219void EnqueueVisitor::VisitStmt(Stmt *S) {
2220 EnqueueChildren(S);
2221}
2222void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2223 AddStmt(S->getBody());
2224 AddStmt(S->getCond());
2225 AddDecl(S->getConditionVariable());
2226}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002227
Ted Kremenek28a71942010-11-13 00:36:47 +00002228void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2229 AddStmt(W->getBody());
2230 AddStmt(W->getCond());
2231 AddDecl(W->getConditionVariable());
2232}
John Wiegley21ff2e52011-04-28 00:16:57 +00002233
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002234void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2235 AddTypeLoc(E->getQueriedTypeSourceInfo());
2236}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002237
2238void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002239 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002240 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002241}
2242
John Wiegley21ff2e52011-04-28 00:16:57 +00002243void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2244 AddTypeLoc(E->getQueriedTypeSourceInfo());
2245}
2246
John Wiegley55262202011-04-25 06:54:41 +00002247void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2248 EnqueueChildren(E);
2249}
2250
Ted Kremenek28a71942010-11-13 00:36:47 +00002251void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2252 VisitOverloadExpr(U);
2253 if (!U->isImplicitAccess())
2254 AddStmt(U->getBase());
2255}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002256void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2257 AddStmt(E->getSubExpr());
2258 AddTypeLoc(E->getWrittenTypeInfo());
2259}
Douglas Gregor94d96292011-01-19 20:34:17 +00002260void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2261 WL.push_back(SizeOfPackExprParts(E, Parent));
2262}
Ted Kremenek60458782010-11-12 21:34:16 +00002263
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002264void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002265 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002266}
2267
2268bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2269 if (RegionOfInterest.isValid()) {
2270 SourceRange Range = getRawCursorExtent(C);
2271 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2272 return false;
2273 }
2274 return true;
2275}
2276
2277bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2278 while (!WL.empty()) {
2279 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002280 VisitorJob LI = WL.back();
2281 WL.pop_back();
2282
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002283 // Set the Parent field, then back to its old value once we're done.
2284 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2285
2286 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002287 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002288 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002289 if (!D)
2290 continue;
2291
2292 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002293 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2294 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002295 return true;
2296
2297 continue;
2298 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002299 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002300 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002301 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2302 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2303 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2304 Arg != ArgEnd; ++Arg) {
2305 if (VisitTemplateArgumentLoc(*Arg))
2306 return true;
2307 }
2308 continue;
2309 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002310 case VisitorJob::TypeLocVisitKind: {
2311 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002312 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002313 return true;
2314 continue;
2315 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002316 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002317 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002318 if (LabelStmt *stmt = LS->getStmt()) {
2319 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2320 TU))) {
2321 return true;
2322 }
2323 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002324 continue;
2325 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002326
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002327 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2328 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2329 if (VisitNestedNameSpecifierLoc(V->get()))
2330 return true;
2331 continue;
2332 }
2333
Ted Kremenekf64d8032010-11-18 00:02:32 +00002334 case VisitorJob::DeclarationNameInfoVisitKind: {
2335 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2336 ->get()))
2337 return true;
2338 continue;
2339 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002340 case VisitorJob::MemberRefVisitKind: {
2341 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2342 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2343 return true;
2344 continue;
2345 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002346 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002347 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002348 if (!S)
2349 continue;
2350
Ted Kremenekf1107452010-11-12 18:26:56 +00002351 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002352 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002353 if (!IsInRegionOfInterest(Cursor))
2354 continue;
2355 switch (Visitor(Cursor, Parent, ClientData)) {
2356 case CXChildVisit_Break: return true;
2357 case CXChildVisit_Continue: break;
2358 case CXChildVisit_Recurse:
2359 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002360 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002361 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002362 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002363 }
2364 case VisitorJob::MemberExprPartsKind: {
2365 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002366 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002367
2368 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002369 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2370 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002371 return true;
2372
2373 // Visit the declaration name.
2374 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2375 return true;
2376
2377 // Visit the explicitly-specified template arguments, if any.
2378 if (M->hasExplicitTemplateArgs()) {
2379 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2380 *ArgEnd = Arg + M->getNumTemplateArgs();
2381 Arg != ArgEnd; ++Arg) {
2382 if (VisitTemplateArgumentLoc(*Arg))
2383 return true;
2384 }
2385 }
2386 continue;
2387 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002388 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002389 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002390 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002391 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2392 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002393 return true;
2394 // Visit declaration name.
2395 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2396 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002397 continue;
2398 }
Ted Kremenek60458782010-11-12 21:34:16 +00002399 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002400 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002401 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002402 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2403 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002404 return true;
2405 // Visit the declaration name.
2406 if (VisitDeclarationNameInfo(O->getNameInfo()))
2407 return true;
2408 // Visit the overloaded declaration reference.
2409 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2410 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002411 continue;
2412 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002413 case VisitorJob::SizeOfPackExprPartsKind: {
2414 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2415 NamedDecl *Pack = E->getPack();
2416 if (isa<TemplateTypeParmDecl>(Pack)) {
2417 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2418 E->getPackLoc(), TU)))
2419 return true;
2420
2421 continue;
2422 }
2423
2424 if (isa<TemplateTemplateParmDecl>(Pack)) {
2425 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2426 E->getPackLoc(), TU)))
2427 return true;
2428
2429 continue;
2430 }
2431
2432 // Non-type template parameter packs and function parameter packs are
2433 // treated like DeclRefExpr cursors.
2434 continue;
2435 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002436 }
2437 }
2438 return false;
2439}
2440
Ted Kremenekcdba6592010-11-18 00:42:18 +00002441bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002442 VisitorWorkList *WL = 0;
2443 if (!WorkListFreeList.empty()) {
2444 WL = WorkListFreeList.back();
2445 WL->clear();
2446 WorkListFreeList.pop_back();
2447 }
2448 else {
2449 WL = new VisitorWorkList();
2450 WorkListCache.push_back(WL);
2451 }
2452 EnqueueWorkList(*WL, S);
2453 bool result = RunVisitorWorkList(*WL);
2454 WorkListFreeList.push_back(WL);
2455 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002456}
2457
Francois Pichet48a8d142011-07-25 22:00:44 +00002458namespace {
2459typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2460RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2461 const DeclarationNameInfo &NI,
2462 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002463 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002464 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2465 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2466 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2467
2468 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2469
2470 RefNamePieces Pieces;
2471
2472 if (WantQualifier && QLoc.isValid())
2473 Pieces.push_back(QLoc);
2474
2475 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2476 Pieces.push_back(NI.getLoc());
2477
2478 if (WantTemplateArgs && TemplateArgs)
2479 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2480 TemplateArgs->RAngleLoc));
2481
2482 if (Kind == DeclarationName::CXXOperatorName) {
2483 Pieces.push_back(SourceLocation::getFromRawEncoding(
2484 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2485 Pieces.push_back(SourceLocation::getFromRawEncoding(
2486 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2487 }
2488
2489 if (WantSinglePiece) {
2490 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2491 Pieces.clear();
2492 Pieces.push_back(R);
2493 }
2494
2495 return Pieces;
2496}
2497}
2498
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002499//===----------------------------------------------------------------------===//
2500// Misc. API hooks.
2501//===----------------------------------------------------------------------===//
2502
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002503static llvm::sys::Mutex EnableMultithreadingMutex;
2504static bool EnabledMultithreading;
2505
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002506extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002507CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2508 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002509 // Disable pretty stack trace functionality, which will otherwise be a very
2510 // poor citizen of the world and set up all sorts of signal handlers.
2511 llvm::DisablePrettyStackTrace = true;
2512
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002513 // We use crash recovery to make some of our APIs more reliable, implicitly
2514 // enable it.
2515 llvm::CrashRecoveryContext::Enable();
2516
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002517 // Enable support for multithreading in LLVM.
2518 {
2519 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2520 if (!EnabledMultithreading) {
2521 llvm::llvm_start_multithreaded();
2522 EnabledMultithreading = true;
2523 }
2524 }
2525
Douglas Gregora030b7c2010-01-22 20:35:53 +00002526 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002527 if (excludeDeclarationsFromPCH)
2528 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002529 if (displayDiagnostics)
2530 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002531 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002532}
2533
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002534void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002535 if (CIdx)
2536 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002537}
2538
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002539void clang_toggleCrashRecovery(unsigned isEnabled) {
2540 if (isEnabled)
2541 llvm::CrashRecoveryContext::Enable();
2542 else
2543 llvm::CrashRecoveryContext::Disable();
2544}
2545
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002546CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002547 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002548 if (!CIdx)
2549 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002550
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002551 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002552 FileSystemOptions FileSystemOpts;
2553 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002554
David Blaikied6471f72011-09-25 23:23:43 +00002555 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002556 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002557 CXXIdx->getOnlyLocalDecls(),
2558 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002559 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002560}
2561
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002562unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002563 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002564 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002565}
2566
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002567CXTranslationUnit
2568clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2569 const char *source_filename,
2570 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002571 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002572 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002573 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002574 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002575 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002576 return clang_parseTranslationUnit(CIdx, source_filename,
2577 command_line_args, num_command_line_args,
2578 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002579 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002580}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002581
2582struct ParseTranslationUnitInfo {
2583 CXIndex CIdx;
2584 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002585 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002586 int num_command_line_args;
2587 struct CXUnsavedFile *unsaved_files;
2588 unsigned num_unsaved_files;
2589 unsigned options;
2590 CXTranslationUnit result;
2591};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002592static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002593 ParseTranslationUnitInfo *PTUI =
2594 static_cast<ParseTranslationUnitInfo*>(UserData);
2595 CXIndex CIdx = PTUI->CIdx;
2596 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002597 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002598 int num_command_line_args = PTUI->num_command_line_args;
2599 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2600 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2601 unsigned options = PTUI->options;
2602 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002603
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002604 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002605 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002606
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002607 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2608
Douglas Gregor44c181a2010-07-23 00:33:23 +00002609 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002610 // FIXME: Add a flag for modules.
2611 TranslationUnitKind TUKind
2612 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002613 bool CacheCodeCompetionResults
2614 = options & CXTranslationUnit_CacheCompletionResults;
2615
Douglas Gregor5352ac02010-01-28 00:27:43 +00002616 // Configure the diagnostics.
2617 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002618 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002619 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2620 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002621
Ted Kremenek25a11e12011-03-22 01:15:24 +00002622 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002623 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2624 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002625 DiagCleanup(Diags.getPtr());
2626
2627 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2628 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2629
2630 // Recover resources if we crash before exiting this function.
2631 llvm::CrashRecoveryContextCleanupRegistrar<
2632 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2633
Douglas Gregor4db64a42010-01-23 00:14:00 +00002634 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002635 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002636 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002637 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002638 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2639 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002640 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002641
Ted Kremenek25a11e12011-03-22 01:15:24 +00002642 llvm::OwningPtr<std::vector<const char *> >
2643 Args(new std::vector<const char*>());
2644
2645 // Recover resources if we crash before exiting this method.
2646 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2647 ArgsCleanup(Args.get());
2648
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002649 // Since the Clang C library is primarily used by batch tools dealing with
2650 // (often very broken) source code, where spell-checking can have a
2651 // significant negative impact on performance (particularly when
2652 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002653 // Only do this if we haven't found a spell-checking-related argument.
2654 bool FoundSpellCheckingArgument = false;
2655 for (int I = 0; I != num_command_line_args; ++I) {
2656 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2657 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2658 FoundSpellCheckingArgument = true;
2659 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002660 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002661 }
2662 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002663 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002664
Ted Kremenek25a11e12011-03-22 01:15:24 +00002665 Args->insert(Args->end(), command_line_args,
2666 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002667
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002668 // The 'source_filename' argument is optional. If the caller does not
2669 // specify it then it is assumed that the source file is specified
2670 // in the actual argument list.
2671 // Put the source file after command_line_args otherwise if '-x' flag is
2672 // present it will be unused.
2673 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002674 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002675
Douglas Gregor44c181a2010-07-23 00:33:23 +00002676 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002677 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002678 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002679 Args->push_back("-Xclang");
2680 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002681 NestedMacroExpansions
2682 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002683 }
2684
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002685 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002686 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002687 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2688 /* vector::data() not portable */,
2689 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002690 Diags,
2691 CXXIdx->getClangResourcesPath(),
2692 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002693 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002694 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002695 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002696 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002697 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002698 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002699 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002700 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002701
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002702 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002703 // Make sure to check that 'Unit' is non-NULL.
2704 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2705 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2706 DEnd = Unit->stored_diag_end();
2707 D != DEnd; ++D) {
2708 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2709 CXString Msg = clang_formatDiagnostic(&Diag,
2710 clang_defaultDiagnosticDisplayOptions());
2711 fprintf(stderr, "%s\n", clang_getCString(Msg));
2712 clang_disposeString(Msg);
2713 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002714#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002715 // On Windows, force a flush, since there may be multiple copies of
2716 // stderr and stdout in the file system, all with different buffers
2717 // but writing to the same device.
2718 fflush(stderr);
2719#endif
2720 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002721 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002722
Ted Kremeneka60ed472010-11-16 08:15:36 +00002723 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002724}
2725CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2726 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002727 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002728 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002729 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002730 unsigned num_unsaved_files,
2731 unsigned options) {
2732 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002733 num_command_line_args, unsaved_files,
2734 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002735 llvm::CrashRecoveryContext CRC;
2736
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002737 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002738 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2739 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2740 fprintf(stderr, " 'command_line_args' : [");
2741 for (int i = 0; i != num_command_line_args; ++i) {
2742 if (i)
2743 fprintf(stderr, ", ");
2744 fprintf(stderr, "'%s'", command_line_args[i]);
2745 }
2746 fprintf(stderr, "],\n");
2747 fprintf(stderr, " 'unsaved_files' : [");
2748 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2749 if (i)
2750 fprintf(stderr, ", ");
2751 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2752 unsaved_files[i].Length);
2753 }
2754 fprintf(stderr, "],\n");
2755 fprintf(stderr, " 'options' : %d,\n", options);
2756 fprintf(stderr, "}\n");
2757
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002758 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002759 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2760 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002761 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002762
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002763 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002764}
2765
Douglas Gregor19998442010-08-13 15:35:05 +00002766unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2767 return CXSaveTranslationUnit_None;
2768}
2769
2770int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2771 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002772 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002773 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002774
Douglas Gregor39c411f2011-07-06 16:43:36 +00002775 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002776 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2777 PrintLibclangResourceUsage(TU);
2778 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002779}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002780
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002781void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002782 if (CTUnit) {
2783 // If the translation unit has been marked as unsafe to free, just discard
2784 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002785 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002786 return;
2787
Ted Kremeneka60ed472010-11-16 08:15:36 +00002788 delete static_cast<ASTUnit *>(CTUnit->TUData);
2789 disposeCXStringPool(CTUnit->StringPool);
2790 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002791 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002792}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002793
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002794unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2795 return CXReparse_None;
2796}
2797
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002798struct ReparseTranslationUnitInfo {
2799 CXTranslationUnit TU;
2800 unsigned num_unsaved_files;
2801 struct CXUnsavedFile *unsaved_files;
2802 unsigned options;
2803 int result;
2804};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002805
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002806static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002807 ReparseTranslationUnitInfo *RTUI =
2808 static_cast<ReparseTranslationUnitInfo*>(UserData);
2809 CXTranslationUnit TU = RTUI->TU;
2810 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2811 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2812 unsigned options = RTUI->options;
2813 (void) options;
2814 RTUI->result = 1;
2815
Douglas Gregorabc563f2010-07-19 21:46:24 +00002816 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002817 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002818
Ted Kremeneka60ed472010-11-16 08:15:36 +00002819 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002820 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002821
Ted Kremenek25a11e12011-03-22 01:15:24 +00002822 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2823 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2824
2825 // Recover resources if we crash before exiting this function.
2826 llvm::CrashRecoveryContextCleanupRegistrar<
2827 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2828
Douglas Gregorabc563f2010-07-19 21:46:24 +00002829 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002830 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002831 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002832 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002833 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2834 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002835 }
2836
Ted Kremenek4ee99262011-03-22 20:16:19 +00002837 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2838 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002839 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002840}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002841
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002842int clang_reparseTranslationUnit(CXTranslationUnit TU,
2843 unsigned num_unsaved_files,
2844 struct CXUnsavedFile *unsaved_files,
2845 unsigned options) {
2846 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2847 options, 0 };
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002848
Argyrios Kyrtzidise7de9b42011-10-29 19:32:39 +00002849 if (getenv("LIBCLANG_NOTHREADS")) {
Argyrios Kyrtzidis8c4b47e2011-10-28 22:54:33 +00002850 clang_reparseTranslationUnit_Impl(&RTUI);
2851 return RTUI.result;
2852 }
2853
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002854 llvm::CrashRecoveryContext CRC;
2855
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002856 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002857 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002858 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002859 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002860 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2861 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002862
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002863 return RTUI.result;
2864}
2865
Douglas Gregordf95a132010-08-09 20:45:32 +00002866
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002867CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002868 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002869 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002870
Ted Kremeneka60ed472010-11-16 08:15:36 +00002871 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002872 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002873}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002874
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002875CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002876 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002877 return Result;
2878}
2879
Ted Kremenekfb480492010-01-13 21:46:36 +00002880} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002881
Ted Kremenekfb480492010-01-13 21:46:36 +00002882//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002883// CXFile Operations.
2884//===----------------------------------------------------------------------===//
2885
2886extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002887CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002888 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002889 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002890
Steve Naroff88145032009-10-27 14:35:18 +00002891 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002892 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002893}
2894
2895time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002896 if (!SFile)
2897 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002898
Steve Naroff88145032009-10-27 14:35:18 +00002899 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2900 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002901}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002902
Douglas Gregorb9790342010-01-22 21:44:22 +00002903CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2904 if (!tu)
2905 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002906
Ted Kremeneka60ed472010-11-16 08:15:36 +00002907 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002908
Douglas Gregorb9790342010-01-22 21:44:22 +00002909 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002910 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002911}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002912
Douglas Gregordd3e5542011-05-04 00:14:37 +00002913unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2914 if (!tu || !file)
2915 return 0;
2916
2917 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2918 FileEntry *FEnt = static_cast<FileEntry *>(file);
2919 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2920 .isFileMultipleIncludeGuarded(FEnt);
2921}
2922
Ted Kremenekfb480492010-01-13 21:46:36 +00002923} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002924
Ted Kremenekfb480492010-01-13 21:46:36 +00002925//===----------------------------------------------------------------------===//
2926// CXCursor Operations.
2927//===----------------------------------------------------------------------===//
2928
Ted Kremenekfb480492010-01-13 21:46:36 +00002929static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002930 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002931 return getDeclFromExpr(CE->getSubExpr());
2932
Ted Kremenekfb480492010-01-13 21:46:36 +00002933 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2934 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002935 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2936 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002937 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2938 return ME->getMemberDecl();
2939 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2940 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002941 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002942 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002943
Ted Kremenekfb480492010-01-13 21:46:36 +00002944 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2945 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002946 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002947 if (!CE->isElidable())
2948 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002949 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2950 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002951
Douglas Gregordb1314e2010-10-01 21:11:22 +00002952 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2953 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002954 if (SubstNonTypeTemplateParmPackExpr *NTTP
2955 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2956 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002957 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2958 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2959 isa<ParmVarDecl>(SizeOfPack->getPack()))
2960 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002961
Ted Kremenekfb480492010-01-13 21:46:36 +00002962 return 0;
2963}
2964
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002965static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002966 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2967 return getLocationFromExpr(CE->getSubExpr());
2968
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002969 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2970 return /*FIXME:*/Msg->getLeftLoc();
2971 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2972 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002973 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2974 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002975 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2976 return Member->getMemberLoc();
2977 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2978 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002979 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2980 return SizeOfPack->getPackLoc();
2981
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002982 return E->getLocStart();
2983}
2984
Ted Kremenekfb480492010-01-13 21:46:36 +00002985extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002986
2987unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002988 CXCursorVisitor visitor,
2989 CXClientData client_data) {
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002990 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2991 /*VisitPreprocessorLast=*/false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002992 return CursorVis.VisitChildren(parent);
2993}
2994
David Chisnall3387c652010-11-03 14:12:26 +00002995#ifndef __has_feature
2996#define __has_feature(x) 0
2997#endif
2998#if __has_feature(blocks)
2999typedef enum CXChildVisitResult
3000 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3001
3002static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3003 CXClientData client_data) {
3004 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3005 return block(cursor, parent);
3006}
3007#else
3008// If we are compiled with a compiler that doesn't have native blocks support,
3009// define and call the block manually, so the
3010typedef struct _CXChildVisitResult
3011{
3012 void *isa;
3013 int flags;
3014 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003015 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3016 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003017} *CXCursorVisitorBlock;
3018
3019static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3020 CXClientData client_data) {
3021 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3022 return block->invoke(block, cursor, parent);
3023}
3024#endif
3025
3026
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003027unsigned clang_visitChildrenWithBlock(CXCursor parent,
3028 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003029 return clang_visitChildren(parent, visitWithBlock, block);
3030}
3031
Douglas Gregor78205d42010-01-20 21:45:58 +00003032static CXString getDeclSpelling(Decl *D) {
3033 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003034 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003035 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003036 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3037 return createCXString(Property->getIdentifier()->getName());
3038
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003039 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003040 }
3041
Douglas Gregor78205d42010-01-20 21:45:58 +00003042 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003043 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003044
Douglas Gregor78205d42010-01-20 21:45:58 +00003045 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3046 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3047 // and returns different names. NamedDecl returns the class name and
3048 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003049 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003050
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003051 if (isa<UsingDirectiveDecl>(D))
3052 return createCXString("");
3053
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003054 llvm::SmallString<1024> S;
3055 llvm::raw_svector_ostream os(S);
3056 ND->printName(os);
3057
3058 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003059}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003060
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003061CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003062 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003063 return clang_getTranslationUnitSpelling(
3064 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003065
Steve Narofff334b4e2009-09-02 18:26:48 +00003066 if (clang_isReference(C.kind)) {
3067 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003068 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003069 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003070 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003071 }
3072 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003073 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003074 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003075 }
3076 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003077 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003078 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003079 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003080 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003081 case CXCursor_CXXBaseSpecifier: {
3082 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3083 return createCXString(B->getType().getAsString());
3084 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003085 case CXCursor_TypeRef: {
3086 TypeDecl *Type = getCursorTypeRef(C).first;
3087 assert(Type && "Missing type decl");
3088
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003089 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3090 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003091 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003092 case CXCursor_TemplateRef: {
3093 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003094 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003095
3096 return createCXString(Template->getNameAsString());
3097 }
Douglas Gregor69319002010-08-31 23:48:11 +00003098
3099 case CXCursor_NamespaceRef: {
3100 NamedDecl *NS = getCursorNamespaceRef(C).first;
3101 assert(NS && "Missing namespace decl");
3102
3103 return createCXString(NS->getNameAsString());
3104 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003105
Douglas Gregora67e03f2010-09-09 21:42:20 +00003106 case CXCursor_MemberRef: {
3107 FieldDecl *Field = getCursorMemberRef(C).first;
3108 assert(Field && "Missing member decl");
3109
3110 return createCXString(Field->getNameAsString());
3111 }
3112
Douglas Gregor36897b02010-09-10 00:22:18 +00003113 case CXCursor_LabelRef: {
3114 LabelStmt *Label = getCursorLabelRef(C).first;
3115 assert(Label && "Missing label");
3116
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003117 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003118 }
3119
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003120 case CXCursor_OverloadedDeclRef: {
3121 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3122 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3123 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3124 return createCXString(ND->getNameAsString());
3125 return createCXString("");
3126 }
3127 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3128 return createCXString(E->getName().getAsString());
3129 OverloadedTemplateStorage *Ovl
3130 = Storage.get<OverloadedTemplateStorage*>();
3131 if (Ovl->size() == 0)
3132 return createCXString("");
3133 return createCXString((*Ovl->begin())->getNameAsString());
3134 }
3135
Daniel Dunbaracca7252009-11-30 20:42:49 +00003136 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003137 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003138 }
3139 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003140
3141 if (clang_isExpression(C.kind)) {
3142 Decl *D = getDeclFromExpr(getCursorExpr(C));
3143 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003144 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003145 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003146 }
3147
Douglas Gregor36897b02010-09-10 00:22:18 +00003148 if (clang_isStatement(C.kind)) {
3149 Stmt *S = getCursorStmt(C);
3150 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003151 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003152
3153 return createCXString("");
3154 }
3155
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003156 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003157 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003158 ->getNameStart());
3159
Douglas Gregor572feb22010-03-18 18:04:21 +00003160 if (C.kind == CXCursor_MacroDefinition)
3161 return createCXString(getCursorMacroDefinition(C)->getName()
3162 ->getNameStart());
3163
Douglas Gregorecdcb882010-10-20 22:00:55 +00003164 if (C.kind == CXCursor_InclusionDirective)
3165 return createCXString(getCursorInclusionDirective(C)->getFileName());
3166
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003167 if (clang_isDeclaration(C.kind))
3168 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003169
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003170 if (C.kind == CXCursor_AnnotateAttr) {
3171 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3172 return createCXString(AA->getAnnotation());
3173 }
3174
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003175 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003176}
3177
Douglas Gregor358559d2010-10-02 22:49:11 +00003178CXString clang_getCursorDisplayName(CXCursor C) {
3179 if (!clang_isDeclaration(C.kind))
3180 return clang_getCursorSpelling(C);
3181
3182 Decl *D = getCursorDecl(C);
3183 if (!D)
3184 return createCXString("");
3185
Douglas Gregor30c42402011-09-27 22:38:19 +00003186 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003187 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3188 D = FunTmpl->getTemplatedDecl();
3189
3190 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3191 llvm::SmallString<64> Str;
3192 llvm::raw_svector_ostream OS(Str);
3193 OS << Function->getNameAsString();
3194 if (Function->getPrimaryTemplate())
3195 OS << "<>";
3196 OS << "(";
3197 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3198 if (I)
3199 OS << ", ";
3200 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3201 }
3202
3203 if (Function->isVariadic()) {
3204 if (Function->getNumParams())
3205 OS << ", ";
3206 OS << "...";
3207 }
3208 OS << ")";
3209 return createCXString(OS.str());
3210 }
3211
3212 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3213 llvm::SmallString<64> Str;
3214 llvm::raw_svector_ostream OS(Str);
3215 OS << ClassTemplate->getNameAsString();
3216 OS << "<";
3217 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3218 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3219 if (I)
3220 OS << ", ";
3221
3222 NamedDecl *Param = Params->getParam(I);
3223 if (Param->getIdentifier()) {
3224 OS << Param->getIdentifier()->getName();
3225 continue;
3226 }
3227
3228 // There is no parameter name, which makes this tricky. Try to come up
3229 // with something useful that isn't too long.
3230 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3231 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3232 else if (NonTypeTemplateParmDecl *NTTP
3233 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3234 OS << NTTP->getType().getAsString(Policy);
3235 else
3236 OS << "template<...> class";
3237 }
3238
3239 OS << ">";
3240 return createCXString(OS.str());
3241 }
3242
3243 if (ClassTemplateSpecializationDecl *ClassSpec
3244 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3245 // If the type was explicitly written, use that.
3246 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3247 return createCXString(TSInfo->getType().getAsString(Policy));
3248
3249 llvm::SmallString<64> Str;
3250 llvm::raw_svector_ostream OS(Str);
3251 OS << ClassSpec->getNameAsString();
3252 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003253 ClassSpec->getTemplateArgs().data(),
3254 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003255 Policy);
3256 return createCXString(OS.str());
3257 }
3258
3259 return clang_getCursorSpelling(C);
3260}
3261
Ted Kremeneke68fff62010-02-17 00:41:32 +00003262CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003263 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003264 case CXCursor_FunctionDecl:
3265 return createCXString("FunctionDecl");
3266 case CXCursor_TypedefDecl:
3267 return createCXString("TypedefDecl");
3268 case CXCursor_EnumDecl:
3269 return createCXString("EnumDecl");
3270 case CXCursor_EnumConstantDecl:
3271 return createCXString("EnumConstantDecl");
3272 case CXCursor_StructDecl:
3273 return createCXString("StructDecl");
3274 case CXCursor_UnionDecl:
3275 return createCXString("UnionDecl");
3276 case CXCursor_ClassDecl:
3277 return createCXString("ClassDecl");
3278 case CXCursor_FieldDecl:
3279 return createCXString("FieldDecl");
3280 case CXCursor_VarDecl:
3281 return createCXString("VarDecl");
3282 case CXCursor_ParmDecl:
3283 return createCXString("ParmDecl");
3284 case CXCursor_ObjCInterfaceDecl:
3285 return createCXString("ObjCInterfaceDecl");
3286 case CXCursor_ObjCCategoryDecl:
3287 return createCXString("ObjCCategoryDecl");
3288 case CXCursor_ObjCProtocolDecl:
3289 return createCXString("ObjCProtocolDecl");
3290 case CXCursor_ObjCPropertyDecl:
3291 return createCXString("ObjCPropertyDecl");
3292 case CXCursor_ObjCIvarDecl:
3293 return createCXString("ObjCIvarDecl");
3294 case CXCursor_ObjCInstanceMethodDecl:
3295 return createCXString("ObjCInstanceMethodDecl");
3296 case CXCursor_ObjCClassMethodDecl:
3297 return createCXString("ObjCClassMethodDecl");
3298 case CXCursor_ObjCImplementationDecl:
3299 return createCXString("ObjCImplementationDecl");
3300 case CXCursor_ObjCCategoryImplDecl:
3301 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003302 case CXCursor_CXXMethod:
3303 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003304 case CXCursor_UnexposedDecl:
3305 return createCXString("UnexposedDecl");
3306 case CXCursor_ObjCSuperClassRef:
3307 return createCXString("ObjCSuperClassRef");
3308 case CXCursor_ObjCProtocolRef:
3309 return createCXString("ObjCProtocolRef");
3310 case CXCursor_ObjCClassRef:
3311 return createCXString("ObjCClassRef");
3312 case CXCursor_TypeRef:
3313 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003314 case CXCursor_TemplateRef:
3315 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003316 case CXCursor_NamespaceRef:
3317 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003318 case CXCursor_MemberRef:
3319 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003320 case CXCursor_LabelRef:
3321 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003322 case CXCursor_OverloadedDeclRef:
3323 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003324 case CXCursor_IntegerLiteral:
3325 return createCXString("IntegerLiteral");
3326 case CXCursor_FloatingLiteral:
3327 return createCXString("FloatingLiteral");
3328 case CXCursor_ImaginaryLiteral:
3329 return createCXString("ImaginaryLiteral");
3330 case CXCursor_StringLiteral:
3331 return createCXString("StringLiteral");
3332 case CXCursor_CharacterLiteral:
3333 return createCXString("CharacterLiteral");
3334 case CXCursor_ParenExpr:
3335 return createCXString("ParenExpr");
3336 case CXCursor_UnaryOperator:
3337 return createCXString("UnaryOperator");
3338 case CXCursor_ArraySubscriptExpr:
3339 return createCXString("ArraySubscriptExpr");
3340 case CXCursor_BinaryOperator:
3341 return createCXString("BinaryOperator");
3342 case CXCursor_CompoundAssignOperator:
3343 return createCXString("CompoundAssignOperator");
3344 case CXCursor_ConditionalOperator:
3345 return createCXString("ConditionalOperator");
3346 case CXCursor_CStyleCastExpr:
3347 return createCXString("CStyleCastExpr");
3348 case CXCursor_CompoundLiteralExpr:
3349 return createCXString("CompoundLiteralExpr");
3350 case CXCursor_InitListExpr:
3351 return createCXString("InitListExpr");
3352 case CXCursor_AddrLabelExpr:
3353 return createCXString("AddrLabelExpr");
3354 case CXCursor_StmtExpr:
3355 return createCXString("StmtExpr");
3356 case CXCursor_GenericSelectionExpr:
3357 return createCXString("GenericSelectionExpr");
3358 case CXCursor_GNUNullExpr:
3359 return createCXString("GNUNullExpr");
3360 case CXCursor_CXXStaticCastExpr:
3361 return createCXString("CXXStaticCastExpr");
3362 case CXCursor_CXXDynamicCastExpr:
3363 return createCXString("CXXDynamicCastExpr");
3364 case CXCursor_CXXReinterpretCastExpr:
3365 return createCXString("CXXReinterpretCastExpr");
3366 case CXCursor_CXXConstCastExpr:
3367 return createCXString("CXXConstCastExpr");
3368 case CXCursor_CXXFunctionalCastExpr:
3369 return createCXString("CXXFunctionalCastExpr");
3370 case CXCursor_CXXTypeidExpr:
3371 return createCXString("CXXTypeidExpr");
3372 case CXCursor_CXXBoolLiteralExpr:
3373 return createCXString("CXXBoolLiteralExpr");
3374 case CXCursor_CXXNullPtrLiteralExpr:
3375 return createCXString("CXXNullPtrLiteralExpr");
3376 case CXCursor_CXXThisExpr:
3377 return createCXString("CXXThisExpr");
3378 case CXCursor_CXXThrowExpr:
3379 return createCXString("CXXThrowExpr");
3380 case CXCursor_CXXNewExpr:
3381 return createCXString("CXXNewExpr");
3382 case CXCursor_CXXDeleteExpr:
3383 return createCXString("CXXDeleteExpr");
3384 case CXCursor_UnaryExpr:
3385 return createCXString("UnaryExpr");
3386 case CXCursor_ObjCStringLiteral:
3387 return createCXString("ObjCStringLiteral");
3388 case CXCursor_ObjCEncodeExpr:
3389 return createCXString("ObjCEncodeExpr");
3390 case CXCursor_ObjCSelectorExpr:
3391 return createCXString("ObjCSelectorExpr");
3392 case CXCursor_ObjCProtocolExpr:
3393 return createCXString("ObjCProtocolExpr");
3394 case CXCursor_ObjCBridgedCastExpr:
3395 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003396 case CXCursor_BlockExpr:
3397 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003398 case CXCursor_PackExpansionExpr:
3399 return createCXString("PackExpansionExpr");
3400 case CXCursor_SizeOfPackExpr:
3401 return createCXString("SizeOfPackExpr");
3402 case CXCursor_UnexposedExpr:
3403 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003404 case CXCursor_DeclRefExpr:
3405 return createCXString("DeclRefExpr");
3406 case CXCursor_MemberRefExpr:
3407 return createCXString("MemberRefExpr");
3408 case CXCursor_CallExpr:
3409 return createCXString("CallExpr");
3410 case CXCursor_ObjCMessageExpr:
3411 return createCXString("ObjCMessageExpr");
3412 case CXCursor_UnexposedStmt:
3413 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003414 case CXCursor_DeclStmt:
3415 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003416 case CXCursor_LabelStmt:
3417 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003418 case CXCursor_CompoundStmt:
3419 return createCXString("CompoundStmt");
3420 case CXCursor_CaseStmt:
3421 return createCXString("CaseStmt");
3422 case CXCursor_DefaultStmt:
3423 return createCXString("DefaultStmt");
3424 case CXCursor_IfStmt:
3425 return createCXString("IfStmt");
3426 case CXCursor_SwitchStmt:
3427 return createCXString("SwitchStmt");
3428 case CXCursor_WhileStmt:
3429 return createCXString("WhileStmt");
3430 case CXCursor_DoStmt:
3431 return createCXString("DoStmt");
3432 case CXCursor_ForStmt:
3433 return createCXString("ForStmt");
3434 case CXCursor_GotoStmt:
3435 return createCXString("GotoStmt");
3436 case CXCursor_IndirectGotoStmt:
3437 return createCXString("IndirectGotoStmt");
3438 case CXCursor_ContinueStmt:
3439 return createCXString("ContinueStmt");
3440 case CXCursor_BreakStmt:
3441 return createCXString("BreakStmt");
3442 case CXCursor_ReturnStmt:
3443 return createCXString("ReturnStmt");
3444 case CXCursor_AsmStmt:
3445 return createCXString("AsmStmt");
3446 case CXCursor_ObjCAtTryStmt:
3447 return createCXString("ObjCAtTryStmt");
3448 case CXCursor_ObjCAtCatchStmt:
3449 return createCXString("ObjCAtCatchStmt");
3450 case CXCursor_ObjCAtFinallyStmt:
3451 return createCXString("ObjCAtFinallyStmt");
3452 case CXCursor_ObjCAtThrowStmt:
3453 return createCXString("ObjCAtThrowStmt");
3454 case CXCursor_ObjCAtSynchronizedStmt:
3455 return createCXString("ObjCAtSynchronizedStmt");
3456 case CXCursor_ObjCAutoreleasePoolStmt:
3457 return createCXString("ObjCAutoreleasePoolStmt");
3458 case CXCursor_ObjCForCollectionStmt:
3459 return createCXString("ObjCForCollectionStmt");
3460 case CXCursor_CXXCatchStmt:
3461 return createCXString("CXXCatchStmt");
3462 case CXCursor_CXXTryStmt:
3463 return createCXString("CXXTryStmt");
3464 case CXCursor_CXXForRangeStmt:
3465 return createCXString("CXXForRangeStmt");
3466 case CXCursor_SEHTryStmt:
3467 return createCXString("SEHTryStmt");
3468 case CXCursor_SEHExceptStmt:
3469 return createCXString("SEHExceptStmt");
3470 case CXCursor_SEHFinallyStmt:
3471 return createCXString("SEHFinallyStmt");
3472 case CXCursor_NullStmt:
3473 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003474 case CXCursor_InvalidFile:
3475 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003476 case CXCursor_InvalidCode:
3477 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003478 case CXCursor_NoDeclFound:
3479 return createCXString("NoDeclFound");
3480 case CXCursor_NotImplemented:
3481 return createCXString("NotImplemented");
3482 case CXCursor_TranslationUnit:
3483 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003484 case CXCursor_UnexposedAttr:
3485 return createCXString("UnexposedAttr");
3486 case CXCursor_IBActionAttr:
3487 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003488 case CXCursor_IBOutletAttr:
3489 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003490 case CXCursor_IBOutletCollectionAttr:
3491 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003492 case CXCursor_CXXFinalAttr:
3493 return createCXString("attribute(final)");
3494 case CXCursor_CXXOverrideAttr:
3495 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003496 case CXCursor_AnnotateAttr:
3497 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003498 case CXCursor_PreprocessingDirective:
3499 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003500 case CXCursor_MacroDefinition:
3501 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003502 case CXCursor_MacroExpansion:
3503 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003504 case CXCursor_InclusionDirective:
3505 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003506 case CXCursor_Namespace:
3507 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003508 case CXCursor_LinkageSpec:
3509 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003510 case CXCursor_CXXBaseSpecifier:
3511 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003512 case CXCursor_Constructor:
3513 return createCXString("CXXConstructor");
3514 case CXCursor_Destructor:
3515 return createCXString("CXXDestructor");
3516 case CXCursor_ConversionFunction:
3517 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003518 case CXCursor_TemplateTypeParameter:
3519 return createCXString("TemplateTypeParameter");
3520 case CXCursor_NonTypeTemplateParameter:
3521 return createCXString("NonTypeTemplateParameter");
3522 case CXCursor_TemplateTemplateParameter:
3523 return createCXString("TemplateTemplateParameter");
3524 case CXCursor_FunctionTemplate:
3525 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003526 case CXCursor_ClassTemplate:
3527 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003528 case CXCursor_ClassTemplatePartialSpecialization:
3529 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003530 case CXCursor_NamespaceAlias:
3531 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003532 case CXCursor_UsingDirective:
3533 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003534 case CXCursor_UsingDeclaration:
3535 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003536 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003537 return createCXString("TypeAliasDecl");
3538 case CXCursor_ObjCSynthesizeDecl:
3539 return createCXString("ObjCSynthesizeDecl");
3540 case CXCursor_ObjCDynamicDecl:
3541 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003542 case CXCursor_CXXAccessSpecifier:
3543 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003544 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003545
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003546 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003547 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003548}
Steve Naroff89922f82009-08-31 00:59:03 +00003549
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003550struct GetCursorData {
3551 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003552 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003553 CXCursor &BestCursor;
3554
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003555 GetCursorData(SourceManager &SM,
3556 SourceLocation tokenBegin, CXCursor &outputCursor)
3557 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3558 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3559 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003560};
3561
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003562static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3563 CXCursor parent,
3564 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003565 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3566 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003567
3568 // If we point inside a macro argument we should provide info of what the
3569 // token is so use the actual cursor, don't replace it with a macro expansion
3570 // cursor.
3571 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3572 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003573
3574 if (clang_isDeclaration(cursor.kind)) {
3575 // Avoid having the implicit methods override the property decls.
3576 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3577 if (MD->isImplicit())
3578 return CXChildVisit_Break;
3579 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003580
3581 if (clang_isExpression(cursor.kind) &&
3582 clang_isDeclaration(BestCursor->kind)) {
3583 Decl *D = getCursorDecl(*BestCursor);
3584
3585 // Avoid having the cursor of an expression replace the declaration cursor
3586 // when the expression source range overlaps the declaration range.
3587 // This can happen for C++ constructor expressions whose range generally
3588 // include the variable declaration, e.g.:
3589 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3590 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3591 D->getLocation() == Data->TokenBeginLoc)
3592 return CXChildVisit_Break;
3593 }
3594
Douglas Gregor93798e22010-11-05 21:11:19 +00003595 // If our current best cursor is the construction of a temporary object,
3596 // don't replace that cursor with a type reference, because we want
3597 // clang_getCursor() to point at the constructor.
3598 if (clang_isExpression(BestCursor->kind) &&
3599 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003600 cursor.kind == CXCursor_TypeRef) {
3601 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3602 // as having the actual point on the type reference.
3603 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003604 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003605 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003606
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003607 *BestCursor = cursor;
3608 return CXChildVisit_Recurse;
3609}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003610
Douglas Gregorb9790342010-01-22 21:44:22 +00003611CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3612 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003613 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003614
Ted Kremeneka60ed472010-11-16 08:15:36 +00003615 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003616 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3617
Ted Kremeneka297de22010-01-25 22:34:44 +00003618 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003619 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003620
Douglas Gregor40749ee2010-11-03 00:35:38 +00003621 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003622 if (Logging) {
3623 CXFile SearchFile;
3624 unsigned SearchLine, SearchColumn;
3625 CXFile ResultFile;
3626 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003627 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3628 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003629 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3630
Chandler Carruth20174222011-08-31 16:53:37 +00003631 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3632 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3633 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003634 SearchFileName = clang_getFileName(SearchFile);
3635 ResultFileName = clang_getFileName(ResultFile);
3636 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003637 USR = clang_getCursorUSR(Result);
3638 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003639 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3640 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003641 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3642 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003643 clang_disposeString(SearchFileName);
3644 clang_disposeString(ResultFileName);
3645 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003646 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003647
3648 CXCursor Definition = clang_getCursorDefinition(Result);
3649 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3650 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3651 CXString DefinitionKindSpelling
3652 = clang_getCursorKindSpelling(Definition.kind);
3653 CXFile DefinitionFile;
3654 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003655 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3656 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003657 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3658 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3659 clang_getCString(DefinitionKindSpelling),
3660 clang_getCString(DefinitionFileName),
3661 DefinitionLine, DefinitionColumn);
3662 clang_disposeString(DefinitionFileName);
3663 clang_disposeString(DefinitionKindSpelling);
3664 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003665 }
3666
Ted Kremeneke68fff62010-02-17 00:41:32 +00003667 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003668}
3669
Ted Kremenek73885552009-11-17 19:28:59 +00003670CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003671 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003672}
3673
3674unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003675 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003676}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003677
Douglas Gregor9ce55842010-11-20 00:09:34 +00003678unsigned clang_hashCursor(CXCursor C) {
3679 unsigned Index = 0;
3680 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3681 Index = 1;
3682
3683 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3684 std::make_pair(C.kind, C.data[Index]));
3685}
3686
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003687unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003688 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3689}
3690
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003691unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003692 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3693}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003694
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003695unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003696 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3697}
3698
Douglas Gregor97b98722010-01-19 23:20:36 +00003699unsigned clang_isExpression(enum CXCursorKind K) {
3700 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3701}
3702
3703unsigned clang_isStatement(enum CXCursorKind K) {
3704 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3705}
3706
Douglas Gregor8be80e12011-07-06 03:00:34 +00003707unsigned clang_isAttribute(enum CXCursorKind K) {
3708 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3709}
3710
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003711unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3712 return K == CXCursor_TranslationUnit;
3713}
3714
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003715unsigned clang_isPreprocessing(enum CXCursorKind K) {
3716 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3717}
3718
Ted Kremenekad6eff62010-03-08 21:17:29 +00003719unsigned clang_isUnexposed(enum CXCursorKind K) {
3720 switch (K) {
3721 case CXCursor_UnexposedDecl:
3722 case CXCursor_UnexposedExpr:
3723 case CXCursor_UnexposedStmt:
3724 case CXCursor_UnexposedAttr:
3725 return true;
3726 default:
3727 return false;
3728 }
3729}
3730
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003731CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003732 return C.kind;
3733}
3734
Douglas Gregor98258af2010-01-18 22:46:11 +00003735CXSourceLocation clang_getCursorLocation(CXCursor C) {
3736 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003737 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003738 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003739 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3740 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003741 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003742 }
3743
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003744 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003745 std::pair<ObjCProtocolDecl *, SourceLocation> P
3746 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003747 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003748 }
3749
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003750 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003751 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3752 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003753 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003754 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003755
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003756 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003757 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003758 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003759 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003760
3761 case CXCursor_TemplateRef: {
3762 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3763 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3764 }
3765
Douglas Gregor69319002010-08-31 23:48:11 +00003766 case CXCursor_NamespaceRef: {
3767 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3768 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3769 }
3770
Douglas Gregora67e03f2010-09-09 21:42:20 +00003771 case CXCursor_MemberRef: {
3772 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3773 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3774 }
3775
Ted Kremenek3064ef92010-08-27 21:34:58 +00003776 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003777 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3778 if (!BaseSpec)
3779 return clang_getNullLocation();
3780
3781 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3782 return cxloc::translateSourceLocation(getCursorContext(C),
3783 TSInfo->getTypeLoc().getBeginLoc());
3784
3785 return cxloc::translateSourceLocation(getCursorContext(C),
3786 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003787 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003788
Douglas Gregor36897b02010-09-10 00:22:18 +00003789 case CXCursor_LabelRef: {
3790 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3791 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3792 }
3793
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003794 case CXCursor_OverloadedDeclRef:
3795 return cxloc::translateSourceLocation(getCursorContext(C),
3796 getCursorOverloadedDeclRef(C).second);
3797
Douglas Gregorf46034a2010-01-18 23:41:10 +00003798 default:
3799 // FIXME: Need a way to enumerate all non-reference cases.
3800 llvm_unreachable("Missed a reference kind");
3801 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003802 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003803
3804 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003805 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003806 getLocationFromExpr(getCursorExpr(C)));
3807
Douglas Gregor36897b02010-09-10 00:22:18 +00003808 if (clang_isStatement(C.kind))
3809 return cxloc::translateSourceLocation(getCursorContext(C),
3810 getCursorStmt(C)->getLocStart());
3811
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003812 if (C.kind == CXCursor_PreprocessingDirective) {
3813 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3814 return cxloc::translateSourceLocation(getCursorContext(C), L);
3815 }
Douglas Gregor48072312010-03-18 15:23:44 +00003816
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003817 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003818 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003819 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003820 return cxloc::translateSourceLocation(getCursorContext(C), L);
3821 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003822
3823 if (C.kind == CXCursor_MacroDefinition) {
3824 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3825 return cxloc::translateSourceLocation(getCursorContext(C), L);
3826 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003827
3828 if (C.kind == CXCursor_InclusionDirective) {
3829 SourceLocation L
3830 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3831 return cxloc::translateSourceLocation(getCursorContext(C), L);
3832 }
3833
Ted Kremenek9a700d22010-05-12 06:16:13 +00003834 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003835 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003836
Douglas Gregorf46034a2010-01-18 23:41:10 +00003837 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003838 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003839 // FIXME: Multiple variables declared in a single declaration
3840 // currently lack the information needed to correctly determine their
3841 // ranges when accounting for the type-specifier. We use context
3842 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3843 // and if so, whether it is the first decl.
3844 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3845 if (!cxcursor::isFirstInDeclGroup(C))
3846 Loc = VD->getLocation();
3847 }
3848
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003849 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003850}
Douglas Gregora7bde202010-01-19 00:34:46 +00003851
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003852} // end extern "C"
3853
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003854CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3855 assert(TU);
3856
3857 // Guard against an invalid SourceLocation, or we may assert in one
3858 // of the following calls.
3859 if (SLoc.isInvalid())
3860 return clang_getNullCursor();
3861
3862 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3863
3864 // Translate the given source location to make it point at the beginning of
3865 // the token under the cursor.
3866 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3867 CXXUnit->getASTContext().getLangOptions());
3868
3869 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3870 if (SLoc.isValid()) {
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003871 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003872 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3873 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00003874 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003875 SourceLocation(SLoc));
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00003876 CursorVis.visitFileRegion();
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003877 }
3878
3879 return Result;
3880}
3881
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003882static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003883 if (clang_isReference(C.kind)) {
3884 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003885 case CXCursor_ObjCSuperClassRef:
3886 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003888 case CXCursor_ObjCProtocolRef:
3889 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003890
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003891 case CXCursor_ObjCClassRef:
3892 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003893
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003894 case CXCursor_TypeRef:
3895 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003896
3897 case CXCursor_TemplateRef:
3898 return getCursorTemplateRef(C).second;
3899
Douglas Gregor69319002010-08-31 23:48:11 +00003900 case CXCursor_NamespaceRef:
3901 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003902
3903 case CXCursor_MemberRef:
3904 return getCursorMemberRef(C).second;
3905
Ted Kremenek3064ef92010-08-27 21:34:58 +00003906 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003907 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003908
Douglas Gregor36897b02010-09-10 00:22:18 +00003909 case CXCursor_LabelRef:
3910 return getCursorLabelRef(C).second;
3911
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003912 case CXCursor_OverloadedDeclRef:
3913 return getCursorOverloadedDeclRef(C).second;
3914
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003915 default:
3916 // FIXME: Need a way to enumerate all non-reference cases.
3917 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003918 }
3919 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003920
3921 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003922 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003923
3924 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003925 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003926
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003927 if (clang_isAttribute(C.kind))
3928 return getCursorAttr(C)->getRange();
3929
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003930 if (C.kind == CXCursor_PreprocessingDirective)
3931 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003932
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003933 if (C.kind == CXCursor_MacroExpansion) {
3934 ASTUnit *TU = getCursorASTUnit(C);
3935 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3936 return TU->mapRangeFromPreamble(Range);
3937 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003938
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003939 if (C.kind == CXCursor_MacroDefinition) {
3940 ASTUnit *TU = getCursorASTUnit(C);
3941 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3942 return TU->mapRangeFromPreamble(Range);
3943 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003944
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003945 if (C.kind == CXCursor_InclusionDirective) {
3946 ASTUnit *TU = getCursorASTUnit(C);
3947 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3948 return TU->mapRangeFromPreamble(Range);
3949 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003950
Ted Kremenek007a7c92010-11-01 23:26:51 +00003951 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3952 Decl *D = cxcursor::getCursorDecl(C);
3953 SourceRange R = D->getSourceRange();
3954 // FIXME: Multiple variables declared in a single declaration
3955 // currently lack the information needed to correctly determine their
3956 // ranges when accounting for the type-specifier. We use context
3957 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3958 // and if so, whether it is the first decl.
3959 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3960 if (!cxcursor::isFirstInDeclGroup(C))
3961 R.setBegin(VD->getLocation());
3962 }
3963 return R;
3964 }
Douglas Gregor66537982010-11-17 17:14:07 +00003965 return SourceRange();
3966}
3967
3968/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3969/// the decl-specifier-seq for declarations.
3970static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3971 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3972 Decl *D = cxcursor::getCursorDecl(C);
3973 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003974
Douglas Gregor2494dd02011-03-01 01:34:45 +00003975 // Adjust the start of the location for declarations preceded by
3976 // declaration specifiers.
3977 SourceLocation StartLoc;
3978 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3979 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3980 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3981 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3982 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3983 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3984 }
3985
3986 if (StartLoc.isValid() && R.getBegin().isValid() &&
3987 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3988 R.setBegin(StartLoc);
3989
3990 // FIXME: Multiple variables declared in a single declaration
3991 // currently lack the information needed to correctly determine their
3992 // ranges when accounting for the type-specifier. We use context
3993 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3994 // and if so, whether it is the first decl.
3995 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3996 if (!cxcursor::isFirstInDeclGroup(C))
3997 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003998 }
3999
4000 return R;
4001 }
4002
4003 return getRawCursorExtent(C);
4004}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004005
4006extern "C" {
4007
4008CXSourceRange clang_getCursorExtent(CXCursor C) {
4009 SourceRange R = getRawCursorExtent(C);
4010 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004011 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004012
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004013 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004014}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004015
4016CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004017 if (clang_isInvalid(C.kind))
4018 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004019
Ted Kremeneka60ed472010-11-16 08:15:36 +00004020 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004021 if (clang_isDeclaration(C.kind)) {
4022 Decl *D = getCursorDecl(C);
4023 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004024 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004025 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004026 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004027 if (ObjCForwardProtocolDecl *Protocols
4028 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004029 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004030 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004031 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4032 return MakeCXCursor(Property, tu);
4033
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004034 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004035 }
4036
Douglas Gregor97b98722010-01-19 23:20:36 +00004037 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004038 Expr *E = getCursorExpr(C);
4039 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004040 if (D) {
4041 CXCursor declCursor = MakeCXCursor(D, tu);
4042 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4043 declCursor);
4044 return declCursor;
4045 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004046
4047 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004048 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004049
Douglas Gregor97b98722010-01-19 23:20:36 +00004050 return clang_getNullCursor();
4051 }
4052
Douglas Gregor36897b02010-09-10 00:22:18 +00004053 if (clang_isStatement(C.kind)) {
4054 Stmt *S = getCursorStmt(C);
4055 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004056 if (LabelDecl *label = Goto->getLabel())
4057 if (LabelStmt *labelS = label->getStmt())
4058 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004059
4060 return clang_getNullCursor();
4061 }
4062
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004063 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004064 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004065 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004066 }
4067
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004068 if (!clang_isReference(C.kind))
4069 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004070
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004071 switch (C.kind) {
4072 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004073 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004074
4075 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004076 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004077
4078 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004079 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004080
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004081 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004083
4084 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004085 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004086
Douglas Gregor69319002010-08-31 23:48:11 +00004087 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004088 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004089
Douglas Gregora67e03f2010-09-09 21:42:20 +00004090 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004091 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004092
Ted Kremenek3064ef92010-08-27 21:34:58 +00004093 case CXCursor_CXXBaseSpecifier: {
4094 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4095 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004096 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004097 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004098
Douglas Gregor36897b02010-09-10 00:22:18 +00004099 case CXCursor_LabelRef:
4100 // FIXME: We end up faking the "parent" declaration here because we
4101 // don't want to make CXCursor larger.
4102 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004103 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4104 .getTranslationUnitDecl(),
4105 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004106
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004107 case CXCursor_OverloadedDeclRef:
4108 return C;
4109
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004110 default:
4111 // We would prefer to enumerate all non-reference cursor kinds here.
4112 llvm_unreachable("Unhandled reference cursor kind");
4113 break;
4114 }
4115 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004116
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004117 return clang_getNullCursor();
4118}
4119
Douglas Gregorb6998662010-01-19 19:34:47 +00004120CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004121 if (clang_isInvalid(C.kind))
4122 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004123
Ted Kremeneka60ed472010-11-16 08:15:36 +00004124 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004125
Douglas Gregorb6998662010-01-19 19:34:47 +00004126 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004127 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004128 C = clang_getCursorReferenced(C);
4129 WasReference = true;
4130 }
4131
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004132 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004133 return clang_getCursorReferenced(C);
4134
Douglas Gregorb6998662010-01-19 19:34:47 +00004135 if (!clang_isDeclaration(C.kind))
4136 return clang_getNullCursor();
4137
4138 Decl *D = getCursorDecl(C);
4139 if (!D)
4140 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004141
Douglas Gregorb6998662010-01-19 19:34:47 +00004142 switch (D->getKind()) {
4143 // Declaration kinds that don't really separate the notions of
4144 // declaration and definition.
4145 case Decl::Namespace:
4146 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004147 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004148 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004149 case Decl::TemplateTypeParm:
4150 case Decl::EnumConstant:
4151 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004152 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004153 case Decl::ObjCIvar:
4154 case Decl::ObjCAtDefsField:
4155 case Decl::ImplicitParam:
4156 case Decl::ParmVar:
4157 case Decl::NonTypeTemplateParm:
4158 case Decl::TemplateTemplateParm:
4159 case Decl::ObjCCategoryImpl:
4160 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004161 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004162 case Decl::LinkageSpec:
4163 case Decl::ObjCPropertyImpl:
4164 case Decl::FileScopeAsm:
4165 case Decl::StaticAssert:
4166 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004167 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004168 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004169 return C;
4170
4171 // Declaration kinds that don't make any sense here, but are
4172 // nonetheless harmless.
4173 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004174 break;
4175
4176 // Declaration kinds for which the definition is not resolvable.
4177 case Decl::UnresolvedUsingTypename:
4178 case Decl::UnresolvedUsingValue:
4179 break;
4180
4181 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004182 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004183 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004184
4185 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004186 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004187
4188 case Decl::Enum:
4189 case Decl::Record:
4190 case Decl::CXXRecord:
4191 case Decl::ClassTemplateSpecialization:
4192 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004193 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004194 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004195 return clang_getNullCursor();
4196
4197 case Decl::Function:
4198 case Decl::CXXMethod:
4199 case Decl::CXXConstructor:
4200 case Decl::CXXDestructor:
4201 case Decl::CXXConversion: {
4202 const FunctionDecl *Def = 0;
4203 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004204 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004205 return clang_getNullCursor();
4206 }
4207
4208 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004209 // Ask the variable if it has a definition.
4210 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004211 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004212 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004213 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004214
Douglas Gregorb6998662010-01-19 19:34:47 +00004215 case Decl::FunctionTemplate: {
4216 const FunctionDecl *Def = 0;
4217 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004218 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004219 return clang_getNullCursor();
4220 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004221
Douglas Gregorb6998662010-01-19 19:34:47 +00004222 case Decl::ClassTemplate: {
4223 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004224 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004225 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004226 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004227 return clang_getNullCursor();
4228 }
4229
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004230 case Decl::Using:
4231 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004232 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004233
4234 case Decl::UsingShadow:
4235 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004236 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004237 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004238
4239 case Decl::ObjCMethod: {
4240 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4241 if (Method->isThisDeclarationADefinition())
4242 return C;
4243
4244 // Dig out the method definition in the associated
4245 // @implementation, if we have it.
4246 // FIXME: The ASTs should make finding the definition easier.
4247 if (ObjCInterfaceDecl *Class
4248 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4249 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4250 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4251 Method->isInstanceMethod()))
4252 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004253 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004254
4255 return clang_getNullCursor();
4256 }
4257
4258 case Decl::ObjCCategory:
4259 if (ObjCCategoryImplDecl *Impl
4260 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004261 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004262 return clang_getNullCursor();
4263
4264 case Decl::ObjCProtocol:
4265 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4266 return C;
4267 return clang_getNullCursor();
4268
4269 case Decl::ObjCInterface:
4270 // There are two notions of a "definition" for an Objective-C
4271 // class: the interface and its implementation. When we resolved a
4272 // reference to an Objective-C class, produce the @interface as
4273 // the definition; when we were provided with the interface,
4274 // produce the @implementation as the definition.
4275 if (WasReference) {
4276 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4277 return C;
4278 } else if (ObjCImplementationDecl *Impl
4279 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004280 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004281 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004282
Douglas Gregorb6998662010-01-19 19:34:47 +00004283 case Decl::ObjCProperty:
4284 // FIXME: We don't really know where to find the
4285 // ObjCPropertyImplDecls that implement this property.
4286 return clang_getNullCursor();
4287
4288 case Decl::ObjCCompatibleAlias:
4289 if (ObjCInterfaceDecl *Class
4290 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4291 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004292 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004293
Douglas Gregorb6998662010-01-19 19:34:47 +00004294 return clang_getNullCursor();
4295
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004296 case Decl::ObjCForwardProtocol:
4297 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004298 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004299
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004300 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004301 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004302 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004303
4304 case Decl::Friend:
4305 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004306 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004307 return clang_getNullCursor();
4308
4309 case Decl::FriendTemplate:
4310 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004311 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004312 return clang_getNullCursor();
4313 }
4314
4315 return clang_getNullCursor();
4316}
4317
4318unsigned clang_isCursorDefinition(CXCursor C) {
4319 if (!clang_isDeclaration(C.kind))
4320 return 0;
4321
4322 return clang_getCursorDefinition(C) == C;
4323}
4324
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004325CXCursor clang_getCanonicalCursor(CXCursor C) {
4326 if (!clang_isDeclaration(C.kind))
4327 return C;
4328
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004329 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004330 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4331 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4332 return MakeCXCursor(CatD, getCursorTU(C));
4333
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004334 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4335 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4336 return MakeCXCursor(IFD, getCursorTU(C));
4337
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004338 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004339 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004340
4341 return C;
4342}
4343
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004344unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004345 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004346 return 0;
4347
4348 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4349 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4350 return E->getNumDecls();
4351
4352 if (OverloadedTemplateStorage *S
4353 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4354 return S->size();
4355
4356 Decl *D = Storage.get<Decl*>();
4357 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004358 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004359 if (isa<ObjCClassDecl>(D))
4360 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004361 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4362 return Protocols->protocol_size();
4363
4364 return 0;
4365}
4366
4367CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004368 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004369 return clang_getNullCursor();
4370
4371 if (index >= clang_getNumOverloadedDecls(cursor))
4372 return clang_getNullCursor();
4373
Ted Kremeneka60ed472010-11-16 08:15:36 +00004374 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004375 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4376 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004377 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004378
4379 if (OverloadedTemplateStorage *S
4380 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004381 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004382
4383 Decl *D = Storage.get<Decl*>();
4384 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4385 // FIXME: This is, unfortunately, linear time.
4386 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4387 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004388 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004389 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004390 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004391 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004392 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004393 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004394
4395 return clang_getNullCursor();
4396}
4397
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004398void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004399 const char **startBuf,
4400 const char **endBuf,
4401 unsigned *startLine,
4402 unsigned *startColumn,
4403 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004404 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004405 assert(getCursorDecl(C) && "CXCursor has null decl");
4406 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004407 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4408 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004409
Steve Naroff4ade6d62009-09-23 17:52:52 +00004410 SourceManager &SM = FD->getASTContext().getSourceManager();
4411 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4412 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4413 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4414 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4415 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4416 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4417}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004418
Douglas Gregor430d7a12011-07-25 17:48:11 +00004419
4420CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4421 unsigned PieceIndex) {
4422 RefNamePieces Pieces;
4423
4424 switch (C.kind) {
4425 case CXCursor_MemberRefExpr:
4426 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4427 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4428 E->getQualifierLoc().getSourceRange());
4429 break;
4430
4431 case CXCursor_DeclRefExpr:
4432 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4433 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4434 E->getQualifierLoc().getSourceRange(),
4435 E->getExplicitTemplateArgsOpt());
4436 break;
4437
4438 case CXCursor_CallExpr:
4439 if (CXXOperatorCallExpr *OCE =
4440 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4441 Expr *Callee = OCE->getCallee();
4442 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4443 Callee = ICE->getSubExpr();
4444
4445 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4446 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4447 DRE->getQualifierLoc().getSourceRange());
4448 }
4449 break;
4450
4451 default:
4452 break;
4453 }
4454
4455 if (Pieces.empty()) {
4456 if (PieceIndex == 0)
4457 return clang_getCursorExtent(C);
4458 } else if (PieceIndex < Pieces.size()) {
4459 SourceRange R = Pieces[PieceIndex];
4460 if (R.isValid())
4461 return cxloc::translateSourceRange(getCursorContext(C), R);
4462 }
4463
4464 return clang_getNullRange();
4465}
4466
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004467void clang_enableStackTraces(void) {
4468 llvm::sys::PrintStackTraceOnErrorSignal();
4469}
4470
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004471void clang_executeOnThread(void (*fn)(void*), void *user_data,
4472 unsigned stack_size) {
4473 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4474}
4475
Ted Kremenekfb480492010-01-13 21:46:36 +00004476} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004477
Ted Kremenekfb480492010-01-13 21:46:36 +00004478//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004479// Token-based Operations.
4480//===----------------------------------------------------------------------===//
4481
4482/* CXToken layout:
4483 * int_data[0]: a CXTokenKind
4484 * int_data[1]: starting token location
4485 * int_data[2]: token length
4486 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004487 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004488 * otherwise unused.
4489 */
4490extern "C" {
4491
4492CXTokenKind clang_getTokenKind(CXToken CXTok) {
4493 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4494}
4495
4496CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4497 switch (clang_getTokenKind(CXTok)) {
4498 case CXToken_Identifier:
4499 case CXToken_Keyword:
4500 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004501 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4502 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004503
4504 case CXToken_Literal: {
4505 // We have stashed the starting pointer in the ptr_data field. Use it.
4506 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004507 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004508 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004509
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004510 case CXToken_Punctuation:
4511 case CXToken_Comment:
4512 break;
4513 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004514
4515 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004516 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004517 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004518 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004519 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004520
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004521 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4522 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004523 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004524 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004525 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004526 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4527 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004528 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004529
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004530 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004531}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004532
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004533CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004534 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004535 if (!CXXUnit)
4536 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004537
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004538 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4539 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4540}
4541
4542CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004543 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004544 if (!CXXUnit)
4545 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004546
4547 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004548 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4549}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004550
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004551static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4552 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004553 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4554 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004555 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004556 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004557 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004558
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004559 // Cannot tokenize across files.
4560 if (BeginLocInfo.first != EndLocInfo.first)
4561 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004562
4563 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004564 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004565 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004566 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004567 if (Invalid)
4568 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004569
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004570 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4571 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004572 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004573 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004574
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004575 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004576 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004577 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004578 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004579 do {
4580 // Lex the next token
4581 Lex.LexFromRawLexer(Tok);
4582 if (Tok.is(tok::eof))
4583 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004584
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004585 // Initialize the CXToken.
4586 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004587
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004588 // - Common fields
4589 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4590 CXTok.int_data[2] = Tok.getLength();
4591 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004592
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004593 // - Kind-specific fields
4594 if (Tok.isLiteral()) {
4595 CXTok.int_data[0] = CXToken_Literal;
4596 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004597 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004598 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004599 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004600 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004601
David Chisnall096428b2010-10-13 21:44:48 +00004602 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004603 CXTok.int_data[0] = CXToken_Keyword;
4604 }
4605 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004606 CXTok.int_data[0] = Tok.is(tok::identifier)
4607 ? CXToken_Identifier
4608 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004609 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004610 CXTok.ptr_data = II;
4611 } else if (Tok.is(tok::comment)) {
4612 CXTok.int_data[0] = CXToken_Comment;
4613 CXTok.ptr_data = 0;
4614 } else {
4615 CXTok.int_data[0] = CXToken_Punctuation;
4616 CXTok.ptr_data = 0;
4617 }
4618 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004619 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004620 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004621}
4622
4623void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4624 CXToken **Tokens, unsigned *NumTokens) {
4625 if (Tokens)
4626 *Tokens = 0;
4627 if (NumTokens)
4628 *NumTokens = 0;
4629
4630 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4631 if (!CXXUnit || !Tokens || !NumTokens)
4632 return;
4633
4634 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4635
4636 SourceRange R = cxloc::translateCXSourceRange(Range);
4637 if (R.isInvalid())
4638 return;
4639
4640 SmallVector<CXToken, 32> CXTokens;
4641 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004642
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004643 if (CXTokens.empty())
4644 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004645
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004646 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4647 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4648 *NumTokens = CXTokens.size();
4649}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004650
Ted Kremenek6db61092010-05-05 00:55:15 +00004651void clang_disposeTokens(CXTranslationUnit TU,
4652 CXToken *Tokens, unsigned NumTokens) {
4653 free(Tokens);
4654}
4655
4656} // end: extern "C"
4657
4658//===----------------------------------------------------------------------===//
4659// Token annotation APIs.
4660//===----------------------------------------------------------------------===//
4661
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004662typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004663static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4664 CXCursor parent,
4665 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004666namespace {
4667class AnnotateTokensWorker {
4668 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004669 CXToken *Tokens;
4670 CXCursor *Cursors;
4671 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004672 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004673 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004674 CursorVisitor AnnotateVis;
4675 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004676 bool HasContextSensitiveKeywords;
4677
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004678 bool MoreTokens() const { return TokIdx < NumTokens; }
4679 unsigned NextToken() const { return TokIdx; }
4680 void AdvanceToken() { ++TokIdx; }
4681 SourceLocation GetTokenLoc(unsigned tokI) {
4682 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4683 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004684 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004685 return Tokens[tokI].int_data[3] != 0;
4686 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004687 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004688 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4689 }
4690
4691 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004692 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4693 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004694
Ted Kremenek6db61092010-05-05 00:55:15 +00004695public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004696 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004697 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004698 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004699 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004700 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004701 AnnotateVis(tu,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004702 AnnotateTokensVisitor, this,
4703 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00004704 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004705 RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004706 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4707 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004708
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004709 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004710 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004711 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004712 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004713 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004714 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004715
4716 /// \brief Determine whether the annotator saw any cursors that have
4717 /// context-sensitive keywords.
4718 bool hasContextSensitiveKeywords() const {
4719 return HasContextSensitiveKeywords;
4720 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004721};
4722}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004723
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004724void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4725 // Walk the AST within the region of interest, annotating tokens
4726 // along the way.
4727 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004728
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004729 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4730 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004731 if (Pos != Annotated.end() &&
4732 (clang_isInvalid(Cursors[I].kind) ||
4733 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004734 Cursors[I] = Pos->second;
4735 }
4736
4737 // Finish up annotating any tokens left.
4738 if (!MoreTokens())
4739 return;
4740
4741 const CXCursor &C = clang_getNullCursor();
4742 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4743 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4744 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004745 }
4746}
4747
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004748/// \brief It annotates and advances tokens with a cursor until the comparison
4749//// between the cursor location and the source range is the same as
4750/// \arg compResult.
4751///
4752/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4753/// Pass RangeOverlap to annotate tokens inside a range.
4754void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4755 RangeComparisonResult compResult,
4756 SourceRange range) {
4757 while (MoreTokens()) {
4758 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004759 if (isFunctionMacroToken(I))
4760 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004761
4762 SourceLocation TokLoc = GetTokenLoc(I);
4763 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4764 Cursors[I] = updateC;
4765 AdvanceToken();
4766 continue;
4767 }
4768 break;
4769 }
4770}
4771
4772/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004773void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4774 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004775 RangeComparisonResult compResult,
4776 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004777 assert(MoreTokens());
4778 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004779 "Should be called only for macro arg tokens");
4780
4781 // This works differently than annotateAndAdvanceTokens; because expanded
4782 // macro arguments can have arbitrary translation-unit source order, we do not
4783 // advance the token index one by one until a token fails the range test.
4784 // We only advance once past all of the macro arg tokens if all of them
4785 // pass the range test. If one of them fails we keep the token index pointing
4786 // at the start of the macro arg tokens so that the failing token will be
4787 // annotated by a subsequent annotation try.
4788
4789 bool atLeastOneCompFail = false;
4790
4791 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004792 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4793 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004794 if (TokLoc.isFileID())
4795 continue; // not macro arg token, it's parens or comma.
4796 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4797 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4798 Cursors[I] = updateC;
4799 } else
4800 atLeastOneCompFail = true;
4801 }
4802
4803 if (!atLeastOneCompFail)
4804 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4805}
4806
Ted Kremenek6db61092010-05-05 00:55:15 +00004807enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004808AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004809 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004810 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004811 if (cursorRange.isInvalid())
4812 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004813
4814 if (!HasContextSensitiveKeywords) {
4815 // Objective-C properties can have context-sensitive keywords.
4816 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4817 if (ObjCPropertyDecl *Property
4818 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4819 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4820 }
4821 // Objective-C methods can have context-sensitive keywords.
4822 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4823 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4824 if (ObjCMethodDecl *Method
4825 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4826 if (Method->getObjCDeclQualifier())
4827 HasContextSensitiveKeywords = true;
4828 else {
4829 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4830 PEnd = Method->param_end();
4831 P != PEnd; ++P) {
4832 if ((*P)->getObjCDeclQualifier()) {
4833 HasContextSensitiveKeywords = true;
4834 break;
4835 }
4836 }
4837 }
4838 }
4839 }
4840 // C++ methods can have context-sensitive keywords.
4841 else if (cursor.kind == CXCursor_CXXMethod) {
4842 if (CXXMethodDecl *Method
4843 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4844 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4845 HasContextSensitiveKeywords = true;
4846 }
4847 }
4848 // C++ classes can have context-sensitive keywords.
4849 else if (cursor.kind == CXCursor_StructDecl ||
4850 cursor.kind == CXCursor_ClassDecl ||
4851 cursor.kind == CXCursor_ClassTemplate ||
4852 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4853 if (Decl *D = getCursorDecl(cursor))
4854 if (D->hasAttr<FinalAttr>())
4855 HasContextSensitiveKeywords = true;
4856 }
4857 }
4858
Douglas Gregor4419b672010-10-21 06:10:04 +00004859 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004860 // For macro expansions, just note where the beginning of the macro
4861 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004862 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004863 Annotated[Loc.int_data] = cursor;
4864 return CXChildVisit_Recurse;
4865 }
4866
Douglas Gregor4419b672010-10-21 06:10:04 +00004867 // Items in the preprocessing record are kept separate from items in
4868 // declarations, so we keep a separate token index.
4869 unsigned SavedTokIdx = TokIdx;
4870 TokIdx = PreprocessingTokIdx;
4871
4872 // Skip tokens up until we catch up to the beginning of the preprocessing
4873 // entry.
4874 while (MoreTokens()) {
4875 const unsigned I = NextToken();
4876 SourceLocation TokLoc = GetTokenLoc(I);
4877 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4878 case RangeBefore:
4879 AdvanceToken();
4880 continue;
4881 case RangeAfter:
4882 case RangeOverlap:
4883 break;
4884 }
4885 break;
4886 }
4887
4888 // Look at all of the tokens within this range.
4889 while (MoreTokens()) {
4890 const unsigned I = NextToken();
4891 SourceLocation TokLoc = GetTokenLoc(I);
4892 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4893 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004894 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004895 case RangeAfter:
4896 break;
4897 case RangeOverlap:
4898 Cursors[I] = cursor;
4899 AdvanceToken();
4900 continue;
4901 }
4902 break;
4903 }
4904
4905 // Save the preprocessing token index; restore the non-preprocessing
4906 // token index.
4907 PreprocessingTokIdx = TokIdx;
4908 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004909 return CXChildVisit_Recurse;
4910 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004911
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004912 if (cursorRange.isInvalid())
4913 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004914
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004915 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4916
Ted Kremeneka333c662010-05-12 05:29:33 +00004917 // Adjust the annotated range based specific declarations.
4918 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4919 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004920 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004921
4922 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004923 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004924 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4925 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4926 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4927 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4928 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004929 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004930
4931 if (StartLoc.isValid() && L.isValid() &&
4932 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4933 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004934 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004935
Ted Kremenek3f404602010-08-14 01:14:06 +00004936 // If the location of the cursor occurs within a macro instantiation, record
4937 // the spelling location of the cursor in our annotation map. We can then
4938 // paper over the token labelings during a post-processing step to try and
4939 // get cursor mappings for tokens that are the *arguments* of a macro
4940 // instantiation.
4941 if (L.isMacroID()) {
4942 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4943 // Only invalidate the old annotation if it isn't part of a preprocessing
4944 // directive. Here we assume that the default construction of CXCursor
4945 // results in CXCursor.kind being an initialized value (i.e., 0). If
4946 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004947
Ted Kremenek3f404602010-08-14 01:14:06 +00004948 CXCursor &oldC = Annotated[rawEncoding];
4949 if (!clang_isPreprocessing(oldC.kind))
4950 oldC = cursor;
4951 }
4952
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004953 const enum CXCursorKind K = clang_getCursorKind(parent);
4954 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004955 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4956 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004957
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004958 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004959
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004960 // Avoid having the cursor of an expression "overwrite" the annotation of the
4961 // variable declaration that it belongs to.
4962 // This can happen for C++ constructor expressions whose range generally
4963 // include the variable declaration, e.g.:
4964 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4965 if (clang_isExpression(cursorK)) {
4966 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004967 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004968 const unsigned I = NextToken();
4969 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4970 E->getLocStart() == D->getLocation() &&
4971 E->getLocStart() == GetTokenLoc(I)) {
4972 Cursors[I] = updateC;
4973 AdvanceToken();
4974 }
4975 }
4976 }
4977
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004978 // Visit children to get their cursor information.
4979 const unsigned BeforeChildren = NextToken();
4980 VisitChildren(cursor);
4981 const unsigned AfterChildren = NextToken();
4982
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004983 // Scan the tokens that are at the end of the cursor, but are not captured
4984 // but the child cursors.
4985 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004986
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004987 // Scan the tokens that are at the beginning of the cursor, but are not
4988 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004989 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4990 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4991 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004992
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004993 Cursors[I] = cursor;
4994 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004995
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004996 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004997}
4998
Ted Kremenek6db61092010-05-05 00:55:15 +00004999static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5000 CXCursor parent,
5001 CXClientData client_data) {
5002 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5003}
5004
Ted Kremenek6628a612011-03-18 22:51:30 +00005005namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005006
5007/// \brief Uses the macro expansions in the preprocessing record to find
5008/// and mark tokens that are macro arguments. This info is used by the
5009/// AnnotateTokensWorker.
5010class MarkMacroArgTokensVisitor {
5011 SourceManager &SM;
5012 CXToken *Tokens;
5013 unsigned NumTokens;
5014 unsigned CurIdx;
5015
5016public:
5017 MarkMacroArgTokensVisitor(SourceManager &SM,
5018 CXToken *tokens, unsigned numTokens)
5019 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5020
5021 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5022 if (cursor.kind != CXCursor_MacroExpansion)
5023 return CXChildVisit_Continue;
5024
5025 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5026 if (macroRange.getBegin() == macroRange.getEnd())
5027 return CXChildVisit_Continue; // it's not a function macro.
5028
5029 for (; CurIdx < NumTokens; ++CurIdx) {
5030 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5031 macroRange.getBegin()))
5032 break;
5033 }
5034
5035 if (CurIdx == NumTokens)
5036 return CXChildVisit_Break;
5037
5038 for (; CurIdx < NumTokens; ++CurIdx) {
5039 SourceLocation tokLoc = getTokenLoc(CurIdx);
5040 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5041 break;
5042
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005043 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005044 }
5045
5046 if (CurIdx == NumTokens)
5047 return CXChildVisit_Break;
5048
5049 return CXChildVisit_Continue;
5050 }
5051
5052private:
5053 SourceLocation getTokenLoc(unsigned tokI) {
5054 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5055 }
5056
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005057 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005058 // The third field is reserved and currently not used. Use it here
5059 // to mark macro arg expanded tokens with their expanded locations.
5060 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5061 }
5062};
5063
5064} // end anonymous namespace
5065
5066static CXChildVisitResult
5067MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5068 CXClientData client_data) {
5069 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5070 parent);
5071}
5072
5073namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005074 struct clang_annotateTokens_Data {
5075 CXTranslationUnit TU;
5076 ASTUnit *CXXUnit;
5077 CXToken *Tokens;
5078 unsigned NumTokens;
5079 CXCursor *Cursors;
5080 };
5081}
5082
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005083static void annotatePreprocessorTokens(CXTranslationUnit TU,
5084 SourceRange RegionOfInterest,
5085 AnnotateTokensData &Annotated) {
5086 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5087
5088 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5089 std::pair<FileID, unsigned> BeginLocInfo
5090 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5091 std::pair<FileID, unsigned> EndLocInfo
5092 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5093
5094 if (BeginLocInfo.first != EndLocInfo.first)
5095 return;
5096
5097 StringRef Buffer;
5098 bool Invalid = false;
5099 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5100 if (Buffer.empty() || Invalid)
5101 return;
5102
5103 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5104 CXXUnit->getASTContext().getLangOptions(),
5105 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5106 Buffer.end());
5107 Lex.SetCommentRetentionState(true);
5108
5109 // Lex tokens in raw mode until we hit the end of the range, to avoid
5110 // entering #includes or expanding macros.
5111 while (true) {
5112 Token Tok;
5113 Lex.LexFromRawLexer(Tok);
5114
5115 reprocess:
5116 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5117 // We have found a preprocessing directive. Gobble it up so that we
5118 // don't see it while preprocessing these tokens later, but keep track
5119 // of all of the token locations inside this preprocessing directive so
5120 // that we can annotate them appropriately.
5121 //
5122 // FIXME: Some simple tests here could identify macro definitions and
5123 // #undefs, to provide specific cursor kinds for those.
5124 SmallVector<SourceLocation, 32> Locations;
5125 do {
5126 Locations.push_back(Tok.getLocation());
5127 Lex.LexFromRawLexer(Tok);
5128 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5129
5130 using namespace cxcursor;
5131 CXCursor Cursor
5132 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5133 Locations.back()),
5134 TU);
5135 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5136 Annotated[Locations[I].getRawEncoding()] = Cursor;
5137 }
5138
5139 if (Tok.isAtStartOfLine())
5140 goto reprocess;
5141
5142 continue;
5143 }
5144
5145 if (Tok.is(tok::eof))
5146 break;
5147 }
5148}
5149
Ted Kremenekab979612010-11-11 08:05:23 +00005150// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005151static void clang_annotateTokensImpl(void *UserData) {
5152 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5153 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5154 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5155 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5156 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5157
5158 // Determine the region of interest, which contains all of the tokens.
5159 SourceRange RegionOfInterest;
5160 RegionOfInterest.setBegin(
5161 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5162 RegionOfInterest.setEnd(
5163 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5164 Tokens[NumTokens-1])));
5165
5166 // A mapping from the source locations found when re-lexing or traversing the
5167 // region of interest to the corresponding cursors.
5168 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005169
Ted Kremenek6628a612011-03-18 22:51:30 +00005170 // Relex the tokens within the source range to look for preprocessing
5171 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005172 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005173
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005174 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5175 // Search and mark tokens that are macro argument expansions.
5176 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5177 Tokens, NumTokens);
5178 CursorVisitor MacroArgMarker(TU,
5179 MarkMacroArgTokensVisitorDelegate, &Visitor,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005180 /*VisitPreprocessorLast=*/true,
Argyrios Kyrtzidise7098462011-10-31 07:19:54 +00005181 /*VisitIncludedEntities=*/false,
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00005182 RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005183 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5184 }
5185
Ted Kremenek6628a612011-03-18 22:51:30 +00005186 // Annotate all of the source locations in the region of interest that map to
5187 // a specific cursor.
5188 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5189 TU, RegionOfInterest);
5190
5191 // FIXME: We use a ridiculous stack size here because the data-recursion
5192 // algorithm uses a large stack frame than the non-data recursive version,
5193 // and AnnotationTokensWorker currently transforms the data-recursion
5194 // algorithm back into a traditional recursion by explicitly calling
5195 // VisitChildren(). We will need to remove this explicit recursive call.
5196 W.AnnotateTokens();
5197
5198 // If we ran into any entities that involve context-sensitive keywords,
5199 // take another pass through the tokens to mark them as such.
5200 if (W.hasContextSensitiveKeywords()) {
5201 for (unsigned I = 0; I != NumTokens; ++I) {
5202 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5203 continue;
5204
5205 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5206 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5207 if (ObjCPropertyDecl *Property
5208 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5209 if (Property->getPropertyAttributesAsWritten() != 0 &&
5210 llvm::StringSwitch<bool>(II->getName())
5211 .Case("readonly", true)
5212 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005213 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005214 .Case("readwrite", true)
5215 .Case("retain", true)
5216 .Case("copy", true)
5217 .Case("nonatomic", true)
5218 .Case("atomic", true)
5219 .Case("getter", true)
5220 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005221 .Case("strong", true)
5222 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005223 .Default(false))
5224 Tokens[I].int_data[0] = CXToken_Keyword;
5225 }
5226 continue;
5227 }
5228
5229 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5230 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5231 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5232 if (llvm::StringSwitch<bool>(II->getName())
5233 .Case("in", true)
5234 .Case("out", true)
5235 .Case("inout", true)
5236 .Case("oneway", true)
5237 .Case("bycopy", true)
5238 .Case("byref", true)
5239 .Default(false))
5240 Tokens[I].int_data[0] = CXToken_Keyword;
5241 continue;
5242 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005243
5244 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5245 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5246 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005247 continue;
5248 }
5249 }
5250 }
Ted Kremenekab979612010-11-11 08:05:23 +00005251}
5252
Ted Kremenek6db61092010-05-05 00:55:15 +00005253extern "C" {
5254
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005255void clang_annotateTokens(CXTranslationUnit TU,
5256 CXToken *Tokens, unsigned NumTokens,
5257 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005258
5259 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005260 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005261
Douglas Gregor4419b672010-10-21 06:10:04 +00005262 // Any token we don't specifically annotate will have a NULL cursor.
5263 CXCursor C = clang_getNullCursor();
5264 for (unsigned I = 0; I != NumTokens; ++I)
5265 Cursors[I] = C;
5266
Ted Kremeneka60ed472010-11-16 08:15:36 +00005267 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005268 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005269 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005270
Douglas Gregorbdf60622010-03-05 21:16:25 +00005271 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005272
5273 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005274 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005275 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005276 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005277 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5278 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005279}
Ted Kremenek6628a612011-03-18 22:51:30 +00005280
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005281} // end: extern "C"
5282
5283//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005284// Operations for querying linkage of a cursor.
5285//===----------------------------------------------------------------------===//
5286
5287extern "C" {
5288CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005289 if (!clang_isDeclaration(cursor.kind))
5290 return CXLinkage_Invalid;
5291
Ted Kremenek16b42592010-03-03 06:36:57 +00005292 Decl *D = cxcursor::getCursorDecl(cursor);
5293 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5294 switch (ND->getLinkage()) {
5295 case NoLinkage: return CXLinkage_NoLinkage;
5296 case InternalLinkage: return CXLinkage_Internal;
5297 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5298 case ExternalLinkage: return CXLinkage_External;
5299 };
5300
5301 return CXLinkage_Invalid;
5302}
5303} // end: extern "C"
5304
5305//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005306// Operations for querying language of a cursor.
5307//===----------------------------------------------------------------------===//
5308
5309static CXLanguageKind getDeclLanguage(const Decl *D) {
5310 switch (D->getKind()) {
5311 default:
5312 break;
5313 case Decl::ImplicitParam:
5314 case Decl::ObjCAtDefsField:
5315 case Decl::ObjCCategory:
5316 case Decl::ObjCCategoryImpl:
5317 case Decl::ObjCClass:
5318 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005319 case Decl::ObjCForwardProtocol:
5320 case Decl::ObjCImplementation:
5321 case Decl::ObjCInterface:
5322 case Decl::ObjCIvar:
5323 case Decl::ObjCMethod:
5324 case Decl::ObjCProperty:
5325 case Decl::ObjCPropertyImpl:
5326 case Decl::ObjCProtocol:
5327 return CXLanguage_ObjC;
5328 case Decl::CXXConstructor:
5329 case Decl::CXXConversion:
5330 case Decl::CXXDestructor:
5331 case Decl::CXXMethod:
5332 case Decl::CXXRecord:
5333 case Decl::ClassTemplate:
5334 case Decl::ClassTemplatePartialSpecialization:
5335 case Decl::ClassTemplateSpecialization:
5336 case Decl::Friend:
5337 case Decl::FriendTemplate:
5338 case Decl::FunctionTemplate:
5339 case Decl::LinkageSpec:
5340 case Decl::Namespace:
5341 case Decl::NamespaceAlias:
5342 case Decl::NonTypeTemplateParm:
5343 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005344 case Decl::TemplateTemplateParm:
5345 case Decl::TemplateTypeParm:
5346 case Decl::UnresolvedUsingTypename:
5347 case Decl::UnresolvedUsingValue:
5348 case Decl::Using:
5349 case Decl::UsingDirective:
5350 case Decl::UsingShadow:
5351 return CXLanguage_CPlusPlus;
5352 }
5353
5354 return CXLanguage_C;
5355}
5356
5357extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005358
5359enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5360 if (clang_isDeclaration(cursor.kind))
5361 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005362 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005363 return CXAvailability_Available;
5364
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005365 switch (D->getAvailability()) {
5366 case AR_Available:
5367 case AR_NotYetIntroduced:
5368 return CXAvailability_Available;
5369
5370 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005371 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005372
5373 case AR_Unavailable:
5374 return CXAvailability_NotAvailable;
5375 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005376 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005377
Douglas Gregor58ddb602010-08-23 23:00:57 +00005378 return CXAvailability_Available;
5379}
5380
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005381CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5382 if (clang_isDeclaration(cursor.kind))
5383 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5384
5385 return CXLanguage_Invalid;
5386}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005387
5388 /// \brief If the given cursor is the "templated" declaration
5389 /// descibing a class or function template, return the class or
5390 /// function template.
5391static Decl *maybeGetTemplateCursor(Decl *D) {
5392 if (!D)
5393 return 0;
5394
5395 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5396 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5397 return FunTmpl;
5398
5399 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5400 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5401 return ClassTmpl;
5402
5403 return D;
5404}
5405
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005406CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5407 if (clang_isDeclaration(cursor.kind)) {
5408 if (Decl *D = getCursorDecl(cursor)) {
5409 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005410 if (!DC)
5411 return clang_getNullCursor();
5412
5413 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5414 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005415 }
5416 }
5417
5418 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5419 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005420 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005421 }
5422
5423 return clang_getNullCursor();
5424}
5425
5426CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5427 if (clang_isDeclaration(cursor.kind)) {
5428 if (Decl *D = getCursorDecl(cursor)) {
5429 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005430 if (!DC)
5431 return clang_getNullCursor();
5432
5433 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5434 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005435 }
5436 }
5437
5438 // FIXME: Note that we can't easily compute the lexical context of a
5439 // statement or expression, so we return nothing.
5440 return clang_getNullCursor();
5441}
5442
Douglas Gregor9f592342010-10-01 20:25:15 +00005443void clang_getOverriddenCursors(CXCursor cursor,
5444 CXCursor **overridden,
5445 unsigned *num_overridden) {
5446 if (overridden)
5447 *overridden = 0;
5448 if (num_overridden)
5449 *num_overridden = 0;
5450 if (!overridden || !num_overridden)
5451 return;
5452
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005453 SmallVector<CXCursor, 8> Overridden;
5454 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005455
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005456 *num_overridden = Overridden.size();
5457 *overridden = new CXCursor [Overridden.size()];
5458 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005459}
5460
5461void clang_disposeOverriddenCursors(CXCursor *overridden) {
5462 delete [] overridden;
5463}
5464
Douglas Gregorecdcb882010-10-20 22:00:55 +00005465CXFile clang_getIncludedFile(CXCursor cursor) {
5466 if (cursor.kind != CXCursor_InclusionDirective)
5467 return 0;
5468
5469 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5470 return (void *)ID->getFile();
5471}
5472
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005473} // end: extern "C"
5474
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005475
5476//===----------------------------------------------------------------------===//
5477// C++ AST instrospection.
5478//===----------------------------------------------------------------------===//
5479
5480extern "C" {
5481unsigned clang_CXXMethod_isStatic(CXCursor C) {
5482 if (!clang_isDeclaration(C.kind))
5483 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005484
5485 CXXMethodDecl *Method = 0;
5486 Decl *D = cxcursor::getCursorDecl(C);
5487 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5488 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5489 else
5490 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5491 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005492}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005493
Douglas Gregor211924b2011-05-12 15:17:24 +00005494unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5495 if (!clang_isDeclaration(C.kind))
5496 return 0;
5497
5498 CXXMethodDecl *Method = 0;
5499 Decl *D = cxcursor::getCursorDecl(C);
5500 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5501 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5502 else
5503 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5504 return (Method && Method->isVirtual()) ? 1 : 0;
5505}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005506} // end: extern "C"
5507
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005508//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005509// Attribute introspection.
5510//===----------------------------------------------------------------------===//
5511
5512extern "C" {
5513CXType clang_getIBOutletCollectionType(CXCursor C) {
5514 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005515 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005516
5517 IBOutletCollectionAttr *A =
5518 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5519
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005520 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005521}
5522} // end: extern "C"
5523
5524//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005525// Inspecting memory usage.
5526//===----------------------------------------------------------------------===//
5527
Ted Kremenekf7870022011-04-20 16:41:07 +00005528typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005529
Ted Kremenekf7870022011-04-20 16:41:07 +00005530static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5531 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005532 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005533 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005534 entries.push_back(entry);
5535}
5536
5537extern "C" {
5538
Ted Kremenekf7870022011-04-20 16:41:07 +00005539const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005540 const char *str = "";
5541 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005542 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005543 str = "ASTContext: expressions, declarations, and types";
5544 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005545 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005546 str = "ASTContext: identifiers";
5547 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005548 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005549 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005550 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005551 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005552 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005553 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005554 case CXTUResourceUsage_SourceManagerContentCache:
5555 str = "SourceManager: content cache allocator";
5556 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005557 case CXTUResourceUsage_AST_SideTables:
5558 str = "ASTContext: side tables";
5559 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005560 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5561 str = "SourceManager: malloc'ed memory buffers";
5562 break;
5563 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5564 str = "SourceManager: mmap'ed memory buffers";
5565 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005566 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5567 str = "ExternalASTSource: malloc'ed memory buffers";
5568 break;
5569 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5570 str = "ExternalASTSource: mmap'ed memory buffers";
5571 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005572 case CXTUResourceUsage_Preprocessor:
5573 str = "Preprocessor: malloc'ed memory";
5574 break;
5575 case CXTUResourceUsage_PreprocessingRecord:
5576 str = "Preprocessor: PreprocessingRecord";
5577 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005578 case CXTUResourceUsage_SourceManager_DataStructures:
5579 str = "SourceManager: data structures and tables";
5580 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005581 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5582 str = "Preprocessor: header search tables";
5583 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005584 }
5585 return str;
5586}
5587
Ted Kremenekf7870022011-04-20 16:41:07 +00005588CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005589 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005590 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005591 return usage;
5592 }
5593
5594 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5595 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5596 ASTContext &astContext = astUnit->getASTContext();
5597
5598 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005599 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005600 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005601
5602 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005603 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005604 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5605
5606 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005607 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005608 (unsigned long) astContext.Selectors.getTotalMemory());
5609
Ted Kremenekba29bd22011-04-28 04:53:38 +00005610 // How much memory is used by ASTContext's side tables?
5611 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5612 (unsigned long) astContext.getSideTableAllocatedMemory());
5613
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005614 // How much memory is used for caching global code completion results?
5615 unsigned long completionBytes = 0;
5616 if (GlobalCodeCompletionAllocator *completionAllocator =
5617 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005618 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005619 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005620 createCXTUResourceUsageEntry(*entries,
5621 CXTUResourceUsage_GlobalCompletionResults,
5622 completionBytes);
5623
5624 // How much memory is being used by SourceManager's content cache?
5625 createCXTUResourceUsageEntry(*entries,
5626 CXTUResourceUsage_SourceManagerContentCache,
5627 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005628
5629 // How much memory is being used by the MemoryBuffer's in SourceManager?
5630 const SourceManager::MemoryBufferSizes &srcBufs =
5631 astUnit->getSourceManager().getMemoryBufferSizes();
5632
5633 createCXTUResourceUsageEntry(*entries,
5634 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5635 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005636 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005637 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5638 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005639 createCXTUResourceUsageEntry(*entries,
5640 CXTUResourceUsage_SourceManager_DataStructures,
5641 (unsigned long) astContext.getSourceManager()
5642 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005643
5644 // How much memory is being used by the ExternalASTSource?
5645 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5646 const ExternalASTSource::MemoryBufferSizes &sizes =
5647 esrc->getMemoryBufferSizes();
5648
5649 createCXTUResourceUsageEntry(*entries,
5650 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5651 (unsigned long) sizes.malloc_bytes);
5652 createCXTUResourceUsageEntry(*entries,
5653 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5654 (unsigned long) sizes.mmap_bytes);
5655 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005656
5657 // How much memory is being used by the Preprocessor?
5658 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005659 createCXTUResourceUsageEntry(*entries,
5660 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005661 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005662
5663 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5664 createCXTUResourceUsageEntry(*entries,
5665 CXTUResourceUsage_PreprocessingRecord,
5666 pRec->getTotalMemory());
5667 }
5668
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005669 createCXTUResourceUsageEntry(*entries,
5670 CXTUResourceUsage_Preprocessor_HeaderSearch,
5671 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005672
Ted Kremenekf7870022011-04-20 16:41:07 +00005673 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005674 (unsigned) entries->size(),
5675 entries->size() ? &(*entries)[0] : 0 };
5676 entries.take();
5677 return usage;
5678}
5679
Ted Kremenekf7870022011-04-20 16:41:07 +00005680void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005681 if (usage.data)
5682 delete (MemUsageEntries*) usage.data;
5683}
5684
5685} // end extern "C"
5686
Douglas Gregor6df78732011-05-05 20:27:22 +00005687void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5688 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5689 for (unsigned I = 0; I != Usage.numEntries; ++I)
5690 fprintf(stderr, " %s: %lu\n",
5691 clang_getTUResourceUsageName(Usage.entries[I].kind),
5692 Usage.entries[I].amount);
5693
5694 clang_disposeCXTUResourceUsage(Usage);
5695}
5696
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005697//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005698// Misc. utility functions.
5699//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005700
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005701/// Default to using an 8 MB stack size on "safety" threads.
5702static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005703
5704namespace clang {
5705
5706bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005707 void (*Fn)(void*), void *UserData,
5708 unsigned Size) {
5709 if (!Size)
5710 Size = GetSafetyThreadStackSize();
5711 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005712 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5713 return CRC.RunSafely(Fn, UserData);
5714}
5715
5716unsigned GetSafetyThreadStackSize() {
5717 return SafetyStackThreadSize;
5718}
5719
5720void SetSafetyThreadStackSize(unsigned Value) {
5721 SafetyStackThreadSize = Value;
5722}
5723
5724}
5725
Ted Kremenek04bb7162010-01-22 22:44:15 +00005726extern "C" {
5727
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005728CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005729 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005730}
5731
5732} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005733