blob: bd3cac336087b0aa385567c7ee0c3ddb2e21641e [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;
Steve Naroff50398192009-08-28 15:28:48 +000054
Ted Kremeneka60ed472010-11-16 08:15:36 +000055static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
56 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
61 return D;
62}
63
Douglas Gregor33e9abd2010-01-22 19:49:59 +000064/// \brief The result of comparing two source ranges.
65enum RangeComparisonResult {
66 /// \brief Either the ranges overlap or one of the ranges is invalid.
67 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000068
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 /// \brief The first range ends before the second range starts.
70 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000071
Douglas Gregor33e9abd2010-01-22 19:49:59 +000072 /// \brief The first range starts after the second range ends.
73 RangeAfter
74};
75
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000078static RangeComparisonResult RangeCompare(SourceManager &SM,
79 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000080 SourceRange R2) {
81 assert(R1.isValid() && "First range is invalid?");
82 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000083 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000084 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000085 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000086 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000087 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000088 return RangeAfter;
89 return RangeOverlap;
90}
91
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000092/// \brief Determine if a source location falls within, before, or after a
93/// a given source range.
94static RangeComparisonResult LocationCompare(SourceManager &SM,
95 SourceLocation L, SourceRange R) {
96 assert(R.isValid() && "First range is invalid?");
97 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000098 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000099 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000100 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
101 return RangeBefore;
102 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
103 return RangeAfter;
104 return RangeOverlap;
105}
106
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107/// \brief Translate a Clang source range into a CIndex source range.
108///
109/// Clang internally represents ranges where the end location points to the
110/// start of the token at the end. However, for external clients it is more
111/// useful to have a CXSourceRange be a proper half-open interval. This routine
112/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000113CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000117 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000119 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000120 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000121 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000122 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000123 EndLoc = EndLoc.getFileLocWithOffset(Length);
124 }
125
126 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
127 R.getBegin().getRawEncoding(),
128 EndLoc.getRawEncoding() };
129 return Result;
130}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000131
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000133// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000134//===----------------------------------------------------------------------===//
135
Steve Naroff89922f82009-08-31 00:59:03 +0000136namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000137
138class VisitorJob {
139public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000140 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000141 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000142 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000143 ExplicitTemplateArgsVisitKind,
144 NestedNameSpecifierVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000145 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000146 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000147 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000148protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000150 CXCursor parent;
151 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000152 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
153 : parent(C), K(k) {
154 data[0] = d1;
155 data[1] = d2;
156 data[2] = d3;
157 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000158public:
159 Kind getKind() const { return K; }
160 const CXCursor &getParent() const { return parent; }
161 static bool classof(VisitorJob *VJ) { return true; }
162};
163
Chris Lattner5f9e2722011-07-23 10:55:15 +0000164typedef SmallVector<VisitorJob, 10> VisitorWorkList;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000165
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000167class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000168 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000169{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000171 CXTranslationUnit TU;
172 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000175 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000177 /// \brief The declaration that serves at the parent of any statement or
178 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000179 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000184 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000185 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000186
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000187 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
188 // to the visitor. Declarations with a PCH level greater than this value will
189 // be suppressed.
190 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +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;
195
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000196 /// \brief When valid, a source range to which the cursor should restrict
197 /// its search.
198 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000200 // FIXME: Eventually remove. This part of a hack to support proper
201 // iteration over all Decls contained lexically within an ObjC container.
202 DeclContext::decl_iterator *DI_current;
203 DeclContext::decl_iterator DE_current;
204
Ted Kremenekd1ded662010-11-15 23:31:32 +0000205 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000206 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
207 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000208
Douglas Gregorb1373d02010-01-20 20:59:29 +0000209 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000210 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
212 /// \brief Determine whether this particular source range comes before, comes
213 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000215 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000216 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
217
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000218 class SetParentRAII {
219 CXCursor &Parent;
220 Decl *&StmtParent;
221 CXCursor OldParent;
222
223 public:
224 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
225 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
226 {
227 Parent = NewParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231
232 ~SetParentRAII() {
233 Parent = OldParent;
234 if (clang_isDeclaration(Parent.kind))
235 StmtParent = getCursorDecl(Parent);
236 }
237 };
238
Steve Naroff89922f82009-08-31 00:59:03 +0000239public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000240 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
241 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242 unsigned MaxPCHLevel,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000243 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000244 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000245 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
246 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000247 MaxPCHLevel(MaxPCHLevel), VisitPreprocessorLast(VisitPreprocessorLast),
248 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000249 {
250 Parent.kind = CXCursor_NoDeclFound;
251 Parent.data[0] = 0;
252 Parent.data[1] = 0;
253 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000254 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000255 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000256
Ted Kremenekd1ded662010-11-15 23:31:32 +0000257 ~CursorVisitor() {
258 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000259 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000260 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
261 delete *I;
262 }
263 }
264
Ted Kremeneka60ed472010-11-16 08:15:36 +0000265 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
266 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000267
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000268 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000269
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000270 bool visitPreprocessedEntitiesInRegion();
271
272 template<typename InputIterator>
273 bool visitPreprocessedEntitiesInRegion(InputIterator First,
274 InputIterator Last);
275
276 template<typename InputIterator>
277 bool visitPreprocessedEntities(InputIterator First, InputIterator Last);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000278
Douglas Gregorb1373d02010-01-20 20:59:29 +0000279 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000280
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000281 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000282 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000283 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000284 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000285 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000286 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000287 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000288 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
289 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000291 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000292 bool VisitClassTemplatePartialSpecializationDecl(
293 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000294 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000295 bool VisitEnumConstantDecl(EnumConstantDecl *D);
296 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
297 bool VisitFunctionDecl(FunctionDecl *ND);
298 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000299 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000300 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000301 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000302 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000303 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000304 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
305 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
306 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
307 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000308 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000309 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
310 bool VisitObjCImplDecl(ObjCImplDecl *D);
311 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
312 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000313 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
314 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
315 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000316 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000317 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000318 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000319 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000320 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000321 bool VisitUsingDecl(UsingDecl *D);
322 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
323 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000324
Douglas Gregor01829d32010-08-31 14:41:23 +0000325 // Name visitor
326 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000327 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000328 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000329
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000330 // Template visitors
331 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000332 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000333 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
334
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000335 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000336 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000337 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000338 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000339 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
340 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000341 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000342 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000343 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000344 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000345 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000346 bool VisitPointerTypeLoc(PointerTypeLoc TL);
347 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
348 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
349 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
350 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +0000351 bool VisitAttributedTypeLoc(AttributedTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000352 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000353 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000354 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000355 // FIXME: Implement visitors here when the unimplemented TypeLocs get
356 // implemented
357 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000358 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000359 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Sean Huntca63c202011-05-24 22:41:36 +0000360 bool VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000361 bool VisitDependentNameTypeLoc(DependentNameTypeLoc TL);
Douglas Gregor94fdffa2011-03-01 20:11:18 +0000362 bool VisitDependentTemplateSpecializationTypeLoc(
363 DependentTemplateSpecializationTypeLoc TL);
Douglas Gregor9e876872011-03-01 18:12:44 +0000364 bool VisitElaboratedTypeLoc(ElaboratedTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000365
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000366 // Data-recursive visitor functions.
367 bool IsInRegionOfInterest(CXCursor C);
368 bool RunVisitorWorkList(VisitorWorkList &WL);
369 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000370 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000371};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000372
Ted Kremenekab188932010-01-05 19:32:54 +0000373} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000374
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000375static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000376static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
377
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000378
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000379RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000380 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381}
382
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383/// \brief Visit the given cursor and, if requested by the visitor,
384/// its children.
385///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000386/// \param Cursor the cursor to visit.
387///
388/// \param CheckRegionOfInterest if true, then the caller already checked that
389/// this cursor is within the region of interest.
390///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391/// \returns true if the visitation should be aborted, false if it
392/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000394 if (clang_isInvalid(Cursor.kind))
395 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000396
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397 if (clang_isDeclaration(Cursor.kind)) {
398 Decl *D = getCursorDecl(Cursor);
399 assert(D && "Invalid declaration cursor");
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +0000400 if (D->getPCHLevel() > MaxPCHLevel && !isa<TranslationUnitDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000401 return false;
402
403 if (D->isImplicit())
404 return false;
405 }
406
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000407 // If we have a range of interest, and this cursor doesn't intersect with it,
408 // we're done.
409 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000410 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000411 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000412 return false;
413 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000414
Douglas Gregorb1373d02010-01-20 20:59:29 +0000415 switch (Visitor(Cursor, Parent, ClientData)) {
416 case CXChildVisit_Break:
417 return true;
418
419 case CXChildVisit_Continue:
420 return false;
421
422 case CXChildVisit_Recurse:
423 return VisitChildren(Cursor);
424 }
425
Douglas Gregorfd643772010-01-25 16:45:46 +0000426 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427}
428
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000429bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000430 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000431 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000432
433 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000434 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
435
436 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
437 // If we would only look at local declarations but we have a region of
438 // interest, check whether that region of interest is in the main file.
439 // If not, we should traverse all declarations.
440 // FIXME: My kingdom for a proper binary search approach to finding
441 // cursors!
442 std::pair<FileID, unsigned> Location
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000443 = AU->getSourceManager().getDecomposedExpansionLoc(
Douglas Gregor32038bb2010-12-21 19:07:48 +0000444 RegionOfInterest.getBegin());
445 if (Location.first != AU->getSourceManager().getMainFileID())
446 OnlyLocalDecls = false;
447 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000448
Douglas Gregor89d99802010-11-30 06:16:57 +0000449 PreprocessingRecord::iterator StartEntity, EndEntity;
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000450 if (OnlyLocalDecls && AU->pp_entity_begin() != AU->pp_entity_end())
451 return visitPreprocessedEntitiesInRegion(AU->pp_entity_begin(),
452 AU->pp_entity_end());
453 else
454 return visitPreprocessedEntitiesInRegion(PPRec.begin(), PPRec.end());
455}
456
457template<typename InputIterator>
458bool CursorVisitor::visitPreprocessedEntitiesInRegion(InputIterator First,
459 InputIterator Last) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000460 // There is no region of interest; we have to walk everything.
461 if (RegionOfInterest.isInvalid())
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000462 return visitPreprocessedEntities(First, Last);
463
Douglas Gregor788f5a12010-03-20 00:41:21 +0000464 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000465 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000466 std::pair<FileID, unsigned> Begin
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000467 = SM.getDecomposedExpansionLoc(RegionOfInterest.getBegin());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000468 std::pair<FileID, unsigned> End
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000469 = SM.getDecomposedExpansionLoc(RegionOfInterest.getEnd());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000470
471 // The region of interest spans files; we have to walk everything.
472 if (Begin.first != End.first)
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000473 return visitPreprocessedEntities(First, Last);
474
Douglas Gregor788f5a12010-03-20 00:41:21 +0000475 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000476 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000477 if (ByFileMap.empty()) {
478 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000479 for (; First != Last; ++First) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000480 std::pair<FileID, unsigned> P
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000481 = SM.getDecomposedExpansionLoc((*First)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000482
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000483 ByFileMap[P.first].push_back(*First);
484 }
485 }
486
487 return visitPreprocessedEntities(ByFileMap[Begin.first].begin(),
488 ByFileMap[Begin.first].end());
489}
490
491template<typename InputIterator>
492bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
493 InputIterator Last) {
494 for (; First != Last; ++First) {
495 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
496 if (Visit(MakeMacroExpansionCursor(ME, TU)))
497 return true;
498
499 continue;
500 }
501
502 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
503 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
504 return true;
505
506 continue;
507 }
508
509 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
510 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
511 return true;
512
513 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000514 }
515 }
516
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000517 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000518}
519
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000521///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522/// \returns true if the visitation should be aborted, false if it
523/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000524bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000525 if (clang_isReference(Cursor.kind) &&
526 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000527 // By definition, references have no children.
528 return false;
529 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000530
531 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000532 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000533 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000534
Douglas Gregorb1373d02010-01-20 20:59:29 +0000535 if (clang_isDeclaration(Cursor.kind)) {
536 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000537 if (!D)
538 return false;
539
Ted Kremenek539311e2010-02-18 18:47:01 +0000540 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000542
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000543 if (clang_isStatement(Cursor.kind)) {
544 if (Stmt *S = getCursorStmt(Cursor))
545 return Visit(S);
546
547 return false;
548 }
549
550 if (clang_isExpression(Cursor.kind)) {
551 if (Expr *E = getCursorExpr(Cursor))
552 return Visit(E);
553
554 return false;
555 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000556
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000558 CXTranslationUnit tu = getCursorTU(Cursor);
559 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000560
561 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
562 for (unsigned I = 0; I != 2; ++I) {
563 if (VisitOrder[I]) {
564 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
565 RegionOfInterest.isInvalid()) {
566 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
567 TLEnd = CXXUnit->top_level_end();
568 TL != TLEnd; ++TL) {
569 if (Visit(MakeCXCursor(*TL, tu), true))
570 return true;
571 }
572 } else if (VisitDeclContext(
573 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000574 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000575 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000576 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000577
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000578 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000579 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
580 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000581 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000582
Douglas Gregor7b691f332010-01-20 21:13:59 +0000583 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000585
Douglas Gregorc314aa42011-03-02 19:17:03 +0000586 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
587 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
588 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
589 return Visit(BaseTSInfo->getTypeLoc());
590 }
591 }
592 }
593
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595 return false;
596}
597
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000598bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000599 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
600 if (Visit(TSInfo->getTypeLoc()))
601 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000602
Ted Kremenek664cffd2010-07-22 11:30:19 +0000603 if (Stmt *Body = B->getBody())
604 return Visit(MakeCXCursor(Body, StmtParent, TU));
605
606 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000607}
608
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000609llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
610 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000611 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000612 if (Range.isInvalid())
613 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000614
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000615 switch (CompareRegionOfInterest(Range)) {
616 case RangeBefore:
617 // This declaration comes before the region of interest; skip it.
618 return llvm::Optional<bool>();
619
620 case RangeAfter:
621 // This declaration comes after the region of interest; we're done.
622 return false;
623
624 case RangeOverlap:
625 // This declaration overlaps the region of interest; visit it.
626 break;
627 }
628 }
629 return true;
630}
631
632bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
633 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
634
635 // FIXME: Eventually remove. This part of a hack to support proper
636 // iteration over all Decls contained lexically within an ObjC container.
637 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
638 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
639
640 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000641 Decl *D = *I;
642 if (D->getLexicalDeclContext() != DC)
643 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000644 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000645 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
646 if (!V.hasValue())
647 continue;
648 if (!V.getValue())
649 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000650 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000651 return true;
652 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000653 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000654}
655
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000656bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
657 llvm_unreachable("Translation units are visited directly by Visit()");
658 return false;
659}
660
Richard Smith162e1c12011-04-15 14:24:37 +0000661bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
662 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
663 return Visit(TSInfo->getTypeLoc());
664
665 return false;
666}
667
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000668bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
669 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
670 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000671
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000672 return false;
673}
674
675bool CursorVisitor::VisitTagDecl(TagDecl *D) {
676 return VisitDeclContext(D);
677}
678
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000679bool CursorVisitor::VisitClassTemplateSpecializationDecl(
680 ClassTemplateSpecializationDecl *D) {
681 bool ShouldVisitBody = false;
682 switch (D->getSpecializationKind()) {
683 case TSK_Undeclared:
684 case TSK_ImplicitInstantiation:
685 // Nothing to visit
686 return false;
687
688 case TSK_ExplicitInstantiationDeclaration:
689 case TSK_ExplicitInstantiationDefinition:
690 break;
691
692 case TSK_ExplicitSpecialization:
693 ShouldVisitBody = true;
694 break;
695 }
696
697 // Visit the template arguments used in the specialization.
698 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
699 TypeLoc TL = SpecType->getTypeLoc();
700 if (TemplateSpecializationTypeLoc *TSTLoc
701 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
702 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
703 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
704 return true;
705 }
706 }
707
708 if (ShouldVisitBody && VisitCXXRecordDecl(D))
709 return true;
710
711 return false;
712}
713
Douglas Gregor74dbe642010-08-31 19:31:58 +0000714bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
715 ClassTemplatePartialSpecializationDecl *D) {
716 // FIXME: Visit the "outer" template parameter lists on the TagDecl
717 // before visiting these template parameters.
718 if (VisitTemplateParameters(D->getTemplateParameters()))
719 return true;
720
721 // Visit the partial specialization arguments.
722 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
723 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
724 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
725 return true;
726
727 return VisitCXXRecordDecl(D);
728}
729
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000730bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000731 // Visit the default argument.
732 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
733 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
734 if (Visit(DefArg->getTypeLoc()))
735 return true;
736
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000737 return false;
738}
739
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000740bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
741 if (Expr *Init = D->getInitExpr())
742 return Visit(MakeCXCursor(Init, StmtParent, TU));
743 return false;
744}
745
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000746bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
747 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
748 if (Visit(TSInfo->getTypeLoc()))
749 return true;
750
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000751 // Visit the nested-name-specifier, if present.
752 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
753 if (VisitNestedNameSpecifierLoc(QualifierLoc))
754 return true;
755
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000756 return false;
757}
758
Douglas Gregora67e03f2010-09-09 21:42:20 +0000759/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000760static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
761 CXXCtorInitializer const * const *X
762 = static_cast<CXXCtorInitializer const * const *>(Xp);
763 CXXCtorInitializer const * const *Y
764 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000765
766 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
767 return -1;
768 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
769 return 1;
770 else
771 return 0;
772}
773
Douglas Gregorb1373d02010-01-20 20:59:29 +0000774bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000775 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
776 // Visit the function declaration's syntactic components in the order
777 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000778 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000779 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
780
781 // If we have a function declared directly (without the use of a typedef),
782 // visit just the return type. Otherwise, just visit the function's type
783 // now.
784 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
785 (!FTL && Visit(TL)))
786 return true;
787
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000788 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000789 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
790 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000791 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000792
793 // Visit the declaration name.
794 if (VisitDeclarationNameInfo(ND->getNameInfo()))
795 return true;
796
797 // FIXME: Visit explicitly-specified template arguments!
798
799 // Visit the function parameters, if we have a function type.
800 if (FTL && VisitFunctionTypeLoc(*FTL, true))
801 return true;
802
803 // FIXME: Attributes?
804 }
805
Sean Hunt10620eb2011-05-06 20:44:56 +0000806 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000807 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
808 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000809 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000810 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
811 IEnd = Constructor->init_end();
812 I != IEnd; ++I) {
813 if (!(*I)->isWritten())
814 continue;
815
816 WrittenInits.push_back(*I);
817 }
818
819 // Sort the initializers in source order
820 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000821 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000822
823 // Visit the initializers in source order
824 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000825 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000826 if (Init->isAnyMemberInitializer()) {
827 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000828 Init->getMemberLocation(), TU)))
829 return true;
830 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
831 if (Visit(BaseInfo->getTypeLoc()))
832 return true;
833 }
834
835 // Visit the initializer value.
836 if (Expr *Initializer = Init->getInit())
837 if (Visit(MakeCXCursor(Initializer, ND, TU)))
838 return true;
839 }
840 }
841
842 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
843 return true;
844 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845
Douglas Gregorb1373d02010-01-20 20:59:29 +0000846 return false;
847}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000848
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
850 if (VisitDeclaratorDecl(D))
851 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853 if (Expr *BitWidth = D->getBitWidth())
854 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000855
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856 return false;
857}
858
859bool CursorVisitor::VisitVarDecl(VarDecl *D) {
860 if (VisitDeclaratorDecl(D))
861 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000862
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000863 if (Expr *Init = D->getInit())
864 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000865
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000866 return false;
867}
868
Douglas Gregor84b51d72010-09-01 20:16:53 +0000869bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
870 if (VisitDeclaratorDecl(D))
871 return true;
872
873 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
874 if (Expr *DefArg = D->getDefaultArgument())
875 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
876
877 return false;
878}
879
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000880bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
881 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
882 // before visiting these template parameters.
883 if (VisitTemplateParameters(D->getTemplateParameters()))
884 return true;
885
886 return VisitFunctionDecl(D->getTemplatedDecl());
887}
888
Douglas Gregor39d6f072010-08-31 19:02:00 +0000889bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
890 // FIXME: Visit the "outer" template parameter lists on the TagDecl
891 // before visiting these template parameters.
892 if (VisitTemplateParameters(D->getTemplateParameters()))
893 return true;
894
895 return VisitCXXRecordDecl(D->getTemplatedDecl());
896}
897
Douglas Gregor84b51d72010-09-01 20:16:53 +0000898bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
899 if (VisitTemplateParameters(D->getTemplateParameters()))
900 return true;
901
902 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
903 VisitTemplateArgumentLoc(D->getDefaultArgument()))
904 return true;
905
906 return false;
907}
908
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000909bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000910 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
911 if (Visit(TSInfo->getTypeLoc()))
912 return true;
913
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000914 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000915 PEnd = ND->param_end();
916 P != PEnd; ++P) {
917 if (Visit(MakeCXCursor(*P, TU)))
918 return true;
919 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000920
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000921 if (ND->isThisDeclarationADefinition() &&
922 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
923 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000924
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000925 return false;
926}
927
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000928namespace {
929 struct ContainerDeclsSort {
930 SourceManager &SM;
931 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
932 bool operator()(Decl *A, Decl *B) {
933 SourceLocation L_A = A->getLocStart();
934 SourceLocation L_B = B->getLocStart();
935 assert(L_A.isValid() && L_B.isValid());
936 return SM.isBeforeInTranslationUnit(L_A, L_B);
937 }
938 };
939}
940
Douglas Gregora59e3902010-01-21 23:27:09 +0000941bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000942 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
943 // an @implementation can lexically contain Decls that are not properly
944 // nested in the AST. When we identify such cases, we need to retrofit
945 // this nesting here.
946 if (!DI_current)
947 return VisitDeclContext(D);
948
949 // Scan the Decls that immediately come after the container
950 // in the current DeclContext. If any fall within the
951 // container's lexical region, stash them into a vector
952 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000953 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000954 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000955 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000956 if (EndLoc.isValid()) {
957 DeclContext::decl_iterator next = *DI_current;
958 while (++next != DE_current) {
959 Decl *D_next = *next;
960 if (!D_next)
961 break;
962 SourceLocation L = D_next->getLocStart();
963 if (!L.isValid())
964 break;
965 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
966 *DI_current = next;
967 DeclsInContainer.push_back(D_next);
968 continue;
969 }
970 break;
971 }
972 }
973
974 // The common case.
975 if (DeclsInContainer.empty())
976 return VisitDeclContext(D);
977
978 // Get all the Decls in the DeclContext, and sort them with the
979 // additional ones we've collected. Then visit them.
980 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
981 I!=E; ++I) {
982 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000983 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
984 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000985 continue;
986 DeclsInContainer.push_back(subDecl);
987 }
988
989 // Now sort the Decls so that they appear in lexical order.
990 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
991 ContainerDeclsSort(SM));
992
993 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000994 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000995 E = DeclsInContainer.end(); I != E; ++I) {
996 CXCursor Cursor = MakeCXCursor(*I, TU);
997 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
998 if (!V.hasValue())
999 continue;
1000 if (!V.getValue())
1001 return false;
1002 if (Visit(Cursor, true))
1003 return true;
1004 }
1005 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001006}
1007
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001009 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1010 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001013 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1014 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1015 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001016 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001017 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018
Douglas Gregora59e3902010-01-21 23:27:09 +00001019 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1023 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1024 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1025 E = PID->protocol_end(); I != E; ++I, ++PL)
1026 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1027 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029 return VisitObjCContainerDecl(PID);
1030}
1031
Ted Kremenek23173d72010-05-18 21:09:07 +00001032bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001033 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001034 return true;
1035
Ted Kremenek23173d72010-05-18 21:09:07 +00001036 // FIXME: This implements a workaround with @property declarations also being
1037 // installed in the DeclContext for the @interface. Eventually this code
1038 // should be removed.
1039 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1040 if (!CDecl || !CDecl->IsClassExtension())
1041 return false;
1042
1043 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1044 if (!ID)
1045 return false;
1046
1047 IdentifierInfo *PropertyId = PD->getIdentifier();
1048 ObjCPropertyDecl *prevDecl =
1049 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1050
1051 if (!prevDecl)
1052 return false;
1053
1054 // Visit synthesized methods since they will be skipped when visiting
1055 // the @interface.
1056 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001057 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001058 if (Visit(MakeCXCursor(MD, TU)))
1059 return true;
1060
1061 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001062 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001063 if (Visit(MakeCXCursor(MD, TU)))
1064 return true;
1065
1066 return false;
1067}
1068
Douglas Gregorb1373d02010-01-20 20:59:29 +00001069bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001070 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001071 if (D->getSuperClass() &&
1072 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001073 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001074 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001075 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001076
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001077 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1078 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1079 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001080 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001081 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001082
Douglas Gregora59e3902010-01-21 23:27:09 +00001083 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001084}
1085
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001086bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1087 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001088}
1089
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001090bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001091 // 'ID' could be null when dealing with invalid code.
1092 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1093 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1094 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001095
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001096 return VisitObjCImplDecl(D);
1097}
1098
1099bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1100#if 0
1101 // Issue callbacks for super class.
1102 // FIXME: No source location information!
1103 if (D->getSuperClass() &&
1104 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001105 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001106 TU)))
1107 return true;
1108#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001109
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001110 return VisitObjCImplDecl(D);
1111}
1112
1113bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1114 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1115 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1116 E = D->protocol_end();
1117 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001118 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001119 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001120
1121 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001122}
1123
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001124bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1125 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1126 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1127 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001128
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001129 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001130}
1131
Douglas Gregora4ffd852010-11-17 01:03:52 +00001132bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1133 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1134 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1135
1136 return false;
1137}
1138
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001139bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1140 return VisitDeclContext(D);
1141}
1142
Douglas Gregor69319002010-08-31 23:48:11 +00001143bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001144 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001145 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1146 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001147 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001148
1149 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1150 D->getTargetNameLoc(), TU));
1151}
1152
Douglas Gregor7e242562010-09-01 19:52:22 +00001153bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001154 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001155 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1156 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001157 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001158 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001159
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001160 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1161 return true;
1162
Douglas Gregor7e242562010-09-01 19:52:22 +00001163 return VisitDeclarationNameInfo(D->getNameInfo());
1164}
1165
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001166bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001167 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001168 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1169 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001170 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001171
1172 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1173 D->getIdentLocation(), TU));
1174}
1175
Douglas Gregor7e242562010-09-01 19:52:22 +00001176bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001177 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001178 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1179 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001180 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001181 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001182
Douglas Gregor7e242562010-09-01 19:52:22 +00001183 return VisitDeclarationNameInfo(D->getNameInfo());
1184}
1185
1186bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1187 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001188 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001189 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1190 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001191 return true;
1192
Douglas Gregor7e242562010-09-01 19:52:22 +00001193 return false;
1194}
1195
Douglas Gregor01829d32010-08-31 14:41:23 +00001196bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1197 switch (Name.getName().getNameKind()) {
1198 case clang::DeclarationName::Identifier:
1199 case clang::DeclarationName::CXXLiteralOperatorName:
1200 case clang::DeclarationName::CXXOperatorName:
1201 case clang::DeclarationName::CXXUsingDirective:
1202 return false;
1203
1204 case clang::DeclarationName::CXXConstructorName:
1205 case clang::DeclarationName::CXXDestructorName:
1206 case clang::DeclarationName::CXXConversionFunctionName:
1207 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1208 return Visit(TSInfo->getTypeLoc());
1209 return false;
1210
1211 case clang::DeclarationName::ObjCZeroArgSelector:
1212 case clang::DeclarationName::ObjCOneArgSelector:
1213 case clang::DeclarationName::ObjCMultiArgSelector:
1214 // FIXME: Per-identifier location info?
1215 return false;
1216 }
1217
1218 return false;
1219}
1220
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001221bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1222 SourceRange Range) {
1223 // FIXME: This whole routine is a hack to work around the lack of proper
1224 // source information in nested-name-specifiers (PR5791). Since we do have
1225 // a beginning source location, we can visit the first component of the
1226 // nested-name-specifier, if it's a single-token component.
1227 if (!NNS)
1228 return false;
1229
1230 // Get the first component in the nested-name-specifier.
1231 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1232 NNS = Prefix;
1233
1234 switch (NNS->getKind()) {
1235 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001236 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1237 TU));
1238
Douglas Gregor14aba762011-02-24 02:36:08 +00001239 case NestedNameSpecifier::NamespaceAlias:
1240 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1241 Range.getBegin(), TU));
1242
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001243 case NestedNameSpecifier::TypeSpec: {
1244 // If the type has a form where we know that the beginning of the source
1245 // range matches up with a reference cursor. Visit the appropriate reference
1246 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001247 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001248 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1249 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1250 if (const TagType *Tag = dyn_cast<TagType>(T))
1251 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1252 if (const TemplateSpecializationType *TST
1253 = dyn_cast<TemplateSpecializationType>(T))
1254 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1255 break;
1256 }
1257
1258 case NestedNameSpecifier::TypeSpecWithTemplate:
1259 case NestedNameSpecifier::Global:
1260 case NestedNameSpecifier::Identifier:
1261 break;
1262 }
1263
1264 return false;
1265}
1266
Douglas Gregordc355712011-02-25 00:36:19 +00001267bool
1268CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001269 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001270 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1271 Qualifiers.push_back(Qualifier);
1272
1273 while (!Qualifiers.empty()) {
1274 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1275 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1276 switch (NNS->getKind()) {
1277 case NestedNameSpecifier::Namespace:
1278 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001279 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001280 TU)))
1281 return true;
1282
1283 break;
1284
1285 case NestedNameSpecifier::NamespaceAlias:
1286 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001287 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001288 TU)))
1289 return true;
1290
1291 break;
1292
1293 case NestedNameSpecifier::TypeSpec:
1294 case NestedNameSpecifier::TypeSpecWithTemplate:
1295 if (Visit(Q.getTypeLoc()))
1296 return true;
1297
1298 break;
1299
1300 case NestedNameSpecifier::Global:
1301 case NestedNameSpecifier::Identifier:
1302 break;
1303 }
1304 }
1305
1306 return false;
1307}
1308
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001309bool CursorVisitor::VisitTemplateParameters(
1310 const TemplateParameterList *Params) {
1311 if (!Params)
1312 return false;
1313
1314 for (TemplateParameterList::const_iterator P = Params->begin(),
1315 PEnd = Params->end();
1316 P != PEnd; ++P) {
1317 if (Visit(MakeCXCursor(*P, TU)))
1318 return true;
1319 }
1320
1321 return false;
1322}
1323
Douglas Gregor0b36e612010-08-31 20:37:03 +00001324bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1325 switch (Name.getKind()) {
1326 case TemplateName::Template:
1327 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1328
1329 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001330 // Visit the overloaded template set.
1331 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1332 return true;
1333
Douglas Gregor0b36e612010-08-31 20:37:03 +00001334 return false;
1335
1336 case TemplateName::DependentTemplate:
1337 // FIXME: Visit nested-name-specifier.
1338 return false;
1339
1340 case TemplateName::QualifiedTemplate:
1341 // FIXME: Visit nested-name-specifier.
1342 return Visit(MakeCursorTemplateRef(
1343 Name.getAsQualifiedTemplateName()->getDecl(),
1344 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001345
1346 case TemplateName::SubstTemplateTemplateParm:
1347 return Visit(MakeCursorTemplateRef(
1348 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1349 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001350
1351 case TemplateName::SubstTemplateTemplateParmPack:
1352 return Visit(MakeCursorTemplateRef(
1353 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1354 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001355 }
1356
1357 return false;
1358}
1359
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001360bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1361 switch (TAL.getArgument().getKind()) {
1362 case TemplateArgument::Null:
1363 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001364 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001365 return false;
1366
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001367 case TemplateArgument::Type:
1368 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1369 return Visit(TSInfo->getTypeLoc());
1370 return false;
1371
1372 case TemplateArgument::Declaration:
1373 if (Expr *E = TAL.getSourceDeclExpression())
1374 return Visit(MakeCXCursor(E, StmtParent, TU));
1375 return false;
1376
1377 case TemplateArgument::Expression:
1378 if (Expr *E = TAL.getSourceExpression())
1379 return Visit(MakeCXCursor(E, StmtParent, TU));
1380 return false;
1381
1382 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001383 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001384 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1385 return true;
1386
Douglas Gregora7fc9012011-01-05 18:58:31 +00001387 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001388 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001389 }
1390
1391 return false;
1392}
1393
Ted Kremeneka0536d82010-05-07 01:04:29 +00001394bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1395 return VisitDeclContext(D);
1396}
1397
Douglas Gregor01829d32010-08-31 14:41:23 +00001398bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1399 return Visit(TL.getUnqualifiedLoc());
1400}
1401
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001402bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001403 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001404
1405 // Some builtin types (such as Objective-C's "id", "sel", and
1406 // "Class") have associated declarations. Create cursors for those.
1407 QualType VisitType;
1408 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001409 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001410 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001411 case BuiltinType::Char_U:
1412 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001413 case BuiltinType::Char16:
1414 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001415 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001416 case BuiltinType::UInt:
1417 case BuiltinType::ULong:
1418 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001419 case BuiltinType::UInt128:
1420 case BuiltinType::Char_S:
1421 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001422 case BuiltinType::WChar_U:
1423 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001424 case BuiltinType::Short:
1425 case BuiltinType::Int:
1426 case BuiltinType::Long:
1427 case BuiltinType::LongLong:
1428 case BuiltinType::Int128:
1429 case BuiltinType::Float:
1430 case BuiltinType::Double:
1431 case BuiltinType::LongDouble:
1432 case BuiltinType::NullPtr:
1433 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001434 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001435 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001436 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001437 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001438
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001439 case BuiltinType::ObjCId:
1440 VisitType = Context.getObjCIdType();
1441 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001442
1443 case BuiltinType::ObjCClass:
1444 VisitType = Context.getObjCClassType();
1445 break;
1446
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001447 case BuiltinType::ObjCSel:
1448 VisitType = Context.getObjCSelType();
1449 break;
1450 }
1451
1452 if (!VisitType.isNull()) {
1453 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455 TU));
1456 }
1457
1458 return false;
1459}
1460
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001461bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001462 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001463}
1464
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001465bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1466 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1467}
1468
1469bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1470 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1471}
1472
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001473bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001474 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001475}
1476
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001477bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1478 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1479 return true;
1480
John McCallc12c5bb2010-05-15 11:32:37 +00001481 return false;
1482}
1483
1484bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1485 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1486 return true;
1487
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001488 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1489 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1490 TU)))
1491 return true;
1492 }
1493
1494 return false;
1495}
1496
1497bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001498 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001499}
1500
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001501bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1502 return Visit(TL.getInnerLoc());
1503}
1504
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001505bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1506 return Visit(TL.getPointeeLoc());
1507}
1508
1509bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1510 return Visit(TL.getPointeeLoc());
1511}
1512
1513bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1514 return Visit(TL.getPointeeLoc());
1515}
1516
1517bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001518 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001519}
1520
1521bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001522 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001523}
1524
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001525bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1526 return Visit(TL.getModifiedLoc());
1527}
1528
Douglas Gregor01829d32010-08-31 14:41:23 +00001529bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1530 bool SkipResultType) {
1531 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001532 return true;
1533
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001534 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001535 if (Decl *D = TL.getArg(I))
1536 if (Visit(MakeCXCursor(D, TU)))
1537 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001538
1539 return false;
1540}
1541
1542bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1543 if (Visit(TL.getElementLoc()))
1544 return true;
1545
1546 if (Expr *Size = TL.getSizeExpr())
1547 return Visit(MakeCXCursor(Size, StmtParent, TU));
1548
1549 return false;
1550}
1551
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001552bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1553 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001554 // Visit the template name.
1555 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1556 TL.getTemplateNameLoc()))
1557 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001558
1559 // Visit the template arguments.
1560 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1561 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1562 return true;
1563
1564 return false;
1565}
1566
Douglas Gregor2332c112010-01-21 20:48:56 +00001567bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1568 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1569}
1570
1571bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1572 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1573 return Visit(TSInfo->getTypeLoc());
1574
1575 return false;
1576}
1577
Sean Huntca63c202011-05-24 22:41:36 +00001578bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1579 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1580 return Visit(TSInfo->getTypeLoc());
1581
1582 return false;
1583}
1584
Douglas Gregor2494dd02011-03-01 01:34:45 +00001585bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1586 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1587 return true;
1588
1589 return false;
1590}
1591
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001592bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1593 DependentTemplateSpecializationTypeLoc TL) {
1594 // Visit the nested-name-specifier, if there is one.
1595 if (TL.getQualifierLoc() &&
1596 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1597 return true;
1598
1599 // Visit the template arguments.
1600 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1601 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1602 return true;
1603
1604 return false;
1605}
1606
Douglas Gregor9e876872011-03-01 18:12:44 +00001607bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1608 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1609 return true;
1610
1611 return Visit(TL.getNamedTypeLoc());
1612}
1613
Douglas Gregor7536dd52010-12-20 02:24:11 +00001614bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1615 return Visit(TL.getPatternLoc());
1616}
1617
Ted Kremenek3064ef92010-08-27 21:34:58 +00001618bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001619 // Visit the nested-name-specifier, if present.
1620 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1621 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1622 return true;
1623
Ted Kremenek3064ef92010-08-27 21:34:58 +00001624 if (D->isDefinition()) {
1625 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1626 E = D->bases_end(); I != E; ++I) {
1627 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1628 return true;
1629 }
1630 }
1631
1632 return VisitTagDecl(D);
1633}
1634
Ted Kremenek09dfa372010-02-18 05:46:33 +00001635bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001636 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1637 i != e; ++i)
1638 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001639 return true;
1640
1641 return false;
1642}
1643
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001644//===----------------------------------------------------------------------===//
1645// Data-recursive visitor methods.
1646//===----------------------------------------------------------------------===//
1647
Ted Kremenek28a71942010-11-13 00:36:47 +00001648namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001649#define DEF_JOB(NAME, DATA, KIND)\
1650class NAME : public VisitorJob {\
1651public:\
1652 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1653 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001654 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001655};
1656
1657DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1658DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001659DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001660DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001661DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1662 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001663DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001664#undef DEF_JOB
1665
1666class DeclVisit : public VisitorJob {
1667public:
1668 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1669 VisitorJob(parent, VisitorJob::DeclVisitKind,
1670 d, isFirst ? (void*) 1 : (void*) 0) {}
1671 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001672 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001673 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001674 Decl *get() const { return static_cast<Decl*>(data[0]); }
1675 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001676};
Ted Kremenek035dc412010-11-13 00:36:50 +00001677class TypeLocVisit : public VisitorJob {
1678public:
1679 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1680 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1681 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1682
1683 static bool classof(const VisitorJob *VJ) {
1684 return VJ->getKind() == TypeLocVisitKind;
1685 }
1686
Ted Kremenek82f3c502010-11-15 22:23:26 +00001687 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001688 QualType T = QualType::getFromOpaquePtr(data[0]);
1689 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001690 }
1691};
1692
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001693class LabelRefVisit : public VisitorJob {
1694public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001695 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1696 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001697 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001698
1699 static bool classof(const VisitorJob *VJ) {
1700 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1701 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001702 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001703 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001704 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001705};
1706class NestedNameSpecifierVisit : public VisitorJob {
1707public:
1708 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1709 CXCursor parent)
1710 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001711 NS, R.getBegin().getPtrEncoding(),
1712 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001713 static bool classof(const VisitorJob *VJ) {
1714 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1715 }
1716 NestedNameSpecifier *get() const {
1717 return static_cast<NestedNameSpecifier*>(data[0]);
1718 }
1719 SourceRange getSourceRange() const {
1720 SourceLocation A =
1721 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1722 SourceLocation B =
1723 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1724 return SourceRange(A, B);
1725 }
1726};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001727
1728class NestedNameSpecifierLocVisit : public VisitorJob {
1729public:
1730 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1731 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1732 Qualifier.getNestedNameSpecifier(),
1733 Qualifier.getOpaqueData()) { }
1734
1735 static bool classof(const VisitorJob *VJ) {
1736 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1737 }
1738
1739 NestedNameSpecifierLoc get() const {
1740 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1741 data[1]);
1742 }
1743};
1744
Ted Kremenekf64d8032010-11-18 00:02:32 +00001745class DeclarationNameInfoVisit : public VisitorJob {
1746public:
1747 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1748 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1749 static bool classof(const VisitorJob *VJ) {
1750 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1751 }
1752 DeclarationNameInfo get() const {
1753 Stmt *S = static_cast<Stmt*>(data[0]);
1754 switch (S->getStmtClass()) {
1755 default:
1756 llvm_unreachable("Unhandled Stmt");
1757 case Stmt::CXXDependentScopeMemberExprClass:
1758 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1759 case Stmt::DependentScopeDeclRefExprClass:
1760 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1761 }
1762 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001763};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001764class MemberRefVisit : public VisitorJob {
1765public:
1766 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1767 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001768 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001769 static bool classof(const VisitorJob *VJ) {
1770 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1771 }
1772 FieldDecl *get() const {
1773 return static_cast<FieldDecl*>(data[0]);
1774 }
1775 SourceLocation getLoc() const {
1776 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1777 }
1778};
Ted Kremenek28a71942010-11-13 00:36:47 +00001779class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1780 VisitorWorkList &WL;
1781 CXCursor Parent;
1782public:
1783 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1784 : WL(wl), Parent(parent) {}
1785
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001786 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001787 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001788 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001789 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001790 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001791 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001792 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001793 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001794 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001795 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001796 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001797 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001798 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001799 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001800 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001801 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001802 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001803 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001804 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1805 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001806 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001807 void VisitIfStmt(IfStmt *If);
1808 void VisitInitListExpr(InitListExpr *IE);
1809 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001810 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001811 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001812 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1813 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001814 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001815 void VisitStmt(Stmt *S);
1816 void VisitSwitchStmt(SwitchStmt *S);
1817 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001818 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001819 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001820 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001821 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001822 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001823 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001824 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001825
Ted Kremenek28a71942010-11-13 00:36:47 +00001826private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001827 void AddDeclarationNameInfo(Stmt *S);
1828 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001829 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001830 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001831 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001832 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001833 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001834 void AddTypeLoc(TypeSourceInfo *TI);
1835 void EnqueueChildren(Stmt *S);
1836};
1837} // end anonyous namespace
1838
Ted Kremenekf64d8032010-11-18 00:02:32 +00001839void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1840 // 'S' should always be non-null, since it comes from the
1841 // statement we are visiting.
1842 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1843}
1844void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1845 SourceRange R) {
1846 if (N)
1847 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1848}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001849
1850void
1851EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1852 if (Qualifier)
1853 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1854}
1855
Ted Kremenek28a71942010-11-13 00:36:47 +00001856void EnqueueVisitor::AddStmt(Stmt *S) {
1857 if (S)
1858 WL.push_back(StmtVisit(S, Parent));
1859}
Ted Kremenek035dc412010-11-13 00:36:50 +00001860void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001861 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001862 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001863}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001864void EnqueueVisitor::
1865 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1866 if (A)
1867 WL.push_back(ExplicitTemplateArgsVisit(
1868 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1869}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001870void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1871 if (D)
1872 WL.push_back(MemberRefVisit(D, L, Parent));
1873}
Ted Kremenek28a71942010-11-13 00:36:47 +00001874void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1875 if (TI)
1876 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1877 }
1878void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001879 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001880 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001881 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001882 }
1883 if (size == WL.size())
1884 return;
1885 // Now reverse the entries we just added. This will match the DFS
1886 // ordering performed by the worklist.
1887 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1888 std::reverse(I, E);
1889}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001890void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1891 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1892}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001893void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1894 AddDecl(B->getBlockDecl());
1895}
Ted Kremenek28a71942010-11-13 00:36:47 +00001896void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1897 EnqueueChildren(E);
1898 AddTypeLoc(E->getTypeSourceInfo());
1899}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001900void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1901 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1902 E = S->body_rend(); I != E; ++I) {
1903 AddStmt(*I);
1904 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001905}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001906void EnqueueVisitor::
1907VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1908 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1909 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001910 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1911 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001912 if (!E->isImplicitAccess())
1913 AddStmt(E->getBase());
1914}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001915void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1916 // Enqueue the initializer or constructor arguments.
1917 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1918 AddStmt(E->getConstructorArg(I-1));
1919 // Enqueue the array size, if any.
1920 AddStmt(E->getArraySize());
1921 // Enqueue the allocated type.
1922 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1923 // Enqueue the placement arguments.
1924 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1925 AddStmt(E->getPlacementArg(I-1));
1926}
Ted Kremenek28a71942010-11-13 00:36:47 +00001927void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001928 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1929 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001930 AddStmt(CE->getCallee());
1931 AddStmt(CE->getArg(0));
1932}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001933void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1934 // Visit the name of the type being destroyed.
1935 AddTypeLoc(E->getDestroyedTypeInfo());
1936 // Visit the scope type that looks disturbingly like the nested-name-specifier
1937 // but isn't.
1938 AddTypeLoc(E->getScopeTypeInfo());
1939 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001940 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1941 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001942 // Visit base expression.
1943 AddStmt(E->getBase());
1944}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001945void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1946 AddTypeLoc(E->getTypeSourceInfo());
1947}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001948void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1949 EnqueueChildren(E);
1950 AddTypeLoc(E->getTypeSourceInfo());
1951}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001952void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1953 EnqueueChildren(E);
1954 if (E->isTypeOperand())
1955 AddTypeLoc(E->getTypeOperandSourceInfo());
1956}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001957
1958void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1959 *E) {
1960 EnqueueChildren(E);
1961 AddTypeLoc(E->getTypeSourceInfo());
1962}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001963void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1964 EnqueueChildren(E);
1965 if (E->isTypeOperand())
1966 AddTypeLoc(E->getTypeOperandSourceInfo());
1967}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001968void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001969 if (DR->hasExplicitTemplateArgs()) {
1970 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1971 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001972 WL.push_back(DeclRefExprParts(DR, Parent));
1973}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001974void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1975 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1976 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001977 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001978}
Ted Kremenek035dc412010-11-13 00:36:50 +00001979void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1980 unsigned size = WL.size();
1981 bool isFirst = true;
1982 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1983 D != DEnd; ++D) {
1984 AddDecl(*D, isFirst);
1985 isFirst = false;
1986 }
1987 if (size == WL.size())
1988 return;
1989 // Now reverse the entries we just added. This will match the DFS
1990 // ordering performed by the worklist.
1991 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1992 std::reverse(I, E);
1993}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001994void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1995 AddStmt(E->getInit());
1996 typedef DesignatedInitExpr::Designator Designator;
1997 for (DesignatedInitExpr::reverse_designators_iterator
1998 D = E->designators_rbegin(), DEnd = E->designators_rend();
1999 D != DEnd; ++D) {
2000 if (D->isFieldDesignator()) {
2001 if (FieldDecl *Field = D->getField())
2002 AddMemberRef(Field, D->getFieldLoc());
2003 continue;
2004 }
2005 if (D->isArrayDesignator()) {
2006 AddStmt(E->getArrayIndex(*D));
2007 continue;
2008 }
2009 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2010 AddStmt(E->getArrayRangeEnd(*D));
2011 AddStmt(E->getArrayRangeStart(*D));
2012 }
2013}
Ted Kremenek28a71942010-11-13 00:36:47 +00002014void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
2015 EnqueueChildren(E);
2016 AddTypeLoc(E->getTypeInfoAsWritten());
2017}
2018void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2019 AddStmt(FS->getBody());
2020 AddStmt(FS->getInc());
2021 AddStmt(FS->getCond());
2022 AddDecl(FS->getConditionVariable());
2023 AddStmt(FS->getInit());
2024}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002025void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2026 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2027}
Ted Kremenek28a71942010-11-13 00:36:47 +00002028void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2029 AddStmt(If->getElse());
2030 AddStmt(If->getThen());
2031 AddStmt(If->getCond());
2032 AddDecl(If->getConditionVariable());
2033}
2034void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2035 // We care about the syntactic form of the initializer list, only.
2036 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2037 IE = Syntactic;
2038 EnqueueChildren(IE);
2039}
2040void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002041 WL.push_back(MemberExprParts(M, Parent));
2042
2043 // If the base of the member access expression is an implicit 'this', don't
2044 // visit it.
2045 // FIXME: If we ever want to show these implicit accesses, this will be
2046 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002047 if (!M->isImplicitAccess())
2048 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002049}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002050void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2051 AddTypeLoc(E->getEncodedTypeSourceInfo());
2052}
Ted Kremenek28a71942010-11-13 00:36:47 +00002053void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2054 EnqueueChildren(M);
2055 AddTypeLoc(M->getClassReceiverTypeInfo());
2056}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002057void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2058 // Visit the components of the offsetof expression.
2059 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2060 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2061 const OffsetOfNode &Node = E->getComponent(I-1);
2062 switch (Node.getKind()) {
2063 case OffsetOfNode::Array:
2064 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2065 break;
2066 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002067 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002068 break;
2069 case OffsetOfNode::Identifier:
2070 case OffsetOfNode::Base:
2071 continue;
2072 }
2073 }
2074 // Visit the type into which we're computing the offset.
2075 AddTypeLoc(E->getTypeSourceInfo());
2076}
Ted Kremenek28a71942010-11-13 00:36:47 +00002077void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002078 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002079 WL.push_back(OverloadExprParts(E, Parent));
2080}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002081void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2082 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002083 EnqueueChildren(E);
2084 if (E->isArgumentType())
2085 AddTypeLoc(E->getArgumentTypeInfo());
2086}
Ted Kremenek28a71942010-11-13 00:36:47 +00002087void EnqueueVisitor::VisitStmt(Stmt *S) {
2088 EnqueueChildren(S);
2089}
2090void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2091 AddStmt(S->getBody());
2092 AddStmt(S->getCond());
2093 AddDecl(S->getConditionVariable());
2094}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002095
Ted Kremenek28a71942010-11-13 00:36:47 +00002096void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2097 AddStmt(W->getBody());
2098 AddStmt(W->getCond());
2099 AddDecl(W->getConditionVariable());
2100}
John Wiegley21ff2e52011-04-28 00:16:57 +00002101
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002102void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2103 AddTypeLoc(E->getQueriedTypeSourceInfo());
2104}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002105
2106void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002107 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002108 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002109}
2110
John Wiegley21ff2e52011-04-28 00:16:57 +00002111void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2112 AddTypeLoc(E->getQueriedTypeSourceInfo());
2113}
2114
John Wiegley55262202011-04-25 06:54:41 +00002115void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2116 EnqueueChildren(E);
2117}
2118
Ted Kremenek28a71942010-11-13 00:36:47 +00002119void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2120 VisitOverloadExpr(U);
2121 if (!U->isImplicitAccess())
2122 AddStmt(U->getBase());
2123}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002124void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2125 AddStmt(E->getSubExpr());
2126 AddTypeLoc(E->getWrittenTypeInfo());
2127}
Douglas Gregor94d96292011-01-19 20:34:17 +00002128void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2129 WL.push_back(SizeOfPackExprParts(E, Parent));
2130}
Ted Kremenek60458782010-11-12 21:34:16 +00002131
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002132void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002133 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002134}
2135
2136bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2137 if (RegionOfInterest.isValid()) {
2138 SourceRange Range = getRawCursorExtent(C);
2139 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2140 return false;
2141 }
2142 return true;
2143}
2144
2145bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2146 while (!WL.empty()) {
2147 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002148 VisitorJob LI = WL.back();
2149 WL.pop_back();
2150
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002151 // Set the Parent field, then back to its old value once we're done.
2152 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2153
2154 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002155 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002156 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002157 if (!D)
2158 continue;
2159
2160 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002161 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002162 return true;
2163
2164 continue;
2165 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002166 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2167 const ExplicitTemplateArgumentList *ArgList =
2168 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2169 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2170 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2171 Arg != ArgEnd; ++Arg) {
2172 if (VisitTemplateArgumentLoc(*Arg))
2173 return true;
2174 }
2175 continue;
2176 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002177 case VisitorJob::TypeLocVisitKind: {
2178 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002179 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002180 return true;
2181 continue;
2182 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002183 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002184 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002185 if (LabelStmt *stmt = LS->getStmt()) {
2186 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2187 TU))) {
2188 return true;
2189 }
2190 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002191 continue;
2192 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002193
Ted Kremenekf64d8032010-11-18 00:02:32 +00002194 case VisitorJob::NestedNameSpecifierVisitKind: {
2195 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2196 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2197 return true;
2198 continue;
2199 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002200
2201 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2202 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2203 if (VisitNestedNameSpecifierLoc(V->get()))
2204 return true;
2205 continue;
2206 }
2207
Ted Kremenekf64d8032010-11-18 00:02:32 +00002208 case VisitorJob::DeclarationNameInfoVisitKind: {
2209 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2210 ->get()))
2211 return true;
2212 continue;
2213 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002214 case VisitorJob::MemberRefVisitKind: {
2215 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2216 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2217 return true;
2218 continue;
2219 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002220 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002221 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002222 if (!S)
2223 continue;
2224
Ted Kremenekf1107452010-11-12 18:26:56 +00002225 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002226 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002227 if (!IsInRegionOfInterest(Cursor))
2228 continue;
2229 switch (Visitor(Cursor, Parent, ClientData)) {
2230 case CXChildVisit_Break: return true;
2231 case CXChildVisit_Continue: break;
2232 case CXChildVisit_Recurse:
2233 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002234 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002235 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002236 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002237 }
2238 case VisitorJob::MemberExprPartsKind: {
2239 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002240 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002241
2242 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002243 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2244 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002245 return true;
2246
2247 // Visit the declaration name.
2248 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2249 return true;
2250
2251 // Visit the explicitly-specified template arguments, if any.
2252 if (M->hasExplicitTemplateArgs()) {
2253 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2254 *ArgEnd = Arg + M->getNumTemplateArgs();
2255 Arg != ArgEnd; ++Arg) {
2256 if (VisitTemplateArgumentLoc(*Arg))
2257 return true;
2258 }
2259 }
2260 continue;
2261 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002262 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002263 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002264 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002265 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2266 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002267 return true;
2268 // Visit declaration name.
2269 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2270 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002271 continue;
2272 }
Ted Kremenek60458782010-11-12 21:34:16 +00002273 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002274 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002275 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002276 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2277 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002278 return true;
2279 // Visit the declaration name.
2280 if (VisitDeclarationNameInfo(O->getNameInfo()))
2281 return true;
2282 // Visit the overloaded declaration reference.
2283 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2284 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002285 continue;
2286 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002287 case VisitorJob::SizeOfPackExprPartsKind: {
2288 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2289 NamedDecl *Pack = E->getPack();
2290 if (isa<TemplateTypeParmDecl>(Pack)) {
2291 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2292 E->getPackLoc(), TU)))
2293 return true;
2294
2295 continue;
2296 }
2297
2298 if (isa<TemplateTemplateParmDecl>(Pack)) {
2299 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2300 E->getPackLoc(), TU)))
2301 return true;
2302
2303 continue;
2304 }
2305
2306 // Non-type template parameter packs and function parameter packs are
2307 // treated like DeclRefExpr cursors.
2308 continue;
2309 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002310 }
2311 }
2312 return false;
2313}
2314
Ted Kremenekcdba6592010-11-18 00:42:18 +00002315bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002316 VisitorWorkList *WL = 0;
2317 if (!WorkListFreeList.empty()) {
2318 WL = WorkListFreeList.back();
2319 WL->clear();
2320 WorkListFreeList.pop_back();
2321 }
2322 else {
2323 WL = new VisitorWorkList();
2324 WorkListCache.push_back(WL);
2325 }
2326 EnqueueWorkList(*WL, S);
2327 bool result = RunVisitorWorkList(*WL);
2328 WorkListFreeList.push_back(WL);
2329 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002330}
2331
Francois Pichet48a8d142011-07-25 22:00:44 +00002332namespace {
2333typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2334RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2335 const DeclarationNameInfo &NI,
2336 const SourceRange &QLoc,
2337 const ExplicitTemplateArgumentList *TemplateArgs = 0){
2338 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2339 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2340 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2341
2342 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2343
2344 RefNamePieces Pieces;
2345
2346 if (WantQualifier && QLoc.isValid())
2347 Pieces.push_back(QLoc);
2348
2349 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2350 Pieces.push_back(NI.getLoc());
2351
2352 if (WantTemplateArgs && TemplateArgs)
2353 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2354 TemplateArgs->RAngleLoc));
2355
2356 if (Kind == DeclarationName::CXXOperatorName) {
2357 Pieces.push_back(SourceLocation::getFromRawEncoding(
2358 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2359 Pieces.push_back(SourceLocation::getFromRawEncoding(
2360 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2361 }
2362
2363 if (WantSinglePiece) {
2364 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2365 Pieces.clear();
2366 Pieces.push_back(R);
2367 }
2368
2369 return Pieces;
2370}
2371}
2372
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002373//===----------------------------------------------------------------------===//
2374// Misc. API hooks.
2375//===----------------------------------------------------------------------===//
2376
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002377static llvm::sys::Mutex EnableMultithreadingMutex;
2378static bool EnabledMultithreading;
2379
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002380extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002381CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2382 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002383 // Disable pretty stack trace functionality, which will otherwise be a very
2384 // poor citizen of the world and set up all sorts of signal handlers.
2385 llvm::DisablePrettyStackTrace = true;
2386
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002387 // We use crash recovery to make some of our APIs more reliable, implicitly
2388 // enable it.
2389 llvm::CrashRecoveryContext::Enable();
2390
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002391 // Enable support for multithreading in LLVM.
2392 {
2393 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2394 if (!EnabledMultithreading) {
2395 llvm::llvm_start_multithreaded();
2396 EnabledMultithreading = true;
2397 }
2398 }
2399
Douglas Gregora030b7c2010-01-22 20:35:53 +00002400 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002401 if (excludeDeclarationsFromPCH)
2402 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002403 if (displayDiagnostics)
2404 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002405 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002406}
2407
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002408void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002409 if (CIdx)
2410 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002411}
2412
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002413void clang_toggleCrashRecovery(unsigned isEnabled) {
2414 if (isEnabled)
2415 llvm::CrashRecoveryContext::Enable();
2416 else
2417 llvm::CrashRecoveryContext::Disable();
2418}
2419
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002420CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002421 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002422 if (!CIdx)
2423 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002424
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002425 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002426 FileSystemOptions FileSystemOpts;
2427 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002428
Douglas Gregor28019772010-04-05 23:52:57 +00002429 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002430 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002431 CXXIdx->getOnlyLocalDecls(),
2432 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002433 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002434}
2435
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002436unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002437 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002438 CXTranslationUnit_CacheCompletionResults |
John McCallf85e1932011-06-15 23:02:42 +00002439 CXTranslationUnit_CXXPrecompiledPreamble |
2440 CXTranslationUnit_CXXChainedPCH;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002441}
2442
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002443CXTranslationUnit
2444clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2445 const char *source_filename,
2446 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002447 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002448 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002449 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002450 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002451 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002452 return clang_parseTranslationUnit(CIdx, source_filename,
2453 command_line_args, num_command_line_args,
2454 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002455 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002456}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002457
2458struct ParseTranslationUnitInfo {
2459 CXIndex CIdx;
2460 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002461 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002462 int num_command_line_args;
2463 struct CXUnsavedFile *unsaved_files;
2464 unsigned num_unsaved_files;
2465 unsigned options;
2466 CXTranslationUnit result;
2467};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002468static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002469 ParseTranslationUnitInfo *PTUI =
2470 static_cast<ParseTranslationUnitInfo*>(UserData);
2471 CXIndex CIdx = PTUI->CIdx;
2472 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002473 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002474 int num_command_line_args = PTUI->num_command_line_args;
2475 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2476 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2477 unsigned options = PTUI->options;
2478 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002479
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002480 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002481 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002482
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002483 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2484
Douglas Gregor44c181a2010-07-23 00:33:23 +00002485 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002486 bool CompleteTranslationUnit
2487 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002488 bool CacheCodeCompetionResults
2489 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002490 bool CXXPrecompilePreamble
2491 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2492 bool CXXChainedPCH
2493 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002494
Douglas Gregor5352ac02010-01-28 00:27:43 +00002495 // Configure the diagnostics.
2496 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002497 llvm::IntrusiveRefCntPtr<Diagnostic>
2498 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2499 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002500
Ted Kremenek25a11e12011-03-22 01:15:24 +00002501 // Recover resources if we crash before exiting this function.
2502 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2503 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2504 DiagCleanup(Diags.getPtr());
2505
2506 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2507 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2508
2509 // Recover resources if we crash before exiting this function.
2510 llvm::CrashRecoveryContextCleanupRegistrar<
2511 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2512
Douglas Gregor4db64a42010-01-23 00:14:00 +00002513 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002514 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002515 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002516 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002517 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2518 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002519 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002520
Ted Kremenek25a11e12011-03-22 01:15:24 +00002521 llvm::OwningPtr<std::vector<const char *> >
2522 Args(new std::vector<const char*>());
2523
2524 // Recover resources if we crash before exiting this method.
2525 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2526 ArgsCleanup(Args.get());
2527
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002528 // Since the Clang C library is primarily used by batch tools dealing with
2529 // (often very broken) source code, where spell-checking can have a
2530 // significant negative impact on performance (particularly when
2531 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002532 // Only do this if we haven't found a spell-checking-related argument.
2533 bool FoundSpellCheckingArgument = false;
2534 for (int I = 0; I != num_command_line_args; ++I) {
2535 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2536 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2537 FoundSpellCheckingArgument = true;
2538 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002539 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002540 }
2541 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002542 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002543
Ted Kremenek25a11e12011-03-22 01:15:24 +00002544 Args->insert(Args->end(), command_line_args,
2545 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002546
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002547 // The 'source_filename' argument is optional. If the caller does not
2548 // specify it then it is assumed that the source file is specified
2549 // in the actual argument list.
2550 // Put the source file after command_line_args otherwise if '-x' flag is
2551 // present it will be unused.
2552 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002553 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002554
Douglas Gregor44c181a2010-07-23 00:33:23 +00002555 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002556 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002557 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002558 Args->push_back("-Xclang");
2559 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002560 NestedMacroExpansions
2561 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002562 }
2563
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002564 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002565 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002566 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2567 /* vector::data() not portable */,
2568 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002569 Diags,
2570 CXXIdx->getClangResourcesPath(),
2571 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002572 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002573 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002574 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002575 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002576 PrecompilePreamble,
2577 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002578 CacheCodeCompetionResults,
2579 CXXPrecompilePreamble,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002580 CXXChainedPCH,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002581 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002583 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002584 // Make sure to check that 'Unit' is non-NULL.
2585 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2586 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2587 DEnd = Unit->stored_diag_end();
2588 D != DEnd; ++D) {
2589 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2590 CXString Msg = clang_formatDiagnostic(&Diag,
2591 clang_defaultDiagnosticDisplayOptions());
2592 fprintf(stderr, "%s\n", clang_getCString(Msg));
2593 clang_disposeString(Msg);
2594 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002595#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002596 // On Windows, force a flush, since there may be multiple copies of
2597 // stderr and stdout in the file system, all with different buffers
2598 // but writing to the same device.
2599 fflush(stderr);
2600#endif
2601 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002602 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002603
Ted Kremeneka60ed472010-11-16 08:15:36 +00002604 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002605}
2606CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2607 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002608 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002609 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002610 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002611 unsigned num_unsaved_files,
2612 unsigned options) {
2613 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002614 num_command_line_args, unsaved_files,
2615 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002616 llvm::CrashRecoveryContext CRC;
2617
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002618 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002619 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2620 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2621 fprintf(stderr, " 'command_line_args' : [");
2622 for (int i = 0; i != num_command_line_args; ++i) {
2623 if (i)
2624 fprintf(stderr, ", ");
2625 fprintf(stderr, "'%s'", command_line_args[i]);
2626 }
2627 fprintf(stderr, "],\n");
2628 fprintf(stderr, " 'unsaved_files' : [");
2629 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2630 if (i)
2631 fprintf(stderr, ", ");
2632 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2633 unsaved_files[i].Length);
2634 }
2635 fprintf(stderr, "],\n");
2636 fprintf(stderr, " 'options' : %d,\n", options);
2637 fprintf(stderr, "}\n");
2638
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002639 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002640 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2641 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002642 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002643
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002644 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002645}
2646
Douglas Gregor19998442010-08-13 15:35:05 +00002647unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2648 return CXSaveTranslationUnit_None;
2649}
2650
2651int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2652 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002653 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002654 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002655
Douglas Gregor39c411f2011-07-06 16:43:36 +00002656 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002657 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2658 PrintLibclangResourceUsage(TU);
2659 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002660}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002661
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002662void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002663 if (CTUnit) {
2664 // If the translation unit has been marked as unsafe to free, just discard
2665 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002666 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002667 return;
2668
Ted Kremeneka60ed472010-11-16 08:15:36 +00002669 delete static_cast<ASTUnit *>(CTUnit->TUData);
2670 disposeCXStringPool(CTUnit->StringPool);
2671 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002672 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002673}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002674
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002675unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2676 return CXReparse_None;
2677}
2678
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002679struct ReparseTranslationUnitInfo {
2680 CXTranslationUnit TU;
2681 unsigned num_unsaved_files;
2682 struct CXUnsavedFile *unsaved_files;
2683 unsigned options;
2684 int result;
2685};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002686
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002687static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002688 ReparseTranslationUnitInfo *RTUI =
2689 static_cast<ReparseTranslationUnitInfo*>(UserData);
2690 CXTranslationUnit TU = RTUI->TU;
2691 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2692 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2693 unsigned options = RTUI->options;
2694 (void) options;
2695 RTUI->result = 1;
2696
Douglas Gregorabc563f2010-07-19 21:46:24 +00002697 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002698 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002699
Ted Kremeneka60ed472010-11-16 08:15:36 +00002700 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002701 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002702
Ted Kremenek25a11e12011-03-22 01:15:24 +00002703 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2704 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2705
2706 // Recover resources if we crash before exiting this function.
2707 llvm::CrashRecoveryContextCleanupRegistrar<
2708 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2709
Douglas Gregorabc563f2010-07-19 21:46:24 +00002710 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002711 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002712 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002713 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002714 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2715 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002716 }
2717
Ted Kremenek4ee99262011-03-22 20:16:19 +00002718 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2719 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002720 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002721}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002722
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002723int clang_reparseTranslationUnit(CXTranslationUnit TU,
2724 unsigned num_unsaved_files,
2725 struct CXUnsavedFile *unsaved_files,
2726 unsigned options) {
2727 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2728 options, 0 };
2729 llvm::CrashRecoveryContext CRC;
2730
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002731 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002732 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002733 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002734 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002735 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2736 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002737
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002738 return RTUI.result;
2739}
2740
Douglas Gregordf95a132010-08-09 20:45:32 +00002741
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002742CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002743 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002744 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002745
Ted Kremeneka60ed472010-11-16 08:15:36 +00002746 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002747 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002748}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002749
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002750CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002751 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002752 return Result;
2753}
2754
Ted Kremenekfb480492010-01-13 21:46:36 +00002755} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002756
Ted Kremenekfb480492010-01-13 21:46:36 +00002757//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002758// CXSourceLocation and CXSourceRange Operations.
2759//===----------------------------------------------------------------------===//
2760
Douglas Gregorb9790342010-01-22 21:44:22 +00002761extern "C" {
2762CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002763 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002764 return Result;
2765}
2766
2767unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002768 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2769 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2770 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002771}
2772
2773CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2774 CXFile file,
2775 unsigned line,
2776 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002777 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002778 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002779
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002780 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002781 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002782 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002783 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002784 = CXXUnit->getSourceManager().getLocation(File, line, column);
2785 if (SLoc.isInvalid()) {
2786 if (Logging)
2787 llvm::errs() << "clang_getLocation(\"" << File->getName()
2788 << "\", " << line << ", " << column << ") = invalid\n";
2789 return clang_getNullLocation();
2790 }
2791
2792 if (Logging)
2793 llvm::errs() << "clang_getLocation(\"" << File->getName()
2794 << "\", " << line << ", " << column << ") = "
2795 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002796
2797 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2798}
2799
2800CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2801 CXFile file,
2802 unsigned offset) {
2803 if (!tu || !file)
2804 return clang_getNullLocation();
2805
Ted Kremeneka60ed472010-11-16 08:15:36 +00002806 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002807 SourceLocation Start
2808 = CXXUnit->getSourceManager().getLocation(
2809 static_cast<const FileEntry *>(file),
2810 1, 1);
2811 if (Start.isInvalid()) return clang_getNullLocation();
2812
2813 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2814
2815 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002816
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002817 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002818}
2819
Douglas Gregor5352ac02010-01-28 00:27:43 +00002820CXSourceRange clang_getNullRange() {
2821 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2822 return Result;
2823}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002824
Douglas Gregor5352ac02010-01-28 00:27:43 +00002825CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2826 if (begin.ptr_data[0] != end.ptr_data[0] ||
2827 begin.ptr_data[1] != end.ptr_data[1])
2828 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002829
2830 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002831 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002832 return Result;
2833}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002834
2835unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2836{
2837 return range1.ptr_data[0] == range2.ptr_data[0]
2838 && range1.ptr_data[1] == range2.ptr_data[1]
2839 && range1.begin_int_data == range2.begin_int_data
2840 && range1.end_int_data == range2.end_int_data;
2841}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002842} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002843
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002844static void createNullLocation(CXFile *file, unsigned *line,
2845 unsigned *column, unsigned *offset) {
2846 if (file)
2847 *file = 0;
2848 if (line)
2849 *line = 0;
2850 if (column)
2851 *column = 0;
2852 if (offset)
2853 *offset = 0;
2854 return;
2855}
2856
2857extern "C" {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002858void clang_getInstantiationLocation(CXSourceLocation location,
2859 CXFile *file,
2860 unsigned *line,
2861 unsigned *column,
2862 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002863 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2864
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002865 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002866 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002867 return;
2868 }
2869
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002870 const SourceManager &SM =
2871 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth40278532011-07-25 16:49:02 +00002872 SourceLocation InstLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002873
Chandler Carruthcea731a2011-07-14 16:07:57 +00002874 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002875 // This can manifest in invalid code.
2876 FileID fileID = SM.getFileID(InstLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002877 bool Invalid = false;
2878 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2879 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002880 createNullLocation(file, line, column, offset);
2881 return;
2882 }
2883
Douglas Gregor1db19de2010-01-19 21:36:55 +00002884 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002885 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002886 if (line)
Chandler Carruth64211622011-07-25 21:09:52 +00002887 *line = SM.getExpansionLineNumber(InstLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002888 if (column)
Chandler Carrutha77c0312011-07-25 20:57:57 +00002889 *column = SM.getExpansionColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002890 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002891 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002892}
2893
Douglas Gregora9b06d42010-11-09 06:24:54 +00002894void clang_getSpellingLocation(CXSourceLocation location,
2895 CXFile *file,
2896 unsigned *line,
2897 unsigned *column,
2898 unsigned *offset) {
2899 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2900
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002901 if (!location.ptr_data[0] || Loc.isInvalid())
2902 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002903
2904 const SourceManager &SM =
2905 *static_cast<const SourceManager*>(location.ptr_data[0]);
2906 SourceLocation SpellLoc = Loc;
2907 if (SpellLoc.isMacroID()) {
2908 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2909 if (SimpleSpellingLoc.isFileID() &&
2910 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2911 SpellLoc = SimpleSpellingLoc;
2912 else
Chandler Carruth40278532011-07-25 16:49:02 +00002913 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002914 }
2915
2916 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2917 FileID FID = LocInfo.first;
2918 unsigned FileOffset = LocInfo.second;
2919
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002920 if (FID.isInvalid())
2921 return createNullLocation(file, line, column, offset);
2922
Douglas Gregora9b06d42010-11-09 06:24:54 +00002923 if (file)
2924 *file = (void *)SM.getFileEntryForID(FID);
2925 if (line)
2926 *line = SM.getLineNumber(FID, FileOffset);
2927 if (column)
2928 *column = SM.getColumnNumber(FID, FileOffset);
2929 if (offset)
2930 *offset = FileOffset;
2931}
2932
Douglas Gregor1db19de2010-01-19 21:36:55 +00002933CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002934 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002935 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002936 return Result;
2937}
2938
2939CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002940 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002941 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002942 return Result;
2943}
2944
Douglas Gregorb9790342010-01-22 21:44:22 +00002945} // end: extern "C"
2946
Douglas Gregor1db19de2010-01-19 21:36:55 +00002947//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002948// CXFile Operations.
2949//===----------------------------------------------------------------------===//
2950
2951extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002952CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002953 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002954 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002955
Steve Naroff88145032009-10-27 14:35:18 +00002956 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002957 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002958}
2959
2960time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002961 if (!SFile)
2962 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002963
Steve Naroff88145032009-10-27 14:35:18 +00002964 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2965 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002966}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002967
Douglas Gregorb9790342010-01-22 21:44:22 +00002968CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2969 if (!tu)
2970 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002971
Ted Kremeneka60ed472010-11-16 08:15:36 +00002972 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002973
Douglas Gregorb9790342010-01-22 21:44:22 +00002974 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002975 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002976}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002977
Douglas Gregordd3e5542011-05-04 00:14:37 +00002978unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2979 if (!tu || !file)
2980 return 0;
2981
2982 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2983 FileEntry *FEnt = static_cast<FileEntry *>(file);
2984 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2985 .isFileMultipleIncludeGuarded(FEnt);
2986}
2987
Ted Kremenekfb480492010-01-13 21:46:36 +00002988} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002989
Ted Kremenekfb480492010-01-13 21:46:36 +00002990//===----------------------------------------------------------------------===//
2991// CXCursor Operations.
2992//===----------------------------------------------------------------------===//
2993
Ted Kremenekfb480492010-01-13 21:46:36 +00002994static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002995 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2996 return getDeclFromExpr(CE->getSubExpr());
2997
Ted Kremenekfb480492010-01-13 21:46:36 +00002998 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2999 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003000 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3001 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00003002 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3003 return ME->getMemberDecl();
3004 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
3005 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00003006 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00003007 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00003008
Ted Kremenekfb480492010-01-13 21:46:36 +00003009 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3010 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00003011 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00003012 if (!CE->isElidable())
3013 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00003014 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3015 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003016
Douglas Gregordb1314e2010-10-01 21:11:22 +00003017 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3018 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00003019 if (SubstNonTypeTemplateParmPackExpr *NTTP
3020 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3021 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00003022 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3023 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3024 isa<ParmVarDecl>(SizeOfPack->getPack()))
3025 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00003026
Ted Kremenekfb480492010-01-13 21:46:36 +00003027 return 0;
3028}
3029
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003030static SourceLocation getLocationFromExpr(Expr *E) {
3031 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3032 return /*FIXME:*/Msg->getLeftLoc();
3033 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3034 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003035 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3036 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003037 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3038 return Member->getMemberLoc();
3039 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3040 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003041 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3042 return SizeOfPack->getPackLoc();
3043
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003044 return E->getLocStart();
3045}
3046
Ted Kremenekfb480492010-01-13 21:46:36 +00003047extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003048
3049unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003050 CXCursorVisitor visitor,
3051 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003052 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003053 getCursorASTUnit(parent)->getMaxPCHLevel(),
3054 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003055 return CursorVis.VisitChildren(parent);
3056}
3057
David Chisnall3387c652010-11-03 14:12:26 +00003058#ifndef __has_feature
3059#define __has_feature(x) 0
3060#endif
3061#if __has_feature(blocks)
3062typedef enum CXChildVisitResult
3063 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3064
3065static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3066 CXClientData client_data) {
3067 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3068 return block(cursor, parent);
3069}
3070#else
3071// If we are compiled with a compiler that doesn't have native blocks support,
3072// define and call the block manually, so the
3073typedef struct _CXChildVisitResult
3074{
3075 void *isa;
3076 int flags;
3077 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003078 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3079 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003080} *CXCursorVisitorBlock;
3081
3082static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3083 CXClientData client_data) {
3084 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3085 return block->invoke(block, cursor, parent);
3086}
3087#endif
3088
3089
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003090unsigned clang_visitChildrenWithBlock(CXCursor parent,
3091 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003092 return clang_visitChildren(parent, visitWithBlock, block);
3093}
3094
Douglas Gregor78205d42010-01-20 21:45:58 +00003095static CXString getDeclSpelling(Decl *D) {
3096 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003097 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003098 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003099 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3100 return createCXString(Property->getIdentifier()->getName());
3101
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003102 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003103 }
3104
Douglas Gregor78205d42010-01-20 21:45:58 +00003105 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003106 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003107
Douglas Gregor78205d42010-01-20 21:45:58 +00003108 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3109 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3110 // and returns different names. NamedDecl returns the class name and
3111 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003112 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003113
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003114 if (isa<UsingDirectiveDecl>(D))
3115 return createCXString("");
3116
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003117 llvm::SmallString<1024> S;
3118 llvm::raw_svector_ostream os(S);
3119 ND->printName(os);
3120
3121 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003122}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003123
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003124CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003125 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003126 return clang_getTranslationUnitSpelling(
3127 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003128
Steve Narofff334b4e2009-09-02 18:26:48 +00003129 if (clang_isReference(C.kind)) {
3130 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003131 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003132 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003133 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003134 }
3135 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003136 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003137 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003138 }
3139 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003140 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003141 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003142 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003143 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003144 case CXCursor_CXXBaseSpecifier: {
3145 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3146 return createCXString(B->getType().getAsString());
3147 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003148 case CXCursor_TypeRef: {
3149 TypeDecl *Type = getCursorTypeRef(C).first;
3150 assert(Type && "Missing type decl");
3151
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003152 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3153 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003154 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003155 case CXCursor_TemplateRef: {
3156 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003157 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003158
3159 return createCXString(Template->getNameAsString());
3160 }
Douglas Gregor69319002010-08-31 23:48:11 +00003161
3162 case CXCursor_NamespaceRef: {
3163 NamedDecl *NS = getCursorNamespaceRef(C).first;
3164 assert(NS && "Missing namespace decl");
3165
3166 return createCXString(NS->getNameAsString());
3167 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003168
Douglas Gregora67e03f2010-09-09 21:42:20 +00003169 case CXCursor_MemberRef: {
3170 FieldDecl *Field = getCursorMemberRef(C).first;
3171 assert(Field && "Missing member decl");
3172
3173 return createCXString(Field->getNameAsString());
3174 }
3175
Douglas Gregor36897b02010-09-10 00:22:18 +00003176 case CXCursor_LabelRef: {
3177 LabelStmt *Label = getCursorLabelRef(C).first;
3178 assert(Label && "Missing label");
3179
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003180 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003181 }
3182
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003183 case CXCursor_OverloadedDeclRef: {
3184 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3185 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3186 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3187 return createCXString(ND->getNameAsString());
3188 return createCXString("");
3189 }
3190 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3191 return createCXString(E->getName().getAsString());
3192 OverloadedTemplateStorage *Ovl
3193 = Storage.get<OverloadedTemplateStorage*>();
3194 if (Ovl->size() == 0)
3195 return createCXString("");
3196 return createCXString((*Ovl->begin())->getNameAsString());
3197 }
3198
Daniel Dunbaracca7252009-11-30 20:42:49 +00003199 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003200 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003201 }
3202 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003203
3204 if (clang_isExpression(C.kind)) {
3205 Decl *D = getDeclFromExpr(getCursorExpr(C));
3206 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003207 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003208 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003209 }
3210
Douglas Gregor36897b02010-09-10 00:22:18 +00003211 if (clang_isStatement(C.kind)) {
3212 Stmt *S = getCursorStmt(C);
3213 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003214 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003215
3216 return createCXString("");
3217 }
3218
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003219 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003220 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003221 ->getNameStart());
3222
Douglas Gregor572feb22010-03-18 18:04:21 +00003223 if (C.kind == CXCursor_MacroDefinition)
3224 return createCXString(getCursorMacroDefinition(C)->getName()
3225 ->getNameStart());
3226
Douglas Gregorecdcb882010-10-20 22:00:55 +00003227 if (C.kind == CXCursor_InclusionDirective)
3228 return createCXString(getCursorInclusionDirective(C)->getFileName());
3229
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003230 if (clang_isDeclaration(C.kind))
3231 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003232
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003233 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003234}
3235
Douglas Gregor358559d2010-10-02 22:49:11 +00003236CXString clang_getCursorDisplayName(CXCursor C) {
3237 if (!clang_isDeclaration(C.kind))
3238 return clang_getCursorSpelling(C);
3239
3240 Decl *D = getCursorDecl(C);
3241 if (!D)
3242 return createCXString("");
3243
3244 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3245 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3246 D = FunTmpl->getTemplatedDecl();
3247
3248 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3249 llvm::SmallString<64> Str;
3250 llvm::raw_svector_ostream OS(Str);
3251 OS << Function->getNameAsString();
3252 if (Function->getPrimaryTemplate())
3253 OS << "<>";
3254 OS << "(";
3255 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3256 if (I)
3257 OS << ", ";
3258 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3259 }
3260
3261 if (Function->isVariadic()) {
3262 if (Function->getNumParams())
3263 OS << ", ";
3264 OS << "...";
3265 }
3266 OS << ")";
3267 return createCXString(OS.str());
3268 }
3269
3270 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3271 llvm::SmallString<64> Str;
3272 llvm::raw_svector_ostream OS(Str);
3273 OS << ClassTemplate->getNameAsString();
3274 OS << "<";
3275 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3276 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3277 if (I)
3278 OS << ", ";
3279
3280 NamedDecl *Param = Params->getParam(I);
3281 if (Param->getIdentifier()) {
3282 OS << Param->getIdentifier()->getName();
3283 continue;
3284 }
3285
3286 // There is no parameter name, which makes this tricky. Try to come up
3287 // with something useful that isn't too long.
3288 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3289 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3290 else if (NonTypeTemplateParmDecl *NTTP
3291 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3292 OS << NTTP->getType().getAsString(Policy);
3293 else
3294 OS << "template<...> class";
3295 }
3296
3297 OS << ">";
3298 return createCXString(OS.str());
3299 }
3300
3301 if (ClassTemplateSpecializationDecl *ClassSpec
3302 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3303 // If the type was explicitly written, use that.
3304 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3305 return createCXString(TSInfo->getType().getAsString(Policy));
3306
3307 llvm::SmallString<64> Str;
3308 llvm::raw_svector_ostream OS(Str);
3309 OS << ClassSpec->getNameAsString();
3310 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003311 ClassSpec->getTemplateArgs().data(),
3312 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003313 Policy);
3314 return createCXString(OS.str());
3315 }
3316
3317 return clang_getCursorSpelling(C);
3318}
3319
Ted Kremeneke68fff62010-02-17 00:41:32 +00003320CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003321 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003322 case CXCursor_FunctionDecl:
3323 return createCXString("FunctionDecl");
3324 case CXCursor_TypedefDecl:
3325 return createCXString("TypedefDecl");
3326 case CXCursor_EnumDecl:
3327 return createCXString("EnumDecl");
3328 case CXCursor_EnumConstantDecl:
3329 return createCXString("EnumConstantDecl");
3330 case CXCursor_StructDecl:
3331 return createCXString("StructDecl");
3332 case CXCursor_UnionDecl:
3333 return createCXString("UnionDecl");
3334 case CXCursor_ClassDecl:
3335 return createCXString("ClassDecl");
3336 case CXCursor_FieldDecl:
3337 return createCXString("FieldDecl");
3338 case CXCursor_VarDecl:
3339 return createCXString("VarDecl");
3340 case CXCursor_ParmDecl:
3341 return createCXString("ParmDecl");
3342 case CXCursor_ObjCInterfaceDecl:
3343 return createCXString("ObjCInterfaceDecl");
3344 case CXCursor_ObjCCategoryDecl:
3345 return createCXString("ObjCCategoryDecl");
3346 case CXCursor_ObjCProtocolDecl:
3347 return createCXString("ObjCProtocolDecl");
3348 case CXCursor_ObjCPropertyDecl:
3349 return createCXString("ObjCPropertyDecl");
3350 case CXCursor_ObjCIvarDecl:
3351 return createCXString("ObjCIvarDecl");
3352 case CXCursor_ObjCInstanceMethodDecl:
3353 return createCXString("ObjCInstanceMethodDecl");
3354 case CXCursor_ObjCClassMethodDecl:
3355 return createCXString("ObjCClassMethodDecl");
3356 case CXCursor_ObjCImplementationDecl:
3357 return createCXString("ObjCImplementationDecl");
3358 case CXCursor_ObjCCategoryImplDecl:
3359 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003360 case CXCursor_CXXMethod:
3361 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003362 case CXCursor_UnexposedDecl:
3363 return createCXString("UnexposedDecl");
3364 case CXCursor_ObjCSuperClassRef:
3365 return createCXString("ObjCSuperClassRef");
3366 case CXCursor_ObjCProtocolRef:
3367 return createCXString("ObjCProtocolRef");
3368 case CXCursor_ObjCClassRef:
3369 return createCXString("ObjCClassRef");
3370 case CXCursor_TypeRef:
3371 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003372 case CXCursor_TemplateRef:
3373 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003374 case CXCursor_NamespaceRef:
3375 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003376 case CXCursor_MemberRef:
3377 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003378 case CXCursor_LabelRef:
3379 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003380 case CXCursor_OverloadedDeclRef:
3381 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003382 case CXCursor_UnexposedExpr:
3383 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003384 case CXCursor_BlockExpr:
3385 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003386 case CXCursor_DeclRefExpr:
3387 return createCXString("DeclRefExpr");
3388 case CXCursor_MemberRefExpr:
3389 return createCXString("MemberRefExpr");
3390 case CXCursor_CallExpr:
3391 return createCXString("CallExpr");
3392 case CXCursor_ObjCMessageExpr:
3393 return createCXString("ObjCMessageExpr");
3394 case CXCursor_UnexposedStmt:
3395 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003396 case CXCursor_LabelStmt:
3397 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003398 case CXCursor_InvalidFile:
3399 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003400 case CXCursor_InvalidCode:
3401 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003402 case CXCursor_NoDeclFound:
3403 return createCXString("NoDeclFound");
3404 case CXCursor_NotImplemented:
3405 return createCXString("NotImplemented");
3406 case CXCursor_TranslationUnit:
3407 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003408 case CXCursor_UnexposedAttr:
3409 return createCXString("UnexposedAttr");
3410 case CXCursor_IBActionAttr:
3411 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003412 case CXCursor_IBOutletAttr:
3413 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003414 case CXCursor_IBOutletCollectionAttr:
3415 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003416 case CXCursor_PreprocessingDirective:
3417 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003418 case CXCursor_MacroDefinition:
3419 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003420 case CXCursor_MacroExpansion:
3421 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003422 case CXCursor_InclusionDirective:
3423 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003424 case CXCursor_Namespace:
3425 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003426 case CXCursor_LinkageSpec:
3427 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003428 case CXCursor_CXXBaseSpecifier:
3429 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003430 case CXCursor_Constructor:
3431 return createCXString("CXXConstructor");
3432 case CXCursor_Destructor:
3433 return createCXString("CXXDestructor");
3434 case CXCursor_ConversionFunction:
3435 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003436 case CXCursor_TemplateTypeParameter:
3437 return createCXString("TemplateTypeParameter");
3438 case CXCursor_NonTypeTemplateParameter:
3439 return createCXString("NonTypeTemplateParameter");
3440 case CXCursor_TemplateTemplateParameter:
3441 return createCXString("TemplateTemplateParameter");
3442 case CXCursor_FunctionTemplate:
3443 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003444 case CXCursor_ClassTemplate:
3445 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003446 case CXCursor_ClassTemplatePartialSpecialization:
3447 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003448 case CXCursor_NamespaceAlias:
3449 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003450 case CXCursor_UsingDirective:
3451 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003452 case CXCursor_UsingDeclaration:
3453 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003454 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003455 return createCXString("TypeAliasDecl");
3456 case CXCursor_ObjCSynthesizeDecl:
3457 return createCXString("ObjCSynthesizeDecl");
3458 case CXCursor_ObjCDynamicDecl:
3459 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003460 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003461
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003462 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003463 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003464}
Steve Naroff89922f82009-08-31 00:59:03 +00003465
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003466struct GetCursorData {
3467 SourceLocation TokenBeginLoc;
3468 CXCursor &BestCursor;
3469
3470 GetCursorData(SourceLocation tokenBegin, CXCursor &outputCursor)
3471 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { }
3472};
3473
Ted Kremeneke68fff62010-02-17 00:41:32 +00003474enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3475 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003476 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003477 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3478 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis8a4bfaa2011-08-10 21:12:04 +00003479
3480 if (clang_isDeclaration(cursor.kind)) {
3481 // Avoid having the synthesized methods override the property decls.
3482 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3483 if (MD->isSynthesized())
3484 return CXChildVisit_Break;
3485 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003486
3487 if (clang_isExpression(cursor.kind) &&
3488 clang_isDeclaration(BestCursor->kind)) {
3489 Decl *D = getCursorDecl(*BestCursor);
3490
3491 // Avoid having the cursor of an expression replace the declaration cursor
3492 // when the expression source range overlaps the declaration range.
3493 // This can happen for C++ constructor expressions whose range generally
3494 // include the variable declaration, e.g.:
3495 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3496 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3497 D->getLocation() == Data->TokenBeginLoc)
3498 return CXChildVisit_Break;
3499 }
3500
Douglas Gregor93798e22010-11-05 21:11:19 +00003501 // If our current best cursor is the construction of a temporary object,
3502 // don't replace that cursor with a type reference, because we want
3503 // clang_getCursor() to point at the constructor.
3504 if (clang_isExpression(BestCursor->kind) &&
3505 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3506 cursor.kind == CXCursor_TypeRef)
3507 return CXChildVisit_Recurse;
3508
Douglas Gregor85fe1562010-12-10 07:23:11 +00003509 // Don't override a preprocessing cursor with another preprocessing
3510 // cursor; we want the outermost preprocessing cursor.
3511 if (clang_isPreprocessing(cursor.kind) &&
3512 clang_isPreprocessing(BestCursor->kind))
3513 return CXChildVisit_Recurse;
3514
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003515 *BestCursor = cursor;
3516 return CXChildVisit_Recurse;
3517}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003518
Douglas Gregorb9790342010-01-22 21:44:22 +00003519CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3520 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003521 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003522
Ted Kremeneka60ed472010-11-16 08:15:36 +00003523 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003524 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3525
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003526 // Translate the given source location to make it point at the beginning of
3527 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003528 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003529
3530 // Guard against an invalid SourceLocation, or we may assert in one
3531 // of the following calls.
3532 if (SLoc.isInvalid())
3533 return clang_getNullCursor();
3534
Douglas Gregor40749ee2010-11-03 00:35:38 +00003535 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003536 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3537 CXXUnit->getASTContext().getLangOptions());
3538
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003539 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3540 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003541 // FIXME: Would be great to have a "hint" cursor, then walk from that
3542 // hint cursor upward until we find a cursor whose source range encloses
3543 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003544 GetCursorData ResultData(SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003545 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003546 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003547 Decl::MaxPCHLevel, true, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003548 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003549 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003550
3551 if (Logging) {
3552 CXFile SearchFile;
3553 unsigned SearchLine, SearchColumn;
3554 CXFile ResultFile;
3555 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003556 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3557 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003558 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3559
3560 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3561 0);
3562 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3563 &ResultColumn, 0);
3564 SearchFileName = clang_getFileName(SearchFile);
3565 ResultFileName = clang_getFileName(ResultFile);
3566 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003567 USR = clang_getCursorUSR(Result);
3568 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003569 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3570 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003571 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3572 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003573 clang_disposeString(SearchFileName);
3574 clang_disposeString(ResultFileName);
3575 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003576 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003577
3578 CXCursor Definition = clang_getCursorDefinition(Result);
3579 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3580 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3581 CXString DefinitionKindSpelling
3582 = clang_getCursorKindSpelling(Definition.kind);
3583 CXFile DefinitionFile;
3584 unsigned DefinitionLine, DefinitionColumn;
3585 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3586 &DefinitionLine, &DefinitionColumn, 0);
3587 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3588 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3589 clang_getCString(DefinitionKindSpelling),
3590 clang_getCString(DefinitionFileName),
3591 DefinitionLine, DefinitionColumn);
3592 clang_disposeString(DefinitionFileName);
3593 clang_disposeString(DefinitionKindSpelling);
3594 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003595 }
3596
Ted Kremeneke68fff62010-02-17 00:41:32 +00003597 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003598}
3599
Ted Kremenek73885552009-11-17 19:28:59 +00003600CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003601 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003602}
3603
3604unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003605 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003606}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003607
Douglas Gregor9ce55842010-11-20 00:09:34 +00003608unsigned clang_hashCursor(CXCursor C) {
3609 unsigned Index = 0;
3610 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3611 Index = 1;
3612
3613 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3614 std::make_pair(C.kind, C.data[Index]));
3615}
3616
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003617unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003618 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3619}
3620
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003621unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003622 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3623}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003624
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003625unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003626 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3627}
3628
Douglas Gregor97b98722010-01-19 23:20:36 +00003629unsigned clang_isExpression(enum CXCursorKind K) {
3630 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3631}
3632
3633unsigned clang_isStatement(enum CXCursorKind K) {
3634 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3635}
3636
Douglas Gregor8be80e12011-07-06 03:00:34 +00003637unsigned clang_isAttribute(enum CXCursorKind K) {
3638 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3639}
3640
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003641unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3642 return K == CXCursor_TranslationUnit;
3643}
3644
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003645unsigned clang_isPreprocessing(enum CXCursorKind K) {
3646 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3647}
3648
Ted Kremenekad6eff62010-03-08 21:17:29 +00003649unsigned clang_isUnexposed(enum CXCursorKind K) {
3650 switch (K) {
3651 case CXCursor_UnexposedDecl:
3652 case CXCursor_UnexposedExpr:
3653 case CXCursor_UnexposedStmt:
3654 case CXCursor_UnexposedAttr:
3655 return true;
3656 default:
3657 return false;
3658 }
3659}
3660
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003661CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003662 return C.kind;
3663}
3664
Douglas Gregor98258af2010-01-18 22:46:11 +00003665CXSourceLocation clang_getCursorLocation(CXCursor C) {
3666 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003667 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003668 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003669 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3670 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003671 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003672 }
3673
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003674 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003675 std::pair<ObjCProtocolDecl *, SourceLocation> P
3676 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003677 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003678 }
3679
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003680 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003681 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3682 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003683 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003684 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003685
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003686 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003687 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003688 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003689 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003690
3691 case CXCursor_TemplateRef: {
3692 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3693 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3694 }
3695
Douglas Gregor69319002010-08-31 23:48:11 +00003696 case CXCursor_NamespaceRef: {
3697 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3698 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3699 }
3700
Douglas Gregora67e03f2010-09-09 21:42:20 +00003701 case CXCursor_MemberRef: {
3702 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3703 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3704 }
3705
Ted Kremenek3064ef92010-08-27 21:34:58 +00003706 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003707 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3708 if (!BaseSpec)
3709 return clang_getNullLocation();
3710
3711 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3712 return cxloc::translateSourceLocation(getCursorContext(C),
3713 TSInfo->getTypeLoc().getBeginLoc());
3714
3715 return cxloc::translateSourceLocation(getCursorContext(C),
3716 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003717 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003718
Douglas Gregor36897b02010-09-10 00:22:18 +00003719 case CXCursor_LabelRef: {
3720 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3721 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3722 }
3723
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003724 case CXCursor_OverloadedDeclRef:
3725 return cxloc::translateSourceLocation(getCursorContext(C),
3726 getCursorOverloadedDeclRef(C).second);
3727
Douglas Gregorf46034a2010-01-18 23:41:10 +00003728 default:
3729 // FIXME: Need a way to enumerate all non-reference cases.
3730 llvm_unreachable("Missed a reference kind");
3731 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003732 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003733
3734 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003735 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003736 getLocationFromExpr(getCursorExpr(C)));
3737
Douglas Gregor36897b02010-09-10 00:22:18 +00003738 if (clang_isStatement(C.kind))
3739 return cxloc::translateSourceLocation(getCursorContext(C),
3740 getCursorStmt(C)->getLocStart());
3741
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003742 if (C.kind == CXCursor_PreprocessingDirective) {
3743 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3744 return cxloc::translateSourceLocation(getCursorContext(C), L);
3745 }
Douglas Gregor48072312010-03-18 15:23:44 +00003746
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003747 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003748 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003749 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003750 return cxloc::translateSourceLocation(getCursorContext(C), L);
3751 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003752
3753 if (C.kind == CXCursor_MacroDefinition) {
3754 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3755 return cxloc::translateSourceLocation(getCursorContext(C), L);
3756 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003757
3758 if (C.kind == CXCursor_InclusionDirective) {
3759 SourceLocation L
3760 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3761 return cxloc::translateSourceLocation(getCursorContext(C), L);
3762 }
3763
Ted Kremenek9a700d22010-05-12 06:16:13 +00003764 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003765 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003766
Douglas Gregorf46034a2010-01-18 23:41:10 +00003767 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003768 SourceLocation Loc = D->getLocation();
3769 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3770 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003771 // FIXME: Multiple variables declared in a single declaration
3772 // currently lack the information needed to correctly determine their
3773 // ranges when accounting for the type-specifier. We use context
3774 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3775 // and if so, whether it is the first decl.
3776 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3777 if (!cxcursor::isFirstInDeclGroup(C))
3778 Loc = VD->getLocation();
3779 }
3780
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003781 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003782}
Douglas Gregora7bde202010-01-19 00:34:46 +00003783
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003784} // end extern "C"
3785
3786static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003787 if (clang_isReference(C.kind)) {
3788 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003789 case CXCursor_ObjCSuperClassRef:
3790 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003791
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003792 case CXCursor_ObjCProtocolRef:
3793 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003794
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003795 case CXCursor_ObjCClassRef:
3796 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003797
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003798 case CXCursor_TypeRef:
3799 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003800
3801 case CXCursor_TemplateRef:
3802 return getCursorTemplateRef(C).second;
3803
Douglas Gregor69319002010-08-31 23:48:11 +00003804 case CXCursor_NamespaceRef:
3805 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003806
3807 case CXCursor_MemberRef:
3808 return getCursorMemberRef(C).second;
3809
Ted Kremenek3064ef92010-08-27 21:34:58 +00003810 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003811 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003812
Douglas Gregor36897b02010-09-10 00:22:18 +00003813 case CXCursor_LabelRef:
3814 return getCursorLabelRef(C).second;
3815
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003816 case CXCursor_OverloadedDeclRef:
3817 return getCursorOverloadedDeclRef(C).second;
3818
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003819 default:
3820 // FIXME: Need a way to enumerate all non-reference cases.
3821 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003822 }
3823 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003824
3825 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003826 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003827
3828 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003829 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003830
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003831 if (C.kind == CXCursor_PreprocessingDirective)
3832 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003833
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003834 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003835 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003836
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003837 if (C.kind == CXCursor_MacroDefinition)
3838 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003839
3840 if (C.kind == CXCursor_InclusionDirective)
3841 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3842
Ted Kremenek007a7c92010-11-01 23:26:51 +00003843 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3844 Decl *D = cxcursor::getCursorDecl(C);
3845 SourceRange R = D->getSourceRange();
3846 // FIXME: Multiple variables declared in a single declaration
3847 // currently lack the information needed to correctly determine their
3848 // ranges when accounting for the type-specifier. We use context
3849 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3850 // and if so, whether it is the first decl.
3851 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3852 if (!cxcursor::isFirstInDeclGroup(C))
3853 R.setBegin(VD->getLocation());
3854 }
3855 return R;
3856 }
Douglas Gregor66537982010-11-17 17:14:07 +00003857 return SourceRange();
3858}
3859
3860/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3861/// the decl-specifier-seq for declarations.
3862static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3863 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3864 Decl *D = cxcursor::getCursorDecl(C);
3865 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003866
Douglas Gregor2494dd02011-03-01 01:34:45 +00003867 // Adjust the start of the location for declarations preceded by
3868 // declaration specifiers.
3869 SourceLocation StartLoc;
3870 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3871 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3872 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3873 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3874 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3875 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3876 }
3877
3878 if (StartLoc.isValid() && R.getBegin().isValid() &&
3879 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3880 R.setBegin(StartLoc);
3881
3882 // FIXME: Multiple variables declared in a single declaration
3883 // currently lack the information needed to correctly determine their
3884 // ranges when accounting for the type-specifier. We use context
3885 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3886 // and if so, whether it is the first decl.
3887 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3888 if (!cxcursor::isFirstInDeclGroup(C))
3889 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003890 }
3891
3892 return R;
3893 }
3894
3895 return getRawCursorExtent(C);
3896}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003897
3898extern "C" {
3899
3900CXSourceRange clang_getCursorExtent(CXCursor C) {
3901 SourceRange R = getRawCursorExtent(C);
3902 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003903 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003904
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003905 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003906}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003907
3908CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003909 if (clang_isInvalid(C.kind))
3910 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003911
Ted Kremeneka60ed472010-11-16 08:15:36 +00003912 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003913 if (clang_isDeclaration(C.kind)) {
3914 Decl *D = getCursorDecl(C);
3915 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003916 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003917 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003918 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003919 if (ObjCForwardProtocolDecl *Protocols
3920 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003921 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003922 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003923 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3924 return MakeCXCursor(Property, tu);
3925
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003926 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003927 }
3928
Douglas Gregor97b98722010-01-19 23:20:36 +00003929 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003930 Expr *E = getCursorExpr(C);
3931 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003932 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003933 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003934
3935 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003936 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003937
Douglas Gregor97b98722010-01-19 23:20:36 +00003938 return clang_getNullCursor();
3939 }
3940
Douglas Gregor36897b02010-09-10 00:22:18 +00003941 if (clang_isStatement(C.kind)) {
3942 Stmt *S = getCursorStmt(C);
3943 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003944 if (LabelDecl *label = Goto->getLabel())
3945 if (LabelStmt *labelS = label->getStmt())
3946 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003947
3948 return clang_getNullCursor();
3949 }
3950
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003951 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003952 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003953 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003954 }
3955
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003956 if (!clang_isReference(C.kind))
3957 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003958
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003959 switch (C.kind) {
3960 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003961 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003962
3963 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003964 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003965
3966 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003967 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003968
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003969 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003970 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003971
3972 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003973 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003974
Douglas Gregor69319002010-08-31 23:48:11 +00003975 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003976 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003977
Douglas Gregora67e03f2010-09-09 21:42:20 +00003978 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003979 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003980
Ted Kremenek3064ef92010-08-27 21:34:58 +00003981 case CXCursor_CXXBaseSpecifier: {
3982 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3983 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003984 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003985 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003986
Douglas Gregor36897b02010-09-10 00:22:18 +00003987 case CXCursor_LabelRef:
3988 // FIXME: We end up faking the "parent" declaration here because we
3989 // don't want to make CXCursor larger.
3990 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003991 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3992 .getTranslationUnitDecl(),
3993 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003994
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003995 case CXCursor_OverloadedDeclRef:
3996 return C;
3997
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003998 default:
3999 // We would prefer to enumerate all non-reference cursor kinds here.
4000 llvm_unreachable("Unhandled reference cursor kind");
4001 break;
4002 }
4003 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004004
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004005 return clang_getNullCursor();
4006}
4007
Douglas Gregorb6998662010-01-19 19:34:47 +00004008CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004009 if (clang_isInvalid(C.kind))
4010 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004011
Ted Kremeneka60ed472010-11-16 08:15:36 +00004012 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004013
Douglas Gregorb6998662010-01-19 19:34:47 +00004014 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004015 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004016 C = clang_getCursorReferenced(C);
4017 WasReference = true;
4018 }
4019
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004020 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004021 return clang_getCursorReferenced(C);
4022
Douglas Gregorb6998662010-01-19 19:34:47 +00004023 if (!clang_isDeclaration(C.kind))
4024 return clang_getNullCursor();
4025
4026 Decl *D = getCursorDecl(C);
4027 if (!D)
4028 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004029
Douglas Gregorb6998662010-01-19 19:34:47 +00004030 switch (D->getKind()) {
4031 // Declaration kinds that don't really separate the notions of
4032 // declaration and definition.
4033 case Decl::Namespace:
4034 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004035 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004036 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004037 case Decl::TemplateTypeParm:
4038 case Decl::EnumConstant:
4039 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004040 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004041 case Decl::ObjCIvar:
4042 case Decl::ObjCAtDefsField:
4043 case Decl::ImplicitParam:
4044 case Decl::ParmVar:
4045 case Decl::NonTypeTemplateParm:
4046 case Decl::TemplateTemplateParm:
4047 case Decl::ObjCCategoryImpl:
4048 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004049 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004050 case Decl::LinkageSpec:
4051 case Decl::ObjCPropertyImpl:
4052 case Decl::FileScopeAsm:
4053 case Decl::StaticAssert:
4054 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004055 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004056 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004057 return C;
4058
4059 // Declaration kinds that don't make any sense here, but are
4060 // nonetheless harmless.
4061 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004062 break;
4063
4064 // Declaration kinds for which the definition is not resolvable.
4065 case Decl::UnresolvedUsingTypename:
4066 case Decl::UnresolvedUsingValue:
4067 break;
4068
4069 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004070 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004071 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004072
4073 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004074 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004075
4076 case Decl::Enum:
4077 case Decl::Record:
4078 case Decl::CXXRecord:
4079 case Decl::ClassTemplateSpecialization:
4080 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004081 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004083 return clang_getNullCursor();
4084
4085 case Decl::Function:
4086 case Decl::CXXMethod:
4087 case Decl::CXXConstructor:
4088 case Decl::CXXDestructor:
4089 case Decl::CXXConversion: {
4090 const FunctionDecl *Def = 0;
4091 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004092 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004093 return clang_getNullCursor();
4094 }
4095
4096 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004097 // Ask the variable if it has a definition.
4098 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004099 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004100 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004101 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004102
Douglas Gregorb6998662010-01-19 19:34:47 +00004103 case Decl::FunctionTemplate: {
4104 const FunctionDecl *Def = 0;
4105 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004106 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004107 return clang_getNullCursor();
4108 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004109
Douglas Gregorb6998662010-01-19 19:34:47 +00004110 case Decl::ClassTemplate: {
4111 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004112 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004113 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004115 return clang_getNullCursor();
4116 }
4117
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004118 case Decl::Using:
4119 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004120 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004121
4122 case Decl::UsingShadow:
4123 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004124 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004125 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004126
4127 case Decl::ObjCMethod: {
4128 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4129 if (Method->isThisDeclarationADefinition())
4130 return C;
4131
4132 // Dig out the method definition in the associated
4133 // @implementation, if we have it.
4134 // FIXME: The ASTs should make finding the definition easier.
4135 if (ObjCInterfaceDecl *Class
4136 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4137 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4138 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4139 Method->isInstanceMethod()))
4140 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004141 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004142
4143 return clang_getNullCursor();
4144 }
4145
4146 case Decl::ObjCCategory:
4147 if (ObjCCategoryImplDecl *Impl
4148 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004149 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004150 return clang_getNullCursor();
4151
4152 case Decl::ObjCProtocol:
4153 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4154 return C;
4155 return clang_getNullCursor();
4156
4157 case Decl::ObjCInterface:
4158 // There are two notions of a "definition" for an Objective-C
4159 // class: the interface and its implementation. When we resolved a
4160 // reference to an Objective-C class, produce the @interface as
4161 // the definition; when we were provided with the interface,
4162 // produce the @implementation as the definition.
4163 if (WasReference) {
4164 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4165 return C;
4166 } else if (ObjCImplementationDecl *Impl
4167 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004168 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004169 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004170
Douglas Gregorb6998662010-01-19 19:34:47 +00004171 case Decl::ObjCProperty:
4172 // FIXME: We don't really know where to find the
4173 // ObjCPropertyImplDecls that implement this property.
4174 return clang_getNullCursor();
4175
4176 case Decl::ObjCCompatibleAlias:
4177 if (ObjCInterfaceDecl *Class
4178 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4179 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004180 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004181
Douglas Gregorb6998662010-01-19 19:34:47 +00004182 return clang_getNullCursor();
4183
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004184 case Decl::ObjCForwardProtocol:
4185 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004186 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004187
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004188 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004189 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004190 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004191
4192 case Decl::Friend:
4193 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004194 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004195 return clang_getNullCursor();
4196
4197 case Decl::FriendTemplate:
4198 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004199 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004200 return clang_getNullCursor();
4201 }
4202
4203 return clang_getNullCursor();
4204}
4205
4206unsigned clang_isCursorDefinition(CXCursor C) {
4207 if (!clang_isDeclaration(C.kind))
4208 return 0;
4209
4210 return clang_getCursorDefinition(C) == C;
4211}
4212
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004213CXCursor clang_getCanonicalCursor(CXCursor C) {
4214 if (!clang_isDeclaration(C.kind))
4215 return C;
4216
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004217 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004218 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4219 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4220 return MakeCXCursor(CatD, getCursorTU(C));
4221
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004222 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4223 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4224 return MakeCXCursor(IFD, getCursorTU(C));
4225
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004226 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004227 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004228
4229 return C;
4230}
4231
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004232unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004233 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004234 return 0;
4235
4236 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4237 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4238 return E->getNumDecls();
4239
4240 if (OverloadedTemplateStorage *S
4241 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4242 return S->size();
4243
4244 Decl *D = Storage.get<Decl*>();
4245 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004246 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004247 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4248 return Classes->size();
4249 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4250 return Protocols->protocol_size();
4251
4252 return 0;
4253}
4254
4255CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004256 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004257 return clang_getNullCursor();
4258
4259 if (index >= clang_getNumOverloadedDecls(cursor))
4260 return clang_getNullCursor();
4261
Ted Kremeneka60ed472010-11-16 08:15:36 +00004262 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004263 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4264 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004265 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004266
4267 if (OverloadedTemplateStorage *S
4268 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004269 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004270
4271 Decl *D = Storage.get<Decl*>();
4272 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4273 // FIXME: This is, unfortunately, linear time.
4274 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4275 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004276 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004277 }
4278
4279 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004280 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004281
4282 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004283 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004284
4285 return clang_getNullCursor();
4286}
4287
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004288void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004289 const char **startBuf,
4290 const char **endBuf,
4291 unsigned *startLine,
4292 unsigned *startColumn,
4293 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004294 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004295 assert(getCursorDecl(C) && "CXCursor has null decl");
4296 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004297 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4298 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004299
Steve Naroff4ade6d62009-09-23 17:52:52 +00004300 SourceManager &SM = FD->getASTContext().getSourceManager();
4301 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4302 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4303 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4304 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4305 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4306 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4307}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004308
Douglas Gregor430d7a12011-07-25 17:48:11 +00004309
4310CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4311 unsigned PieceIndex) {
4312 RefNamePieces Pieces;
4313
4314 switch (C.kind) {
4315 case CXCursor_MemberRefExpr:
4316 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4317 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4318 E->getQualifierLoc().getSourceRange());
4319 break;
4320
4321 case CXCursor_DeclRefExpr:
4322 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4323 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4324 E->getQualifierLoc().getSourceRange(),
4325 E->getExplicitTemplateArgsOpt());
4326 break;
4327
4328 case CXCursor_CallExpr:
4329 if (CXXOperatorCallExpr *OCE =
4330 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4331 Expr *Callee = OCE->getCallee();
4332 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4333 Callee = ICE->getSubExpr();
4334
4335 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4336 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4337 DRE->getQualifierLoc().getSourceRange());
4338 }
4339 break;
4340
4341 default:
4342 break;
4343 }
4344
4345 if (Pieces.empty()) {
4346 if (PieceIndex == 0)
4347 return clang_getCursorExtent(C);
4348 } else if (PieceIndex < Pieces.size()) {
4349 SourceRange R = Pieces[PieceIndex];
4350 if (R.isValid())
4351 return cxloc::translateSourceRange(getCursorContext(C), R);
4352 }
4353
4354 return clang_getNullRange();
4355}
4356
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004357void clang_enableStackTraces(void) {
4358 llvm::sys::PrintStackTraceOnErrorSignal();
4359}
4360
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004361void clang_executeOnThread(void (*fn)(void*), void *user_data,
4362 unsigned stack_size) {
4363 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4364}
4365
Ted Kremenekfb480492010-01-13 21:46:36 +00004366} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004367
Ted Kremenekfb480492010-01-13 21:46:36 +00004368//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004369// Token-based Operations.
4370//===----------------------------------------------------------------------===//
4371
4372/* CXToken layout:
4373 * int_data[0]: a CXTokenKind
4374 * int_data[1]: starting token location
4375 * int_data[2]: token length
4376 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004377 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004378 * otherwise unused.
4379 */
4380extern "C" {
4381
4382CXTokenKind clang_getTokenKind(CXToken CXTok) {
4383 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4384}
4385
4386CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4387 switch (clang_getTokenKind(CXTok)) {
4388 case CXToken_Identifier:
4389 case CXToken_Keyword:
4390 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004391 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4392 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004393
4394 case CXToken_Literal: {
4395 // We have stashed the starting pointer in the ptr_data field. Use it.
4396 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004397 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004398 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004399
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004400 case CXToken_Punctuation:
4401 case CXToken_Comment:
4402 break;
4403 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004404
4405 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004406 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004407 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004408 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004409 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004410
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004411 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4412 std::pair<FileID, unsigned> LocInfo
4413 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004414 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004415 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004416 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4417 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004418 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004419
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004420 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004421}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004422
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004423CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004424 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004425 if (!CXXUnit)
4426 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004427
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004428 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4429 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4430}
4431
4432CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004433 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004434 if (!CXXUnit)
4435 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004436
4437 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004438 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4439}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004440
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004441void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4442 CXToken **Tokens, unsigned *NumTokens) {
4443 if (Tokens)
4444 *Tokens = 0;
4445 if (NumTokens)
4446 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004447
Ted Kremeneka60ed472010-11-16 08:15:36 +00004448 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004449 if (!CXXUnit || !Tokens || !NumTokens)
4450 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004451
Douglas Gregorbdf60622010-03-05 21:16:25 +00004452 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4453
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004454 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004455 if (R.isInvalid())
4456 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004457
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004458 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4459 std::pair<FileID, unsigned> BeginLocInfo
4460 = SourceMgr.getDecomposedLoc(R.getBegin());
4461 std::pair<FileID, unsigned> EndLocInfo
4462 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004463
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004464 // Cannot tokenize across files.
4465 if (BeginLocInfo.first != EndLocInfo.first)
4466 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004467
4468 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004469 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004470 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004471 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004472 if (Invalid)
4473 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004474
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004475 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4476 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004477 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004478 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004479
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004480 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004481 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004482 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004483 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004484 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004485 do {
4486 // Lex the next token
4487 Lex.LexFromRawLexer(Tok);
4488 if (Tok.is(tok::eof))
4489 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004490
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004491 // Initialize the CXToken.
4492 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004493
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004494 // - Common fields
4495 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4496 CXTok.int_data[2] = Tok.getLength();
4497 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004498
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004499 // - Kind-specific fields
4500 if (Tok.isLiteral()) {
4501 CXTok.int_data[0] = CXToken_Literal;
4502 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004503 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004504 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004505 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004506 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004507
David Chisnall096428b2010-10-13 21:44:48 +00004508 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004509 CXTok.int_data[0] = CXToken_Keyword;
4510 }
4511 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004512 CXTok.int_data[0] = Tok.is(tok::identifier)
4513 ? CXToken_Identifier
4514 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004515 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004516 CXTok.ptr_data = II;
4517 } else if (Tok.is(tok::comment)) {
4518 CXTok.int_data[0] = CXToken_Comment;
4519 CXTok.ptr_data = 0;
4520 } else {
4521 CXTok.int_data[0] = CXToken_Punctuation;
4522 CXTok.ptr_data = 0;
4523 }
4524 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004525 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004526 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004527
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004528 if (CXTokens.empty())
4529 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004530
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004531 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4532 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4533 *NumTokens = CXTokens.size();
4534}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004535
Ted Kremenek6db61092010-05-05 00:55:15 +00004536void clang_disposeTokens(CXTranslationUnit TU,
4537 CXToken *Tokens, unsigned NumTokens) {
4538 free(Tokens);
4539}
4540
4541} // end: extern "C"
4542
4543//===----------------------------------------------------------------------===//
4544// Token annotation APIs.
4545//===----------------------------------------------------------------------===//
4546
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004547typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004548static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4549 CXCursor parent,
4550 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004551namespace {
4552class AnnotateTokensWorker {
4553 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004554 CXToken *Tokens;
4555 CXCursor *Cursors;
4556 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004557 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004558 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004559 CursorVisitor AnnotateVis;
4560 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004561 bool HasContextSensitiveKeywords;
4562
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004563 bool MoreTokens() const { return TokIdx < NumTokens; }
4564 unsigned NextToken() const { return TokIdx; }
4565 void AdvanceToken() { ++TokIdx; }
4566 SourceLocation GetTokenLoc(unsigned tokI) {
4567 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4568 }
4569
Ted Kremenek6db61092010-05-05 00:55:15 +00004570public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004571 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004572 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004573 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004574 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004575 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004576 AnnotateVis(tu,
4577 AnnotateTokensVisitor, this,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00004578 Decl::MaxPCHLevel, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004579 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4580 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004581
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004582 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004583 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004584 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004585 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004586 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004587 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004588
4589 /// \brief Determine whether the annotator saw any cursors that have
4590 /// context-sensitive keywords.
4591 bool hasContextSensitiveKeywords() const {
4592 return HasContextSensitiveKeywords;
4593 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004594};
4595}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004596
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004597void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4598 // Walk the AST within the region of interest, annotating tokens
4599 // along the way.
4600 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004601
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004602 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4603 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004604 if (Pos != Annotated.end() &&
4605 (clang_isInvalid(Cursors[I].kind) ||
4606 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004607 Cursors[I] = Pos->second;
4608 }
4609
4610 // Finish up annotating any tokens left.
4611 if (!MoreTokens())
4612 return;
4613
4614 const CXCursor &C = clang_getNullCursor();
4615 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4616 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4617 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004618 }
4619}
4620
Ted Kremenek6db61092010-05-05 00:55:15 +00004621enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004622AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004623 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004624 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004625 if (cursorRange.isInvalid())
4626 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004627
4628 if (!HasContextSensitiveKeywords) {
4629 // Objective-C properties can have context-sensitive keywords.
4630 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4631 if (ObjCPropertyDecl *Property
4632 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4633 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4634 }
4635 // Objective-C methods can have context-sensitive keywords.
4636 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4637 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4638 if (ObjCMethodDecl *Method
4639 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4640 if (Method->getObjCDeclQualifier())
4641 HasContextSensitiveKeywords = true;
4642 else {
4643 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4644 PEnd = Method->param_end();
4645 P != PEnd; ++P) {
4646 if ((*P)->getObjCDeclQualifier()) {
4647 HasContextSensitiveKeywords = true;
4648 break;
4649 }
4650 }
4651 }
4652 }
4653 }
4654 // C++ methods can have context-sensitive keywords.
4655 else if (cursor.kind == CXCursor_CXXMethod) {
4656 if (CXXMethodDecl *Method
4657 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4658 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4659 HasContextSensitiveKeywords = true;
4660 }
4661 }
4662 // C++ classes can have context-sensitive keywords.
4663 else if (cursor.kind == CXCursor_StructDecl ||
4664 cursor.kind == CXCursor_ClassDecl ||
4665 cursor.kind == CXCursor_ClassTemplate ||
4666 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4667 if (Decl *D = getCursorDecl(cursor))
4668 if (D->hasAttr<FinalAttr>())
4669 HasContextSensitiveKeywords = true;
4670 }
4671 }
4672
Douglas Gregor4419b672010-10-21 06:10:04 +00004673 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004674 // For macro expansions, just note where the beginning of the macro
4675 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004676 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004677 Annotated[Loc.int_data] = cursor;
4678 return CXChildVisit_Recurse;
4679 }
4680
Douglas Gregor4419b672010-10-21 06:10:04 +00004681 // Items in the preprocessing record are kept separate from items in
4682 // declarations, so we keep a separate token index.
4683 unsigned SavedTokIdx = TokIdx;
4684 TokIdx = PreprocessingTokIdx;
4685
4686 // Skip tokens up until we catch up to the beginning of the preprocessing
4687 // entry.
4688 while (MoreTokens()) {
4689 const unsigned I = NextToken();
4690 SourceLocation TokLoc = GetTokenLoc(I);
4691 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4692 case RangeBefore:
4693 AdvanceToken();
4694 continue;
4695 case RangeAfter:
4696 case RangeOverlap:
4697 break;
4698 }
4699 break;
4700 }
4701
4702 // Look at all of the tokens within this range.
4703 while (MoreTokens()) {
4704 const unsigned I = NextToken();
4705 SourceLocation TokLoc = GetTokenLoc(I);
4706 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4707 case RangeBefore:
4708 assert(0 && "Infeasible");
4709 case RangeAfter:
4710 break;
4711 case RangeOverlap:
4712 Cursors[I] = cursor;
4713 AdvanceToken();
4714 continue;
4715 }
4716 break;
4717 }
4718
4719 // Save the preprocessing token index; restore the non-preprocessing
4720 // token index.
4721 PreprocessingTokIdx = TokIdx;
4722 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004723 return CXChildVisit_Recurse;
4724 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004725
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004726 if (cursorRange.isInvalid())
4727 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004728
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004729 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4730
Ted Kremeneka333c662010-05-12 05:29:33 +00004731 // Adjust the annotated range based specific declarations.
4732 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4733 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004734 Decl *D = cxcursor::getCursorDecl(cursor);
4735 // Don't visit synthesized ObjC methods, since they have no syntatic
4736 // representation in the source.
4737 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4738 if (MD->isSynthesized())
4739 return CXChildVisit_Continue;
4740 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004741
4742 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004743 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004744 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4745 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4746 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4747 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4748 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004749 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004750
4751 if (StartLoc.isValid() && L.isValid() &&
4752 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4753 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004754 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004755
Ted Kremenek3f404602010-08-14 01:14:06 +00004756 // If the location of the cursor occurs within a macro instantiation, record
4757 // the spelling location of the cursor in our annotation map. We can then
4758 // paper over the token labelings during a post-processing step to try and
4759 // get cursor mappings for tokens that are the *arguments* of a macro
4760 // instantiation.
4761 if (L.isMacroID()) {
4762 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4763 // Only invalidate the old annotation if it isn't part of a preprocessing
4764 // directive. Here we assume that the default construction of CXCursor
4765 // results in CXCursor.kind being an initialized value (i.e., 0). If
4766 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004767
Ted Kremenek3f404602010-08-14 01:14:06 +00004768 CXCursor &oldC = Annotated[rawEncoding];
4769 if (!clang_isPreprocessing(oldC.kind))
4770 oldC = cursor;
4771 }
4772
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004773 const enum CXCursorKind K = clang_getCursorKind(parent);
4774 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004775 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4776 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004777
4778 while (MoreTokens()) {
4779 const unsigned I = NextToken();
4780 SourceLocation TokLoc = GetTokenLoc(I);
4781 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4782 case RangeBefore:
4783 Cursors[I] = updateC;
4784 AdvanceToken();
4785 continue;
4786 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004787 case RangeOverlap:
4788 break;
4789 }
4790 break;
4791 }
4792
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004793 // Avoid having the cursor of an expression "overwrite" the annotation of the
4794 // variable declaration that it belongs to.
4795 // This can happen for C++ constructor expressions whose range generally
4796 // include the variable declaration, e.g.:
4797 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4798 if (clang_isExpression(cursorK)) {
4799 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004800 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004801 const unsigned I = NextToken();
4802 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4803 E->getLocStart() == D->getLocation() &&
4804 E->getLocStart() == GetTokenLoc(I)) {
4805 Cursors[I] = updateC;
4806 AdvanceToken();
4807 }
4808 }
4809 }
4810
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004811 // Visit children to get their cursor information.
4812 const unsigned BeforeChildren = NextToken();
4813 VisitChildren(cursor);
4814 const unsigned AfterChildren = NextToken();
4815
4816 // Adjust 'Last' to the last token within the extent of the cursor.
4817 while (MoreTokens()) {
4818 const unsigned I = NextToken();
4819 SourceLocation TokLoc = GetTokenLoc(I);
4820 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4821 case RangeBefore:
4822 assert(0 && "Infeasible");
4823 case RangeAfter:
4824 break;
4825 case RangeOverlap:
4826 Cursors[I] = updateC;
4827 AdvanceToken();
4828 continue;
4829 }
4830 break;
4831 }
4832 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004833
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004834 // Scan the tokens that are at the beginning of the cursor, but are not
4835 // capture by the child cursors.
4836
4837 // For AST elements within macros, rely on a post-annotate pass to
4838 // to correctly annotate the tokens with cursors. Otherwise we can
4839 // get confusing results of having tokens that map to cursors that really
4840 // are expanded by an instantiation.
4841 if (L.isMacroID())
4842 cursor = clang_getNullCursor();
4843
4844 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4845 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4846 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004847
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004848 Cursors[I] = cursor;
4849 }
4850 // Scan the tokens that are at the end of the cursor, but are not captured
4851 // but the child cursors.
4852 for (unsigned I = AfterChildren; I != Last; ++I)
4853 Cursors[I] = cursor;
4854
4855 TokIdx = Last;
4856 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004857}
4858
Ted Kremenek6db61092010-05-05 00:55:15 +00004859static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4860 CXCursor parent,
4861 CXClientData client_data) {
4862 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4863}
4864
Ted Kremenek6628a612011-03-18 22:51:30 +00004865namespace {
4866 struct clang_annotateTokens_Data {
4867 CXTranslationUnit TU;
4868 ASTUnit *CXXUnit;
4869 CXToken *Tokens;
4870 unsigned NumTokens;
4871 CXCursor *Cursors;
4872 };
4873}
4874
Ted Kremenekab979612010-11-11 08:05:23 +00004875// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004876static void clang_annotateTokensImpl(void *UserData) {
4877 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4878 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4879 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4880 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4881 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4882
4883 // Determine the region of interest, which contains all of the tokens.
4884 SourceRange RegionOfInterest;
4885 RegionOfInterest.setBegin(
4886 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4887 RegionOfInterest.setEnd(
4888 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4889 Tokens[NumTokens-1])));
4890
4891 // A mapping from the source locations found when re-lexing or traversing the
4892 // region of interest to the corresponding cursors.
4893 AnnotateTokensData Annotated;
4894
4895 // Relex the tokens within the source range to look for preprocessing
4896 // directives.
4897 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4898 std::pair<FileID, unsigned> BeginLocInfo
4899 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4900 std::pair<FileID, unsigned> EndLocInfo
4901 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4902
Chris Lattner5f9e2722011-07-23 10:55:15 +00004903 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00004904 bool Invalid = false;
4905 if (BeginLocInfo.first == EndLocInfo.first &&
4906 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4907 !Invalid) {
4908 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4909 CXXUnit->getASTContext().getLangOptions(),
4910 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4911 Buffer.end());
4912 Lex.SetCommentRetentionState(true);
4913
4914 // Lex tokens in raw mode until we hit the end of the range, to avoid
4915 // entering #includes or expanding macros.
4916 while (true) {
4917 Token Tok;
4918 Lex.LexFromRawLexer(Tok);
4919
4920 reprocess:
4921 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4922 // We have found a preprocessing directive. Gobble it up so that we
4923 // don't see it while preprocessing these tokens later, but keep track
4924 // of all of the token locations inside this preprocessing directive so
4925 // that we can annotate them appropriately.
4926 //
4927 // FIXME: Some simple tests here could identify macro definitions and
4928 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004929 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00004930 do {
4931 Locations.push_back(Tok.getLocation());
4932 Lex.LexFromRawLexer(Tok);
4933 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4934
4935 using namespace cxcursor;
4936 CXCursor Cursor
4937 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4938 Locations.back()),
4939 TU);
4940 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4941 Annotated[Locations[I].getRawEncoding()] = Cursor;
4942 }
4943
4944 if (Tok.isAtStartOfLine())
4945 goto reprocess;
4946
4947 continue;
4948 }
4949
4950 if (Tok.is(tok::eof))
4951 break;
4952 }
4953 }
4954
4955 // Annotate all of the source locations in the region of interest that map to
4956 // a specific cursor.
4957 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4958 TU, RegionOfInterest);
4959
4960 // FIXME: We use a ridiculous stack size here because the data-recursion
4961 // algorithm uses a large stack frame than the non-data recursive version,
4962 // and AnnotationTokensWorker currently transforms the data-recursion
4963 // algorithm back into a traditional recursion by explicitly calling
4964 // VisitChildren(). We will need to remove this explicit recursive call.
4965 W.AnnotateTokens();
4966
4967 // If we ran into any entities that involve context-sensitive keywords,
4968 // take another pass through the tokens to mark them as such.
4969 if (W.hasContextSensitiveKeywords()) {
4970 for (unsigned I = 0; I != NumTokens; ++I) {
4971 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4972 continue;
4973
4974 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4975 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4976 if (ObjCPropertyDecl *Property
4977 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4978 if (Property->getPropertyAttributesAsWritten() != 0 &&
4979 llvm::StringSwitch<bool>(II->getName())
4980 .Case("readonly", true)
4981 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00004982 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004983 .Case("readwrite", true)
4984 .Case("retain", true)
4985 .Case("copy", true)
4986 .Case("nonatomic", true)
4987 .Case("atomic", true)
4988 .Case("getter", true)
4989 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00004990 .Case("strong", true)
4991 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004992 .Default(false))
4993 Tokens[I].int_data[0] = CXToken_Keyword;
4994 }
4995 continue;
4996 }
4997
4998 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
4999 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5000 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5001 if (llvm::StringSwitch<bool>(II->getName())
5002 .Case("in", true)
5003 .Case("out", true)
5004 .Case("inout", true)
5005 .Case("oneway", true)
5006 .Case("bycopy", true)
5007 .Case("byref", true)
5008 .Default(false))
5009 Tokens[I].int_data[0] = CXToken_Keyword;
5010 continue;
5011 }
5012
5013 if (Cursors[I].kind == CXCursor_CXXMethod) {
5014 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5015 if (CXXMethodDecl *Method
5016 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
5017 if ((Method->hasAttr<FinalAttr>() ||
5018 Method->hasAttr<OverrideAttr>()) &&
5019 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
5020 llvm::StringSwitch<bool>(II->getName())
5021 .Case("final", true)
5022 .Case("override", true)
5023 .Default(false))
5024 Tokens[I].int_data[0] = CXToken_Keyword;
5025 }
5026 continue;
5027 }
5028
5029 if (Cursors[I].kind == CXCursor_ClassDecl ||
5030 Cursors[I].kind == CXCursor_StructDecl ||
5031 Cursors[I].kind == CXCursor_ClassTemplate) {
5032 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5033 if (II->getName() == "final") {
5034 // We have to be careful with 'final', since it could be the name
5035 // of a member class rather than the context-sensitive keyword.
5036 // So, check whether the cursor associated with this
5037 Decl *D = getCursorDecl(Cursors[I]);
5038 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
5039 if ((Record->hasAttr<FinalAttr>()) &&
5040 Record->getIdentifier() != II)
5041 Tokens[I].int_data[0] = CXToken_Keyword;
5042 } else if (ClassTemplateDecl *ClassTemplate
5043 = dyn_cast_or_null<ClassTemplateDecl>(D)) {
5044 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
5045 if ((Record->hasAttr<FinalAttr>()) &&
5046 Record->getIdentifier() != II)
5047 Tokens[I].int_data[0] = CXToken_Keyword;
5048 }
5049 }
5050 continue;
5051 }
5052 }
5053 }
Ted Kremenekab979612010-11-11 08:05:23 +00005054}
5055
Ted Kremenek6db61092010-05-05 00:55:15 +00005056extern "C" {
5057
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005058void clang_annotateTokens(CXTranslationUnit TU,
5059 CXToken *Tokens, unsigned NumTokens,
5060 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005061
5062 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005063 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005064
Douglas Gregor4419b672010-10-21 06:10:04 +00005065 // Any token we don't specifically annotate will have a NULL cursor.
5066 CXCursor C = clang_getNullCursor();
5067 for (unsigned I = 0; I != NumTokens; ++I)
5068 Cursors[I] = C;
5069
Ted Kremeneka60ed472010-11-16 08:15:36 +00005070 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005071 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005072 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005073
Douglas Gregorbdf60622010-03-05 21:16:25 +00005074 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005075
5076 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005077 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005078 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005079 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005080 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5081 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005082}
Ted Kremenek6628a612011-03-18 22:51:30 +00005083
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005084} // end: extern "C"
5085
5086//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005087// Operations for querying linkage of a cursor.
5088//===----------------------------------------------------------------------===//
5089
5090extern "C" {
5091CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005092 if (!clang_isDeclaration(cursor.kind))
5093 return CXLinkage_Invalid;
5094
Ted Kremenek16b42592010-03-03 06:36:57 +00005095 Decl *D = cxcursor::getCursorDecl(cursor);
5096 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5097 switch (ND->getLinkage()) {
5098 case NoLinkage: return CXLinkage_NoLinkage;
5099 case InternalLinkage: return CXLinkage_Internal;
5100 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5101 case ExternalLinkage: return CXLinkage_External;
5102 };
5103
5104 return CXLinkage_Invalid;
5105}
5106} // end: extern "C"
5107
5108//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005109// Operations for querying language of a cursor.
5110//===----------------------------------------------------------------------===//
5111
5112static CXLanguageKind getDeclLanguage(const Decl *D) {
5113 switch (D->getKind()) {
5114 default:
5115 break;
5116 case Decl::ImplicitParam:
5117 case Decl::ObjCAtDefsField:
5118 case Decl::ObjCCategory:
5119 case Decl::ObjCCategoryImpl:
5120 case Decl::ObjCClass:
5121 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005122 case Decl::ObjCForwardProtocol:
5123 case Decl::ObjCImplementation:
5124 case Decl::ObjCInterface:
5125 case Decl::ObjCIvar:
5126 case Decl::ObjCMethod:
5127 case Decl::ObjCProperty:
5128 case Decl::ObjCPropertyImpl:
5129 case Decl::ObjCProtocol:
5130 return CXLanguage_ObjC;
5131 case Decl::CXXConstructor:
5132 case Decl::CXXConversion:
5133 case Decl::CXXDestructor:
5134 case Decl::CXXMethod:
5135 case Decl::CXXRecord:
5136 case Decl::ClassTemplate:
5137 case Decl::ClassTemplatePartialSpecialization:
5138 case Decl::ClassTemplateSpecialization:
5139 case Decl::Friend:
5140 case Decl::FriendTemplate:
5141 case Decl::FunctionTemplate:
5142 case Decl::LinkageSpec:
5143 case Decl::Namespace:
5144 case Decl::NamespaceAlias:
5145 case Decl::NonTypeTemplateParm:
5146 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005147 case Decl::TemplateTemplateParm:
5148 case Decl::TemplateTypeParm:
5149 case Decl::UnresolvedUsingTypename:
5150 case Decl::UnresolvedUsingValue:
5151 case Decl::Using:
5152 case Decl::UsingDirective:
5153 case Decl::UsingShadow:
5154 return CXLanguage_CPlusPlus;
5155 }
5156
5157 return CXLanguage_C;
5158}
5159
5160extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005161
5162enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5163 if (clang_isDeclaration(cursor.kind))
5164 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005165 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005166 return CXAvailability_Available;
5167
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005168 switch (D->getAvailability()) {
5169 case AR_Available:
5170 case AR_NotYetIntroduced:
5171 return CXAvailability_Available;
5172
5173 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005174 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005175
5176 case AR_Unavailable:
5177 return CXAvailability_NotAvailable;
5178 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005179 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005180
Douglas Gregor58ddb602010-08-23 23:00:57 +00005181 return CXAvailability_Available;
5182}
5183
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005184CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5185 if (clang_isDeclaration(cursor.kind))
5186 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5187
5188 return CXLanguage_Invalid;
5189}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005190
5191 /// \brief If the given cursor is the "templated" declaration
5192 /// descibing a class or function template, return the class or
5193 /// function template.
5194static Decl *maybeGetTemplateCursor(Decl *D) {
5195 if (!D)
5196 return 0;
5197
5198 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5199 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5200 return FunTmpl;
5201
5202 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5203 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5204 return ClassTmpl;
5205
5206 return D;
5207}
5208
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005209CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5210 if (clang_isDeclaration(cursor.kind)) {
5211 if (Decl *D = getCursorDecl(cursor)) {
5212 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005213 if (!DC)
5214 return clang_getNullCursor();
5215
5216 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5217 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005218 }
5219 }
5220
5221 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5222 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005223 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005224 }
5225
5226 return clang_getNullCursor();
5227}
5228
5229CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5230 if (clang_isDeclaration(cursor.kind)) {
5231 if (Decl *D = getCursorDecl(cursor)) {
5232 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005233 if (!DC)
5234 return clang_getNullCursor();
5235
5236 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5237 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005238 }
5239 }
5240
5241 // FIXME: Note that we can't easily compute the lexical context of a
5242 // statement or expression, so we return nothing.
5243 return clang_getNullCursor();
5244}
5245
Douglas Gregor9f592342010-10-01 20:25:15 +00005246static void CollectOverriddenMethods(DeclContext *Ctx,
5247 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005248 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005249 if (!Ctx)
5250 return;
5251
5252 // If we have a class or category implementation, jump straight to the
5253 // interface.
5254 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5255 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5256
5257 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5258 if (!Container)
5259 return;
5260
5261 // Check whether we have a matching method at this level.
5262 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5263 Method->isInstanceMethod()))
5264 if (Method != Overridden) {
5265 // We found an override at this level; there is no need to look
5266 // into other protocols or categories.
5267 Methods.push_back(Overridden);
5268 return;
5269 }
5270
5271 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5272 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5273 PEnd = Protocol->protocol_end();
5274 P != PEnd; ++P)
5275 CollectOverriddenMethods(*P, Method, Methods);
5276 }
5277
5278 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5279 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5280 PEnd = Category->protocol_end();
5281 P != PEnd; ++P)
5282 CollectOverriddenMethods(*P, Method, Methods);
5283 }
5284
5285 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5286 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5287 PEnd = Interface->protocol_end();
5288 P != PEnd; ++P)
5289 CollectOverriddenMethods(*P, Method, Methods);
5290
5291 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5292 Category; Category = Category->getNextClassCategory())
5293 CollectOverriddenMethods(Category, Method, Methods);
5294
5295 // We only look into the superclass if we haven't found anything yet.
5296 if (Methods.empty())
5297 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5298 return CollectOverriddenMethods(Super, Method, Methods);
5299 }
5300}
5301
5302void clang_getOverriddenCursors(CXCursor cursor,
5303 CXCursor **overridden,
5304 unsigned *num_overridden) {
5305 if (overridden)
5306 *overridden = 0;
5307 if (num_overridden)
5308 *num_overridden = 0;
5309 if (!overridden || !num_overridden)
5310 return;
5311
5312 if (!clang_isDeclaration(cursor.kind))
5313 return;
5314
5315 Decl *D = getCursorDecl(cursor);
5316 if (!D)
5317 return;
5318
5319 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005320 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005321 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5322 *num_overridden = CXXMethod->size_overridden_methods();
5323 if (!*num_overridden)
5324 return;
5325
5326 *overridden = new CXCursor [*num_overridden];
5327 unsigned I = 0;
5328 for (CXXMethodDecl::method_iterator
5329 M = CXXMethod->begin_overridden_methods(),
5330 MEnd = CXXMethod->end_overridden_methods();
5331 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005332 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005333 return;
5334 }
5335
5336 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5337 if (!Method)
5338 return;
5339
5340 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005341 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005342 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5343
5344 if (Methods.empty())
5345 return;
5346
5347 *num_overridden = Methods.size();
5348 *overridden = new CXCursor [Methods.size()];
5349 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005350 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005351}
5352
5353void clang_disposeOverriddenCursors(CXCursor *overridden) {
5354 delete [] overridden;
5355}
5356
Douglas Gregorecdcb882010-10-20 22:00:55 +00005357CXFile clang_getIncludedFile(CXCursor cursor) {
5358 if (cursor.kind != CXCursor_InclusionDirective)
5359 return 0;
5360
5361 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5362 return (void *)ID->getFile();
5363}
5364
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005365} // end: extern "C"
5366
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005367
5368//===----------------------------------------------------------------------===//
5369// C++ AST instrospection.
5370//===----------------------------------------------------------------------===//
5371
5372extern "C" {
5373unsigned clang_CXXMethod_isStatic(CXCursor C) {
5374 if (!clang_isDeclaration(C.kind))
5375 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005376
5377 CXXMethodDecl *Method = 0;
5378 Decl *D = cxcursor::getCursorDecl(C);
5379 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5380 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5381 else
5382 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5383 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005384}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005385
Douglas Gregor211924b2011-05-12 15:17:24 +00005386unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5387 if (!clang_isDeclaration(C.kind))
5388 return 0;
5389
5390 CXXMethodDecl *Method = 0;
5391 Decl *D = cxcursor::getCursorDecl(C);
5392 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5393 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5394 else
5395 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5396 return (Method && Method->isVirtual()) ? 1 : 0;
5397}
5398
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005399} // end: extern "C"
5400
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005401//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005402// Attribute introspection.
5403//===----------------------------------------------------------------------===//
5404
5405extern "C" {
5406CXType clang_getIBOutletCollectionType(CXCursor C) {
5407 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005408 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005409
5410 IBOutletCollectionAttr *A =
5411 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5412
Douglas Gregor841b2382011-03-06 18:55:32 +00005413 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005414}
5415} // end: extern "C"
5416
5417//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005418// Inspecting memory usage.
5419//===----------------------------------------------------------------------===//
5420
Ted Kremenekf7870022011-04-20 16:41:07 +00005421typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005422
Ted Kremenekf7870022011-04-20 16:41:07 +00005423static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5424 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005425 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005426 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005427 entries.push_back(entry);
5428}
5429
5430extern "C" {
5431
Ted Kremenekf7870022011-04-20 16:41:07 +00005432const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005433 const char *str = "";
5434 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005435 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005436 str = "ASTContext: expressions, declarations, and types";
5437 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005438 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005439 str = "ASTContext: identifiers";
5440 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005441 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005442 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005443 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005444 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005445 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005446 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005447 case CXTUResourceUsage_SourceManagerContentCache:
5448 str = "SourceManager: content cache allocator";
5449 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005450 case CXTUResourceUsage_AST_SideTables:
5451 str = "ASTContext: side tables";
5452 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005453 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5454 str = "SourceManager: malloc'ed memory buffers";
5455 break;
5456 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5457 str = "SourceManager: mmap'ed memory buffers";
5458 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005459 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5460 str = "ExternalASTSource: malloc'ed memory buffers";
5461 break;
5462 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5463 str = "ExternalASTSource: mmap'ed memory buffers";
5464 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005465 case CXTUResourceUsage_Preprocessor:
5466 str = "Preprocessor: malloc'ed memory";
5467 break;
5468 case CXTUResourceUsage_PreprocessingRecord:
5469 str = "Preprocessor: PreprocessingRecord";
5470 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005471 case CXTUResourceUsage_SourceManager_DataStructures:
5472 str = "SourceManager: data structures and tables";
5473 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005474 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5475 str = "Preprocessor: header search tables";
5476 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005477 }
5478 return str;
5479}
5480
Ted Kremenekf7870022011-04-20 16:41:07 +00005481CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005482 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005483 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005484 return usage;
5485 }
5486
5487 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5488 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5489 ASTContext &astContext = astUnit->getASTContext();
5490
5491 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005492 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005493 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005494
5495 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005496 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005497 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5498
5499 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005500 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005501 (unsigned long) astContext.Selectors.getTotalMemory());
5502
Ted Kremenekba29bd22011-04-28 04:53:38 +00005503 // How much memory is used by ASTContext's side tables?
5504 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5505 (unsigned long) astContext.getSideTableAllocatedMemory());
5506
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005507 // How much memory is used for caching global code completion results?
5508 unsigned long completionBytes = 0;
5509 if (GlobalCodeCompletionAllocator *completionAllocator =
5510 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005511 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005512 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005513 createCXTUResourceUsageEntry(*entries,
5514 CXTUResourceUsage_GlobalCompletionResults,
5515 completionBytes);
5516
5517 // How much memory is being used by SourceManager's content cache?
5518 createCXTUResourceUsageEntry(*entries,
5519 CXTUResourceUsage_SourceManagerContentCache,
5520 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005521
5522 // How much memory is being used by the MemoryBuffer's in SourceManager?
5523 const SourceManager::MemoryBufferSizes &srcBufs =
5524 astUnit->getSourceManager().getMemoryBufferSizes();
5525
5526 createCXTUResourceUsageEntry(*entries,
5527 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5528 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005529 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005530 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5531 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005532 createCXTUResourceUsageEntry(*entries,
5533 CXTUResourceUsage_SourceManager_DataStructures,
5534 (unsigned long) astContext.getSourceManager()
5535 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005536
5537 // How much memory is being used by the ExternalASTSource?
5538 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5539 const ExternalASTSource::MemoryBufferSizes &sizes =
5540 esrc->getMemoryBufferSizes();
5541
5542 createCXTUResourceUsageEntry(*entries,
5543 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5544 (unsigned long) sizes.malloc_bytes);
5545 createCXTUResourceUsageEntry(*entries,
5546 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5547 (unsigned long) sizes.mmap_bytes);
5548 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005549
5550 // How much memory is being used by the Preprocessor?
5551 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005552 createCXTUResourceUsageEntry(*entries,
5553 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005554 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005555
5556 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5557 createCXTUResourceUsageEntry(*entries,
5558 CXTUResourceUsage_PreprocessingRecord,
5559 pRec->getTotalMemory());
5560 }
5561
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005562 createCXTUResourceUsageEntry(*entries,
5563 CXTUResourceUsage_Preprocessor_HeaderSearch,
5564 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005565
Ted Kremenekf7870022011-04-20 16:41:07 +00005566 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005567 (unsigned) entries->size(),
5568 entries->size() ? &(*entries)[0] : 0 };
5569 entries.take();
5570 return usage;
5571}
5572
Ted Kremenekf7870022011-04-20 16:41:07 +00005573void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005574 if (usage.data)
5575 delete (MemUsageEntries*) usage.data;
5576}
5577
5578} // end extern "C"
5579
Douglas Gregor6df78732011-05-05 20:27:22 +00005580void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5581 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5582 for (unsigned I = 0; I != Usage.numEntries; ++I)
5583 fprintf(stderr, " %s: %lu\n",
5584 clang_getTUResourceUsageName(Usage.entries[I].kind),
5585 Usage.entries[I].amount);
5586
5587 clang_disposeCXTUResourceUsage(Usage);
5588}
5589
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005590//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005591// Misc. utility functions.
5592//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005593
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005594/// Default to using an 8 MB stack size on "safety" threads.
5595static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005596
5597namespace clang {
5598
5599bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005600 void (*Fn)(void*), void *UserData,
5601 unsigned Size) {
5602 if (!Size)
5603 Size = GetSafetyThreadStackSize();
5604 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005605 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5606 return CRC.RunSafely(Fn, UserData);
5607}
5608
5609unsigned GetSafetyThreadStackSize() {
5610 return SafetyStackThreadSize;
5611}
5612
5613void SetSafetyThreadStackSize(unsigned Value) {
5614 SafetyStackThreadSize = Value;
5615}
5616
5617}
5618
Ted Kremenek04bb7162010-01-22 22:44:15 +00005619extern "C" {
5620
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005621CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005622 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005623}
5624
5625} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005626