blob: 8104828eccec154f4b20954e7708e6f8af851c4b [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);
Douglas Gregor01829d32010-08-31 14:41:23 +0000351 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000352 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000353 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000354 // FIXME: Implement visitors here when the unimplemented TypeLocs get
355 // implemented
356 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000357 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000358 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Sean Huntca63c202011-05-24 22:41:36 +0000359 bool VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000360 bool VisitDependentNameTypeLoc(DependentNameTypeLoc TL);
Douglas Gregor94fdffa2011-03-01 20:11:18 +0000361 bool VisitDependentTemplateSpecializationTypeLoc(
362 DependentTemplateSpecializationTypeLoc TL);
Douglas Gregor9e876872011-03-01 18:12:44 +0000363 bool VisitElaboratedTypeLoc(ElaboratedTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000364
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000365 // Data-recursive visitor functions.
366 bool IsInRegionOfInterest(CXCursor C);
367 bool RunVisitorWorkList(VisitorWorkList &WL);
368 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000369 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000370};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000371
Ted Kremenekab188932010-01-05 19:32:54 +0000372} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000373
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000374static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000375static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
376
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000377
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000378RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000379 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000380}
381
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382/// \brief Visit the given cursor and, if requested by the visitor,
383/// its children.
384///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385/// \param Cursor the cursor to visit.
386///
387/// \param CheckRegionOfInterest if true, then the caller already checked that
388/// this cursor is within the region of interest.
389///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000390/// \returns true if the visitation should be aborted, false if it
391/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000393 if (clang_isInvalid(Cursor.kind))
394 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000395
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 if (clang_isDeclaration(Cursor.kind)) {
397 Decl *D = getCursorDecl(Cursor);
398 assert(D && "Invalid declaration cursor");
399 if (D->getPCHLevel() > MaxPCHLevel)
400 return false;
401
402 if (D->isImplicit())
403 return false;
404 }
405
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000406 // If we have a range of interest, and this cursor doesn't intersect with it,
407 // we're done.
408 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000409 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000410 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000411 return false;
412 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000413
Douglas Gregorb1373d02010-01-20 20:59:29 +0000414 switch (Visitor(Cursor, Parent, ClientData)) {
415 case CXChildVisit_Break:
416 return true;
417
418 case CXChildVisit_Continue:
419 return false;
420
421 case CXChildVisit_Recurse:
422 return VisitChildren(Cursor);
423 }
424
Douglas Gregorfd643772010-01-25 16:45:46 +0000425 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000426}
427
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000428bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000430 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000431
432 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000433 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
434
435 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
436 // If we would only look at local declarations but we have a region of
437 // interest, check whether that region of interest is in the main file.
438 // If not, we should traverse all declarations.
439 // FIXME: My kingdom for a proper binary search approach to finding
440 // cursors!
441 std::pair<FileID, unsigned> Location
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000442 = AU->getSourceManager().getDecomposedExpansionLoc(
Douglas Gregor32038bb2010-12-21 19:07:48 +0000443 RegionOfInterest.getBegin());
444 if (Location.first != AU->getSourceManager().getMainFileID())
445 OnlyLocalDecls = false;
446 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000447
Douglas Gregor89d99802010-11-30 06:16:57 +0000448 PreprocessingRecord::iterator StartEntity, EndEntity;
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000449 if (OnlyLocalDecls && AU->pp_entity_begin() != AU->pp_entity_end())
450 return visitPreprocessedEntitiesInRegion(AU->pp_entity_begin(),
451 AU->pp_entity_end());
452 else
453 return visitPreprocessedEntitiesInRegion(PPRec.begin(), PPRec.end());
454}
455
456template<typename InputIterator>
457bool CursorVisitor::visitPreprocessedEntitiesInRegion(InputIterator First,
458 InputIterator Last) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000459 // There is no region of interest; we have to walk everything.
460 if (RegionOfInterest.isInvalid())
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000461 return visitPreprocessedEntities(First, Last);
462
Douglas Gregor788f5a12010-03-20 00:41:21 +0000463 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000464 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000465 std::pair<FileID, unsigned> Begin
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000466 = SM.getDecomposedExpansionLoc(RegionOfInterest.getBegin());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000467 std::pair<FileID, unsigned> End
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000468 = SM.getDecomposedExpansionLoc(RegionOfInterest.getEnd());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000469
470 // The region of interest spans files; we have to walk everything.
471 if (Begin.first != End.first)
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000472 return visitPreprocessedEntities(First, Last);
473
Douglas Gregor788f5a12010-03-20 00:41:21 +0000474 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000475 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000476 if (ByFileMap.empty()) {
477 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000478 for (; First != Last; ++First) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000479 std::pair<FileID, unsigned> P
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000480 = SM.getDecomposedExpansionLoc((*First)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000481
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000482 ByFileMap[P.first].push_back(*First);
483 }
484 }
485
486 return visitPreprocessedEntities(ByFileMap[Begin.first].begin(),
487 ByFileMap[Begin.first].end());
488}
489
490template<typename InputIterator>
491bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
492 InputIterator Last) {
493 for (; First != Last; ++First) {
494 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
495 if (Visit(MakeMacroExpansionCursor(ME, TU)))
496 return true;
497
498 continue;
499 }
500
501 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
502 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
503 return true;
504
505 continue;
506 }
507
508 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
509 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
510 return true;
511
512 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000513 }
514 }
515
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000516 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000517}
518
Douglas Gregorb1373d02010-01-20 20:59:29 +0000519/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000520///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521/// \returns true if the visitation should be aborted, false if it
522/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000523bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000524 if (clang_isReference(Cursor.kind) &&
525 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000526 // By definition, references have no children.
527 return false;
528 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000529
530 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000531 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000532 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000533
Douglas Gregorb1373d02010-01-20 20:59:29 +0000534 if (clang_isDeclaration(Cursor.kind)) {
535 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000536 if (!D)
537 return false;
538
Ted Kremenek539311e2010-02-18 18:47:01 +0000539 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000541
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000542 if (clang_isStatement(Cursor.kind)) {
543 if (Stmt *S = getCursorStmt(Cursor))
544 return Visit(S);
545
546 return false;
547 }
548
549 if (clang_isExpression(Cursor.kind)) {
550 if (Expr *E = getCursorExpr(Cursor))
551 return Visit(E);
552
553 return false;
554 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000555
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000557 CXTranslationUnit tu = getCursorTU(Cursor);
558 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000559
560 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
561 for (unsigned I = 0; I != 2; ++I) {
562 if (VisitOrder[I]) {
563 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
564 RegionOfInterest.isInvalid()) {
565 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
566 TLEnd = CXXUnit->top_level_end();
567 TL != TLEnd; ++TL) {
568 if (Visit(MakeCXCursor(*TL, tu), true))
569 return true;
570 }
571 } else if (VisitDeclContext(
572 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000573 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000574 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000575 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000576
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000577 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000578 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
579 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000580 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000581
Douglas Gregor7b691f332010-01-20 21:13:59 +0000582 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000584
Douglas Gregorc314aa42011-03-02 19:17:03 +0000585 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
586 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
587 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
588 return Visit(BaseTSInfo->getTypeLoc());
589 }
590 }
591 }
592
Douglas Gregorb1373d02010-01-20 20:59:29 +0000593 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594 return false;
595}
596
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000597bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000598 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
599 if (Visit(TSInfo->getTypeLoc()))
600 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000601
Ted Kremenek664cffd2010-07-22 11:30:19 +0000602 if (Stmt *Body = B->getBody())
603 return Visit(MakeCXCursor(Body, StmtParent, TU));
604
605 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000606}
607
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000608llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
609 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000610 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000611 if (Range.isInvalid())
612 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000613
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000614 switch (CompareRegionOfInterest(Range)) {
615 case RangeBefore:
616 // This declaration comes before the region of interest; skip it.
617 return llvm::Optional<bool>();
618
619 case RangeAfter:
620 // This declaration comes after the region of interest; we're done.
621 return false;
622
623 case RangeOverlap:
624 // This declaration overlaps the region of interest; visit it.
625 break;
626 }
627 }
628 return true;
629}
630
631bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
632 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
633
634 // FIXME: Eventually remove. This part of a hack to support proper
635 // iteration over all Decls contained lexically within an ObjC container.
636 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
637 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
638
639 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000640 Decl *D = *I;
641 if (D->getLexicalDeclContext() != DC)
642 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000643 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000644 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
645 if (!V.hasValue())
646 continue;
647 if (!V.getValue())
648 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000649 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000650 return true;
651 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000652 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000653}
654
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000655bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
656 llvm_unreachable("Translation units are visited directly by Visit()");
657 return false;
658}
659
Richard Smith162e1c12011-04-15 14:24:37 +0000660bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
661 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
662 return Visit(TSInfo->getTypeLoc());
663
664 return false;
665}
666
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000667bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
668 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
669 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000670
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000671 return false;
672}
673
674bool CursorVisitor::VisitTagDecl(TagDecl *D) {
675 return VisitDeclContext(D);
676}
677
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000678bool CursorVisitor::VisitClassTemplateSpecializationDecl(
679 ClassTemplateSpecializationDecl *D) {
680 bool ShouldVisitBody = false;
681 switch (D->getSpecializationKind()) {
682 case TSK_Undeclared:
683 case TSK_ImplicitInstantiation:
684 // Nothing to visit
685 return false;
686
687 case TSK_ExplicitInstantiationDeclaration:
688 case TSK_ExplicitInstantiationDefinition:
689 break;
690
691 case TSK_ExplicitSpecialization:
692 ShouldVisitBody = true;
693 break;
694 }
695
696 // Visit the template arguments used in the specialization.
697 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
698 TypeLoc TL = SpecType->getTypeLoc();
699 if (TemplateSpecializationTypeLoc *TSTLoc
700 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
701 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
702 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
703 return true;
704 }
705 }
706
707 if (ShouldVisitBody && VisitCXXRecordDecl(D))
708 return true;
709
710 return false;
711}
712
Douglas Gregor74dbe642010-08-31 19:31:58 +0000713bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
714 ClassTemplatePartialSpecializationDecl *D) {
715 // FIXME: Visit the "outer" template parameter lists on the TagDecl
716 // before visiting these template parameters.
717 if (VisitTemplateParameters(D->getTemplateParameters()))
718 return true;
719
720 // Visit the partial specialization arguments.
721 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
722 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
723 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
724 return true;
725
726 return VisitCXXRecordDecl(D);
727}
728
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000729bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000730 // Visit the default argument.
731 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
732 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
733 if (Visit(DefArg->getTypeLoc()))
734 return true;
735
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000736 return false;
737}
738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
740 if (Expr *Init = D->getInitExpr())
741 return Visit(MakeCXCursor(Init, StmtParent, TU));
742 return false;
743}
744
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000745bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
746 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
747 if (Visit(TSInfo->getTypeLoc()))
748 return true;
749
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000750 // Visit the nested-name-specifier, if present.
751 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
752 if (VisitNestedNameSpecifierLoc(QualifierLoc))
753 return true;
754
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000755 return false;
756}
757
Douglas Gregora67e03f2010-09-09 21:42:20 +0000758/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000759static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
760 CXXCtorInitializer const * const *X
761 = static_cast<CXXCtorInitializer const * const *>(Xp);
762 CXXCtorInitializer const * const *Y
763 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000764
765 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
766 return -1;
767 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
768 return 1;
769 else
770 return 0;
771}
772
Douglas Gregorb1373d02010-01-20 20:59:29 +0000773bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000774 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
775 // Visit the function declaration's syntactic components in the order
776 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000777 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000778 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
779
780 // If we have a function declared directly (without the use of a typedef),
781 // visit just the return type. Otherwise, just visit the function's type
782 // now.
783 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
784 (!FTL && Visit(TL)))
785 return true;
786
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000787 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000788 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
789 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000790 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000791
792 // Visit the declaration name.
793 if (VisitDeclarationNameInfo(ND->getNameInfo()))
794 return true;
795
796 // FIXME: Visit explicitly-specified template arguments!
797
798 // Visit the function parameters, if we have a function type.
799 if (FTL && VisitFunctionTypeLoc(*FTL, true))
800 return true;
801
802 // FIXME: Attributes?
803 }
804
Sean Hunt10620eb2011-05-06 20:44:56 +0000805 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000806 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
807 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000808 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000809 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
810 IEnd = Constructor->init_end();
811 I != IEnd; ++I) {
812 if (!(*I)->isWritten())
813 continue;
814
815 WrittenInits.push_back(*I);
816 }
817
818 // Sort the initializers in source order
819 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000820 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000821
822 // Visit the initializers in source order
823 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000824 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000825 if (Init->isAnyMemberInitializer()) {
826 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000827 Init->getMemberLocation(), TU)))
828 return true;
829 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
830 if (Visit(BaseInfo->getTypeLoc()))
831 return true;
832 }
833
834 // Visit the initializer value.
835 if (Expr *Initializer = Init->getInit())
836 if (Visit(MakeCXCursor(Initializer, ND, TU)))
837 return true;
838 }
839 }
840
841 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
842 return true;
843 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000844
Douglas Gregorb1373d02010-01-20 20:59:29 +0000845 return false;
846}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000847
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
849 if (VisitDeclaratorDecl(D))
850 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000851
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000852 if (Expr *BitWidth = D->getBitWidth())
853 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000854
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855 return false;
856}
857
858bool CursorVisitor::VisitVarDecl(VarDecl *D) {
859 if (VisitDeclaratorDecl(D))
860 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000861
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000862 if (Expr *Init = D->getInit())
863 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000864
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000865 return false;
866}
867
Douglas Gregor84b51d72010-09-01 20:16:53 +0000868bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
869 if (VisitDeclaratorDecl(D))
870 return true;
871
872 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
873 if (Expr *DefArg = D->getDefaultArgument())
874 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
875
876 return false;
877}
878
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000879bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
880 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
881 // before visiting these template parameters.
882 if (VisitTemplateParameters(D->getTemplateParameters()))
883 return true;
884
885 return VisitFunctionDecl(D->getTemplatedDecl());
886}
887
Douglas Gregor39d6f072010-08-31 19:02:00 +0000888bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
889 // FIXME: Visit the "outer" template parameter lists on the TagDecl
890 // before visiting these template parameters.
891 if (VisitTemplateParameters(D->getTemplateParameters()))
892 return true;
893
894 return VisitCXXRecordDecl(D->getTemplatedDecl());
895}
896
Douglas Gregor84b51d72010-09-01 20:16:53 +0000897bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
898 if (VisitTemplateParameters(D->getTemplateParameters()))
899 return true;
900
901 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
902 VisitTemplateArgumentLoc(D->getDefaultArgument()))
903 return true;
904
905 return false;
906}
907
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000908bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000909 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
910 if (Visit(TSInfo->getTypeLoc()))
911 return true;
912
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000913 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000914 PEnd = ND->param_end();
915 P != PEnd; ++P) {
916 if (Visit(MakeCXCursor(*P, TU)))
917 return true;
918 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000919
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000920 if (ND->isThisDeclarationADefinition() &&
921 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
922 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000923
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000924 return false;
925}
926
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000927namespace {
928 struct ContainerDeclsSort {
929 SourceManager &SM;
930 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
931 bool operator()(Decl *A, Decl *B) {
932 SourceLocation L_A = A->getLocStart();
933 SourceLocation L_B = B->getLocStart();
934 assert(L_A.isValid() && L_B.isValid());
935 return SM.isBeforeInTranslationUnit(L_A, L_B);
936 }
937 };
938}
939
Douglas Gregora59e3902010-01-21 23:27:09 +0000940bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000941 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
942 // an @implementation can lexically contain Decls that are not properly
943 // nested in the AST. When we identify such cases, we need to retrofit
944 // this nesting here.
945 if (!DI_current)
946 return VisitDeclContext(D);
947
948 // Scan the Decls that immediately come after the container
949 // in the current DeclContext. If any fall within the
950 // container's lexical region, stash them into a vector
951 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000952 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000953 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000954 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000955 if (EndLoc.isValid()) {
956 DeclContext::decl_iterator next = *DI_current;
957 while (++next != DE_current) {
958 Decl *D_next = *next;
959 if (!D_next)
960 break;
961 SourceLocation L = D_next->getLocStart();
962 if (!L.isValid())
963 break;
964 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
965 *DI_current = next;
966 DeclsInContainer.push_back(D_next);
967 continue;
968 }
969 break;
970 }
971 }
972
973 // The common case.
974 if (DeclsInContainer.empty())
975 return VisitDeclContext(D);
976
977 // Get all the Decls in the DeclContext, and sort them with the
978 // additional ones we've collected. Then visit them.
979 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
980 I!=E; ++I) {
981 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000982 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
983 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000984 continue;
985 DeclsInContainer.push_back(subDecl);
986 }
987
988 // Now sort the Decls so that they appear in lexical order.
989 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
990 ContainerDeclsSort(SM));
991
992 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000993 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000994 E = DeclsInContainer.end(); I != E; ++I) {
995 CXCursor Cursor = MakeCXCursor(*I, TU);
996 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
997 if (!V.hasValue())
998 continue;
999 if (!V.getValue())
1000 return false;
1001 if (Visit(Cursor, true))
1002 return true;
1003 }
1004 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001005}
1006
Douglas Gregorb1373d02010-01-20 20:59:29 +00001007bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001008 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1009 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001010 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001011
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001012 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1013 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1014 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001015 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001016 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001017
Douglas Gregora59e3902010-01-21 23:27:09 +00001018 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001019}
1020
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001021bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1022 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1023 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1024 E = PID->protocol_end(); I != E; ++I, ++PL)
1025 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1026 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028 return VisitObjCContainerDecl(PID);
1029}
1030
Ted Kremenek23173d72010-05-18 21:09:07 +00001031bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001032 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001033 return true;
1034
Ted Kremenek23173d72010-05-18 21:09:07 +00001035 // FIXME: This implements a workaround with @property declarations also being
1036 // installed in the DeclContext for the @interface. Eventually this code
1037 // should be removed.
1038 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1039 if (!CDecl || !CDecl->IsClassExtension())
1040 return false;
1041
1042 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1043 if (!ID)
1044 return false;
1045
1046 IdentifierInfo *PropertyId = PD->getIdentifier();
1047 ObjCPropertyDecl *prevDecl =
1048 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1049
1050 if (!prevDecl)
1051 return false;
1052
1053 // Visit synthesized methods since they will be skipped when visiting
1054 // the @interface.
1055 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001056 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001057 if (Visit(MakeCXCursor(MD, TU)))
1058 return true;
1059
1060 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001061 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001062 if (Visit(MakeCXCursor(MD, TU)))
1063 return true;
1064
1065 return false;
1066}
1067
Douglas Gregorb1373d02010-01-20 20:59:29 +00001068bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001069 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001070 if (D->getSuperClass() &&
1071 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001072 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001073 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001074 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001075
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001076 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1077 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1078 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001079 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001080 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001081
Douglas Gregora59e3902010-01-21 23:27:09 +00001082 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001083}
1084
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001085bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1086 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001087}
1088
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001089bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001090 // 'ID' could be null when dealing with invalid code.
1091 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1092 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1093 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001094
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001095 return VisitObjCImplDecl(D);
1096}
1097
1098bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1099#if 0
1100 // Issue callbacks for super class.
1101 // FIXME: No source location information!
1102 if (D->getSuperClass() &&
1103 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001104 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001105 TU)))
1106 return true;
1107#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001108
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001109 return VisitObjCImplDecl(D);
1110}
1111
1112bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1113 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1114 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1115 E = D->protocol_end();
1116 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001117 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001118 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001119
1120 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001121}
1122
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001123bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1124 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1125 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1126 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001127
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001128 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001129}
1130
Douglas Gregora4ffd852010-11-17 01:03:52 +00001131bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1132 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1133 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1134
1135 return false;
1136}
1137
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001138bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1139 return VisitDeclContext(D);
1140}
1141
Douglas Gregor69319002010-08-31 23:48:11 +00001142bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001143 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001144 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1145 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001146 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001147
1148 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1149 D->getTargetNameLoc(), TU));
1150}
1151
Douglas Gregor7e242562010-09-01 19:52:22 +00001152bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001153 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001154 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1155 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001156 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001157 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001158
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001159 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1160 return true;
1161
Douglas Gregor7e242562010-09-01 19:52:22 +00001162 return VisitDeclarationNameInfo(D->getNameInfo());
1163}
1164
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001165bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001166 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001167 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1168 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001169 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001170
1171 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1172 D->getIdentLocation(), TU));
1173}
1174
Douglas Gregor7e242562010-09-01 19:52:22 +00001175bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001176 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001177 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1178 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001179 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001180 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001181
Douglas Gregor7e242562010-09-01 19:52:22 +00001182 return VisitDeclarationNameInfo(D->getNameInfo());
1183}
1184
1185bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1186 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001187 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001188 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1189 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001190 return true;
1191
Douglas Gregor7e242562010-09-01 19:52:22 +00001192 return false;
1193}
1194
Douglas Gregor01829d32010-08-31 14:41:23 +00001195bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1196 switch (Name.getName().getNameKind()) {
1197 case clang::DeclarationName::Identifier:
1198 case clang::DeclarationName::CXXLiteralOperatorName:
1199 case clang::DeclarationName::CXXOperatorName:
1200 case clang::DeclarationName::CXXUsingDirective:
1201 return false;
1202
1203 case clang::DeclarationName::CXXConstructorName:
1204 case clang::DeclarationName::CXXDestructorName:
1205 case clang::DeclarationName::CXXConversionFunctionName:
1206 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1207 return Visit(TSInfo->getTypeLoc());
1208 return false;
1209
1210 case clang::DeclarationName::ObjCZeroArgSelector:
1211 case clang::DeclarationName::ObjCOneArgSelector:
1212 case clang::DeclarationName::ObjCMultiArgSelector:
1213 // FIXME: Per-identifier location info?
1214 return false;
1215 }
1216
1217 return false;
1218}
1219
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001220bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1221 SourceRange Range) {
1222 // FIXME: This whole routine is a hack to work around the lack of proper
1223 // source information in nested-name-specifiers (PR5791). Since we do have
1224 // a beginning source location, we can visit the first component of the
1225 // nested-name-specifier, if it's a single-token component.
1226 if (!NNS)
1227 return false;
1228
1229 // Get the first component in the nested-name-specifier.
1230 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1231 NNS = Prefix;
1232
1233 switch (NNS->getKind()) {
1234 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001235 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1236 TU));
1237
Douglas Gregor14aba762011-02-24 02:36:08 +00001238 case NestedNameSpecifier::NamespaceAlias:
1239 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1240 Range.getBegin(), TU));
1241
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001242 case NestedNameSpecifier::TypeSpec: {
1243 // If the type has a form where we know that the beginning of the source
1244 // range matches up with a reference cursor. Visit the appropriate reference
1245 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001246 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001247 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1248 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1249 if (const TagType *Tag = dyn_cast<TagType>(T))
1250 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1251 if (const TemplateSpecializationType *TST
1252 = dyn_cast<TemplateSpecializationType>(T))
1253 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1254 break;
1255 }
1256
1257 case NestedNameSpecifier::TypeSpecWithTemplate:
1258 case NestedNameSpecifier::Global:
1259 case NestedNameSpecifier::Identifier:
1260 break;
1261 }
1262
1263 return false;
1264}
1265
Douglas Gregordc355712011-02-25 00:36:19 +00001266bool
1267CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001268 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001269 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1270 Qualifiers.push_back(Qualifier);
1271
1272 while (!Qualifiers.empty()) {
1273 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1274 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1275 switch (NNS->getKind()) {
1276 case NestedNameSpecifier::Namespace:
1277 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001278 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001279 TU)))
1280 return true;
1281
1282 break;
1283
1284 case NestedNameSpecifier::NamespaceAlias:
1285 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001286 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001287 TU)))
1288 return true;
1289
1290 break;
1291
1292 case NestedNameSpecifier::TypeSpec:
1293 case NestedNameSpecifier::TypeSpecWithTemplate:
1294 if (Visit(Q.getTypeLoc()))
1295 return true;
1296
1297 break;
1298
1299 case NestedNameSpecifier::Global:
1300 case NestedNameSpecifier::Identifier:
1301 break;
1302 }
1303 }
1304
1305 return false;
1306}
1307
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001308bool CursorVisitor::VisitTemplateParameters(
1309 const TemplateParameterList *Params) {
1310 if (!Params)
1311 return false;
1312
1313 for (TemplateParameterList::const_iterator P = Params->begin(),
1314 PEnd = Params->end();
1315 P != PEnd; ++P) {
1316 if (Visit(MakeCXCursor(*P, TU)))
1317 return true;
1318 }
1319
1320 return false;
1321}
1322
Douglas Gregor0b36e612010-08-31 20:37:03 +00001323bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1324 switch (Name.getKind()) {
1325 case TemplateName::Template:
1326 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1327
1328 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001329 // Visit the overloaded template set.
1330 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1331 return true;
1332
Douglas Gregor0b36e612010-08-31 20:37:03 +00001333 return false;
1334
1335 case TemplateName::DependentTemplate:
1336 // FIXME: Visit nested-name-specifier.
1337 return false;
1338
1339 case TemplateName::QualifiedTemplate:
1340 // FIXME: Visit nested-name-specifier.
1341 return Visit(MakeCursorTemplateRef(
1342 Name.getAsQualifiedTemplateName()->getDecl(),
1343 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001344
1345 case TemplateName::SubstTemplateTemplateParm:
1346 return Visit(MakeCursorTemplateRef(
1347 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1348 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001349
1350 case TemplateName::SubstTemplateTemplateParmPack:
1351 return Visit(MakeCursorTemplateRef(
1352 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1353 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001354 }
1355
1356 return false;
1357}
1358
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001359bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1360 switch (TAL.getArgument().getKind()) {
1361 case TemplateArgument::Null:
1362 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001363 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001364 return false;
1365
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001366 case TemplateArgument::Type:
1367 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1368 return Visit(TSInfo->getTypeLoc());
1369 return false;
1370
1371 case TemplateArgument::Declaration:
1372 if (Expr *E = TAL.getSourceDeclExpression())
1373 return Visit(MakeCXCursor(E, StmtParent, TU));
1374 return false;
1375
1376 case TemplateArgument::Expression:
1377 if (Expr *E = TAL.getSourceExpression())
1378 return Visit(MakeCXCursor(E, StmtParent, TU));
1379 return false;
1380
1381 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001382 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001383 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1384 return true;
1385
Douglas Gregora7fc9012011-01-05 18:58:31 +00001386 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001387 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001388 }
1389
1390 return false;
1391}
1392
Ted Kremeneka0536d82010-05-07 01:04:29 +00001393bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1394 return VisitDeclContext(D);
1395}
1396
Douglas Gregor01829d32010-08-31 14:41:23 +00001397bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1398 return Visit(TL.getUnqualifiedLoc());
1399}
1400
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001401bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001402 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001403
1404 // Some builtin types (such as Objective-C's "id", "sel", and
1405 // "Class") have associated declarations. Create cursors for those.
1406 QualType VisitType;
1407 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001408 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001410 case BuiltinType::Char_U:
1411 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001412 case BuiltinType::Char16:
1413 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001414 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001415 case BuiltinType::UInt:
1416 case BuiltinType::ULong:
1417 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001418 case BuiltinType::UInt128:
1419 case BuiltinType::Char_S:
1420 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001421 case BuiltinType::WChar_U:
1422 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001423 case BuiltinType::Short:
1424 case BuiltinType::Int:
1425 case BuiltinType::Long:
1426 case BuiltinType::LongLong:
1427 case BuiltinType::Int128:
1428 case BuiltinType::Float:
1429 case BuiltinType::Double:
1430 case BuiltinType::LongDouble:
1431 case BuiltinType::NullPtr:
1432 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001433 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001434 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001435 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001436 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001437
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001438 case BuiltinType::ObjCId:
1439 VisitType = Context.getObjCIdType();
1440 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001441
1442 case BuiltinType::ObjCClass:
1443 VisitType = Context.getObjCClassType();
1444 break;
1445
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001446 case BuiltinType::ObjCSel:
1447 VisitType = Context.getObjCSelType();
1448 break;
1449 }
1450
1451 if (!VisitType.isNull()) {
1452 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001453 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001454 TU));
1455 }
1456
1457 return false;
1458}
1459
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001460bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001461 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001462}
1463
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001464bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1465 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1466}
1467
1468bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1469 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1470}
1471
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001472bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001473 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001474}
1475
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001476bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1477 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1478 return true;
1479
John McCallc12c5bb2010-05-15 11:32:37 +00001480 return false;
1481}
1482
1483bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1484 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1485 return true;
1486
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001487 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1488 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1489 TU)))
1490 return true;
1491 }
1492
1493 return false;
1494}
1495
1496bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001497 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001498}
1499
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001500bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1501 return Visit(TL.getInnerLoc());
1502}
1503
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001504bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1505 return Visit(TL.getPointeeLoc());
1506}
1507
1508bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1509 return Visit(TL.getPointeeLoc());
1510}
1511
1512bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1513 return Visit(TL.getPointeeLoc());
1514}
1515
1516bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001517 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001518}
1519
1520bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001521 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001522}
1523
Douglas Gregor01829d32010-08-31 14:41:23 +00001524bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1525 bool SkipResultType) {
1526 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001527 return true;
1528
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001529 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001530 if (Decl *D = TL.getArg(I))
1531 if (Visit(MakeCXCursor(D, TU)))
1532 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001533
1534 return false;
1535}
1536
1537bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1538 if (Visit(TL.getElementLoc()))
1539 return true;
1540
1541 if (Expr *Size = TL.getSizeExpr())
1542 return Visit(MakeCXCursor(Size, StmtParent, TU));
1543
1544 return false;
1545}
1546
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001547bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1548 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001549 // Visit the template name.
1550 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1551 TL.getTemplateNameLoc()))
1552 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001553
1554 // Visit the template arguments.
1555 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1556 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1557 return true;
1558
1559 return false;
1560}
1561
Douglas Gregor2332c112010-01-21 20:48:56 +00001562bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1563 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1564}
1565
1566bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1567 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1568 return Visit(TSInfo->getTypeLoc());
1569
1570 return false;
1571}
1572
Sean Huntca63c202011-05-24 22:41:36 +00001573bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1574 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1575 return Visit(TSInfo->getTypeLoc());
1576
1577 return false;
1578}
1579
Douglas Gregor2494dd02011-03-01 01:34:45 +00001580bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1581 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1582 return true;
1583
1584 return false;
1585}
1586
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001587bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1588 DependentTemplateSpecializationTypeLoc TL) {
1589 // Visit the nested-name-specifier, if there is one.
1590 if (TL.getQualifierLoc() &&
1591 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1592 return true;
1593
1594 // Visit the template arguments.
1595 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1596 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1597 return true;
1598
1599 return false;
1600}
1601
Douglas Gregor9e876872011-03-01 18:12:44 +00001602bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1603 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1604 return true;
1605
1606 return Visit(TL.getNamedTypeLoc());
1607}
1608
Douglas Gregor7536dd52010-12-20 02:24:11 +00001609bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1610 return Visit(TL.getPatternLoc());
1611}
1612
Ted Kremenek3064ef92010-08-27 21:34:58 +00001613bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001614 // Visit the nested-name-specifier, if present.
1615 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1616 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1617 return true;
1618
Ted Kremenek3064ef92010-08-27 21:34:58 +00001619 if (D->isDefinition()) {
1620 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1621 E = D->bases_end(); I != E; ++I) {
1622 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1623 return true;
1624 }
1625 }
1626
1627 return VisitTagDecl(D);
1628}
1629
Ted Kremenek09dfa372010-02-18 05:46:33 +00001630bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001631 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1632 i != e; ++i)
1633 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001634 return true;
1635
1636 return false;
1637}
1638
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001639//===----------------------------------------------------------------------===//
1640// Data-recursive visitor methods.
1641//===----------------------------------------------------------------------===//
1642
Ted Kremenek28a71942010-11-13 00:36:47 +00001643namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001644#define DEF_JOB(NAME, DATA, KIND)\
1645class NAME : public VisitorJob {\
1646public:\
1647 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1648 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001649 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001650};
1651
1652DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1653DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001654DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001655DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001656DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1657 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001658DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001659#undef DEF_JOB
1660
1661class DeclVisit : public VisitorJob {
1662public:
1663 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1664 VisitorJob(parent, VisitorJob::DeclVisitKind,
1665 d, isFirst ? (void*) 1 : (void*) 0) {}
1666 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001667 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001668 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001669 Decl *get() const { return static_cast<Decl*>(data[0]); }
1670 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001671};
Ted Kremenek035dc412010-11-13 00:36:50 +00001672class TypeLocVisit : public VisitorJob {
1673public:
1674 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1675 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1676 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1677
1678 static bool classof(const VisitorJob *VJ) {
1679 return VJ->getKind() == TypeLocVisitKind;
1680 }
1681
Ted Kremenek82f3c502010-11-15 22:23:26 +00001682 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001683 QualType T = QualType::getFromOpaquePtr(data[0]);
1684 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001685 }
1686};
1687
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001688class LabelRefVisit : public VisitorJob {
1689public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001690 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1691 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001692 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001693
1694 static bool classof(const VisitorJob *VJ) {
1695 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1696 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001697 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001698 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001699 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001700};
1701class NestedNameSpecifierVisit : public VisitorJob {
1702public:
1703 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1704 CXCursor parent)
1705 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001706 NS, R.getBegin().getPtrEncoding(),
1707 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001708 static bool classof(const VisitorJob *VJ) {
1709 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1710 }
1711 NestedNameSpecifier *get() const {
1712 return static_cast<NestedNameSpecifier*>(data[0]);
1713 }
1714 SourceRange getSourceRange() const {
1715 SourceLocation A =
1716 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1717 SourceLocation B =
1718 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1719 return SourceRange(A, B);
1720 }
1721};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001722
1723class NestedNameSpecifierLocVisit : public VisitorJob {
1724public:
1725 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1726 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1727 Qualifier.getNestedNameSpecifier(),
1728 Qualifier.getOpaqueData()) { }
1729
1730 static bool classof(const VisitorJob *VJ) {
1731 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1732 }
1733
1734 NestedNameSpecifierLoc get() const {
1735 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1736 data[1]);
1737 }
1738};
1739
Ted Kremenekf64d8032010-11-18 00:02:32 +00001740class DeclarationNameInfoVisit : public VisitorJob {
1741public:
1742 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1743 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1744 static bool classof(const VisitorJob *VJ) {
1745 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1746 }
1747 DeclarationNameInfo get() const {
1748 Stmt *S = static_cast<Stmt*>(data[0]);
1749 switch (S->getStmtClass()) {
1750 default:
1751 llvm_unreachable("Unhandled Stmt");
1752 case Stmt::CXXDependentScopeMemberExprClass:
1753 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1754 case Stmt::DependentScopeDeclRefExprClass:
1755 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1756 }
1757 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001758};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001759class MemberRefVisit : public VisitorJob {
1760public:
1761 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1762 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001763 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001764 static bool classof(const VisitorJob *VJ) {
1765 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1766 }
1767 FieldDecl *get() const {
1768 return static_cast<FieldDecl*>(data[0]);
1769 }
1770 SourceLocation getLoc() const {
1771 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1772 }
1773};
Ted Kremenek28a71942010-11-13 00:36:47 +00001774class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1775 VisitorWorkList &WL;
1776 CXCursor Parent;
1777public:
1778 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1779 : WL(wl), Parent(parent) {}
1780
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001781 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001782 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001783 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001784 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001785 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001786 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001787 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001788 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001789 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001790 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001791 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001792 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001793 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001794 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001795 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001796 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001797 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001798 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001799 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1800 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001801 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001802 void VisitIfStmt(IfStmt *If);
1803 void VisitInitListExpr(InitListExpr *IE);
1804 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001805 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001806 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001807 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1808 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001809 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001810 void VisitStmt(Stmt *S);
1811 void VisitSwitchStmt(SwitchStmt *S);
1812 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001813 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001814 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001815 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001816 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001817 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001818 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001819 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001820
Ted Kremenek28a71942010-11-13 00:36:47 +00001821private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001822 void AddDeclarationNameInfo(Stmt *S);
1823 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001824 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001825 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001826 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001827 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001828 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001829 void AddTypeLoc(TypeSourceInfo *TI);
1830 void EnqueueChildren(Stmt *S);
1831};
1832} // end anonyous namespace
1833
Ted Kremenekf64d8032010-11-18 00:02:32 +00001834void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1835 // 'S' should always be non-null, since it comes from the
1836 // statement we are visiting.
1837 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1838}
1839void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1840 SourceRange R) {
1841 if (N)
1842 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1843}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001844
1845void
1846EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1847 if (Qualifier)
1848 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1849}
1850
Ted Kremenek28a71942010-11-13 00:36:47 +00001851void EnqueueVisitor::AddStmt(Stmt *S) {
1852 if (S)
1853 WL.push_back(StmtVisit(S, Parent));
1854}
Ted Kremenek035dc412010-11-13 00:36:50 +00001855void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001856 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001857 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001858}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001859void EnqueueVisitor::
1860 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1861 if (A)
1862 WL.push_back(ExplicitTemplateArgsVisit(
1863 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1864}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001865void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1866 if (D)
1867 WL.push_back(MemberRefVisit(D, L, Parent));
1868}
Ted Kremenek28a71942010-11-13 00:36:47 +00001869void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1870 if (TI)
1871 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1872 }
1873void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001874 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001875 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001876 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001877 }
1878 if (size == WL.size())
1879 return;
1880 // Now reverse the entries we just added. This will match the DFS
1881 // ordering performed by the worklist.
1882 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1883 std::reverse(I, E);
1884}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001885void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1886 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1887}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001888void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1889 AddDecl(B->getBlockDecl());
1890}
Ted Kremenek28a71942010-11-13 00:36:47 +00001891void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1892 EnqueueChildren(E);
1893 AddTypeLoc(E->getTypeSourceInfo());
1894}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001895void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1896 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1897 E = S->body_rend(); I != E; ++I) {
1898 AddStmt(*I);
1899 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001900}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001901void EnqueueVisitor::
1902VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1903 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1904 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001905 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1906 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001907 if (!E->isImplicitAccess())
1908 AddStmt(E->getBase());
1909}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001910void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1911 // Enqueue the initializer or constructor arguments.
1912 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1913 AddStmt(E->getConstructorArg(I-1));
1914 // Enqueue the array size, if any.
1915 AddStmt(E->getArraySize());
1916 // Enqueue the allocated type.
1917 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1918 // Enqueue the placement arguments.
1919 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1920 AddStmt(E->getPlacementArg(I-1));
1921}
Ted Kremenek28a71942010-11-13 00:36:47 +00001922void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001923 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1924 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001925 AddStmt(CE->getCallee());
1926 AddStmt(CE->getArg(0));
1927}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001928void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1929 // Visit the name of the type being destroyed.
1930 AddTypeLoc(E->getDestroyedTypeInfo());
1931 // Visit the scope type that looks disturbingly like the nested-name-specifier
1932 // but isn't.
1933 AddTypeLoc(E->getScopeTypeInfo());
1934 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001935 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1936 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001937 // Visit base expression.
1938 AddStmt(E->getBase());
1939}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001940void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1941 AddTypeLoc(E->getTypeSourceInfo());
1942}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001943void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1944 EnqueueChildren(E);
1945 AddTypeLoc(E->getTypeSourceInfo());
1946}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001947void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1948 EnqueueChildren(E);
1949 if (E->isTypeOperand())
1950 AddTypeLoc(E->getTypeOperandSourceInfo());
1951}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001952
1953void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1954 *E) {
1955 EnqueueChildren(E);
1956 AddTypeLoc(E->getTypeSourceInfo());
1957}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001958void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1959 EnqueueChildren(E);
1960 if (E->isTypeOperand())
1961 AddTypeLoc(E->getTypeOperandSourceInfo());
1962}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001963void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001964 if (DR->hasExplicitTemplateArgs()) {
1965 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1966 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001967 WL.push_back(DeclRefExprParts(DR, Parent));
1968}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001969void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1970 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1971 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001972 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001973}
Ted Kremenek035dc412010-11-13 00:36:50 +00001974void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1975 unsigned size = WL.size();
1976 bool isFirst = true;
1977 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1978 D != DEnd; ++D) {
1979 AddDecl(*D, isFirst);
1980 isFirst = false;
1981 }
1982 if (size == WL.size())
1983 return;
1984 // Now reverse the entries we just added. This will match the DFS
1985 // ordering performed by the worklist.
1986 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1987 std::reverse(I, E);
1988}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001989void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1990 AddStmt(E->getInit());
1991 typedef DesignatedInitExpr::Designator Designator;
1992 for (DesignatedInitExpr::reverse_designators_iterator
1993 D = E->designators_rbegin(), DEnd = E->designators_rend();
1994 D != DEnd; ++D) {
1995 if (D->isFieldDesignator()) {
1996 if (FieldDecl *Field = D->getField())
1997 AddMemberRef(Field, D->getFieldLoc());
1998 continue;
1999 }
2000 if (D->isArrayDesignator()) {
2001 AddStmt(E->getArrayIndex(*D));
2002 continue;
2003 }
2004 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2005 AddStmt(E->getArrayRangeEnd(*D));
2006 AddStmt(E->getArrayRangeStart(*D));
2007 }
2008}
Ted Kremenek28a71942010-11-13 00:36:47 +00002009void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
2010 EnqueueChildren(E);
2011 AddTypeLoc(E->getTypeInfoAsWritten());
2012}
2013void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2014 AddStmt(FS->getBody());
2015 AddStmt(FS->getInc());
2016 AddStmt(FS->getCond());
2017 AddDecl(FS->getConditionVariable());
2018 AddStmt(FS->getInit());
2019}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002020void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2021 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2022}
Ted Kremenek28a71942010-11-13 00:36:47 +00002023void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2024 AddStmt(If->getElse());
2025 AddStmt(If->getThen());
2026 AddStmt(If->getCond());
2027 AddDecl(If->getConditionVariable());
2028}
2029void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2030 // We care about the syntactic form of the initializer list, only.
2031 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2032 IE = Syntactic;
2033 EnqueueChildren(IE);
2034}
2035void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002036 WL.push_back(MemberExprParts(M, Parent));
2037
2038 // If the base of the member access expression is an implicit 'this', don't
2039 // visit it.
2040 // FIXME: If we ever want to show these implicit accesses, this will be
2041 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002042 if (!M->isImplicitAccess())
2043 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002044}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002045void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2046 AddTypeLoc(E->getEncodedTypeSourceInfo());
2047}
Ted Kremenek28a71942010-11-13 00:36:47 +00002048void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2049 EnqueueChildren(M);
2050 AddTypeLoc(M->getClassReceiverTypeInfo());
2051}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002052void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2053 // Visit the components of the offsetof expression.
2054 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2055 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2056 const OffsetOfNode &Node = E->getComponent(I-1);
2057 switch (Node.getKind()) {
2058 case OffsetOfNode::Array:
2059 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2060 break;
2061 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002062 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002063 break;
2064 case OffsetOfNode::Identifier:
2065 case OffsetOfNode::Base:
2066 continue;
2067 }
2068 }
2069 // Visit the type into which we're computing the offset.
2070 AddTypeLoc(E->getTypeSourceInfo());
2071}
Ted Kremenek28a71942010-11-13 00:36:47 +00002072void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002073 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002074 WL.push_back(OverloadExprParts(E, Parent));
2075}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002076void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2077 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002078 EnqueueChildren(E);
2079 if (E->isArgumentType())
2080 AddTypeLoc(E->getArgumentTypeInfo());
2081}
Ted Kremenek28a71942010-11-13 00:36:47 +00002082void EnqueueVisitor::VisitStmt(Stmt *S) {
2083 EnqueueChildren(S);
2084}
2085void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2086 AddStmt(S->getBody());
2087 AddStmt(S->getCond());
2088 AddDecl(S->getConditionVariable());
2089}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002090
Ted Kremenek28a71942010-11-13 00:36:47 +00002091void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2092 AddStmt(W->getBody());
2093 AddStmt(W->getCond());
2094 AddDecl(W->getConditionVariable());
2095}
John Wiegley21ff2e52011-04-28 00:16:57 +00002096
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002097void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2098 AddTypeLoc(E->getQueriedTypeSourceInfo());
2099}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002100
2101void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002102 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002103 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002104}
2105
John Wiegley21ff2e52011-04-28 00:16:57 +00002106void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2107 AddTypeLoc(E->getQueriedTypeSourceInfo());
2108}
2109
John Wiegley55262202011-04-25 06:54:41 +00002110void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2111 EnqueueChildren(E);
2112}
2113
Ted Kremenek28a71942010-11-13 00:36:47 +00002114void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2115 VisitOverloadExpr(U);
2116 if (!U->isImplicitAccess())
2117 AddStmt(U->getBase());
2118}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002119void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2120 AddStmt(E->getSubExpr());
2121 AddTypeLoc(E->getWrittenTypeInfo());
2122}
Douglas Gregor94d96292011-01-19 20:34:17 +00002123void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2124 WL.push_back(SizeOfPackExprParts(E, Parent));
2125}
Ted Kremenek60458782010-11-12 21:34:16 +00002126
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002127void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002128 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002129}
2130
2131bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2132 if (RegionOfInterest.isValid()) {
2133 SourceRange Range = getRawCursorExtent(C);
2134 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2135 return false;
2136 }
2137 return true;
2138}
2139
2140bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2141 while (!WL.empty()) {
2142 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002143 VisitorJob LI = WL.back();
2144 WL.pop_back();
2145
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002146 // Set the Parent field, then back to its old value once we're done.
2147 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2148
2149 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002150 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002151 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002152 if (!D)
2153 continue;
2154
2155 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002156 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002157 return true;
2158
2159 continue;
2160 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002161 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2162 const ExplicitTemplateArgumentList *ArgList =
2163 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2164 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2165 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2166 Arg != ArgEnd; ++Arg) {
2167 if (VisitTemplateArgumentLoc(*Arg))
2168 return true;
2169 }
2170 continue;
2171 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002172 case VisitorJob::TypeLocVisitKind: {
2173 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002174 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002175 return true;
2176 continue;
2177 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002178 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002179 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002180 if (LabelStmt *stmt = LS->getStmt()) {
2181 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2182 TU))) {
2183 return true;
2184 }
2185 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002186 continue;
2187 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002188
Ted Kremenekf64d8032010-11-18 00:02:32 +00002189 case VisitorJob::NestedNameSpecifierVisitKind: {
2190 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2191 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2192 return true;
2193 continue;
2194 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002195
2196 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2197 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2198 if (VisitNestedNameSpecifierLoc(V->get()))
2199 return true;
2200 continue;
2201 }
2202
Ted Kremenekf64d8032010-11-18 00:02:32 +00002203 case VisitorJob::DeclarationNameInfoVisitKind: {
2204 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2205 ->get()))
2206 return true;
2207 continue;
2208 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002209 case VisitorJob::MemberRefVisitKind: {
2210 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2211 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2212 return true;
2213 continue;
2214 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002215 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002216 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002217 if (!S)
2218 continue;
2219
Ted Kremenekf1107452010-11-12 18:26:56 +00002220 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002221 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002222 if (!IsInRegionOfInterest(Cursor))
2223 continue;
2224 switch (Visitor(Cursor, Parent, ClientData)) {
2225 case CXChildVisit_Break: return true;
2226 case CXChildVisit_Continue: break;
2227 case CXChildVisit_Recurse:
2228 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002229 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002230 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002231 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002232 }
2233 case VisitorJob::MemberExprPartsKind: {
2234 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002235 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002236
2237 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002238 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2239 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002240 return true;
2241
2242 // Visit the declaration name.
2243 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2244 return true;
2245
2246 // Visit the explicitly-specified template arguments, if any.
2247 if (M->hasExplicitTemplateArgs()) {
2248 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2249 *ArgEnd = Arg + M->getNumTemplateArgs();
2250 Arg != ArgEnd; ++Arg) {
2251 if (VisitTemplateArgumentLoc(*Arg))
2252 return true;
2253 }
2254 }
2255 continue;
2256 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002257 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002258 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002259 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002260 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2261 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002262 return true;
2263 // Visit declaration name.
2264 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2265 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002266 continue;
2267 }
Ted Kremenek60458782010-11-12 21:34:16 +00002268 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002269 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002270 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002271 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2272 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002273 return true;
2274 // Visit the declaration name.
2275 if (VisitDeclarationNameInfo(O->getNameInfo()))
2276 return true;
2277 // Visit the overloaded declaration reference.
2278 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2279 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002280 continue;
2281 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002282 case VisitorJob::SizeOfPackExprPartsKind: {
2283 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2284 NamedDecl *Pack = E->getPack();
2285 if (isa<TemplateTypeParmDecl>(Pack)) {
2286 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2287 E->getPackLoc(), TU)))
2288 return true;
2289
2290 continue;
2291 }
2292
2293 if (isa<TemplateTemplateParmDecl>(Pack)) {
2294 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2295 E->getPackLoc(), TU)))
2296 return true;
2297
2298 continue;
2299 }
2300
2301 // Non-type template parameter packs and function parameter packs are
2302 // treated like DeclRefExpr cursors.
2303 continue;
2304 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002305 }
2306 }
2307 return false;
2308}
2309
Ted Kremenekcdba6592010-11-18 00:42:18 +00002310bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002311 VisitorWorkList *WL = 0;
2312 if (!WorkListFreeList.empty()) {
2313 WL = WorkListFreeList.back();
2314 WL->clear();
2315 WorkListFreeList.pop_back();
2316 }
2317 else {
2318 WL = new VisitorWorkList();
2319 WorkListCache.push_back(WL);
2320 }
2321 EnqueueWorkList(*WL, S);
2322 bool result = RunVisitorWorkList(*WL);
2323 WorkListFreeList.push_back(WL);
2324 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002325}
2326
2327//===----------------------------------------------------------------------===//
2328// Misc. API hooks.
2329//===----------------------------------------------------------------------===//
2330
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002331static llvm::sys::Mutex EnableMultithreadingMutex;
2332static bool EnabledMultithreading;
2333
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002334extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002335CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2336 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002337 // Disable pretty stack trace functionality, which will otherwise be a very
2338 // poor citizen of the world and set up all sorts of signal handlers.
2339 llvm::DisablePrettyStackTrace = true;
2340
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002341 // We use crash recovery to make some of our APIs more reliable, implicitly
2342 // enable it.
2343 llvm::CrashRecoveryContext::Enable();
2344
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002345 // Enable support for multithreading in LLVM.
2346 {
2347 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2348 if (!EnabledMultithreading) {
2349 llvm::llvm_start_multithreaded();
2350 EnabledMultithreading = true;
2351 }
2352 }
2353
Douglas Gregora030b7c2010-01-22 20:35:53 +00002354 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002355 if (excludeDeclarationsFromPCH)
2356 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002357 if (displayDiagnostics)
2358 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002359 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002360}
2361
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002362void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002363 if (CIdx)
2364 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002365}
2366
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002367void clang_toggleCrashRecovery(unsigned isEnabled) {
2368 if (isEnabled)
2369 llvm::CrashRecoveryContext::Enable();
2370 else
2371 llvm::CrashRecoveryContext::Disable();
2372}
2373
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002374CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002375 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002376 if (!CIdx)
2377 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002378
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002379 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002380 FileSystemOptions FileSystemOpts;
2381 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002382
Douglas Gregor28019772010-04-05 23:52:57 +00002383 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002384 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002385 CXXIdx->getOnlyLocalDecls(),
2386 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002387 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002388}
2389
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002390unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002391 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002392 CXTranslationUnit_CacheCompletionResults |
John McCallf85e1932011-06-15 23:02:42 +00002393 CXTranslationUnit_CXXPrecompiledPreamble |
2394 CXTranslationUnit_CXXChainedPCH;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002395}
2396
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002397CXTranslationUnit
2398clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2399 const char *source_filename,
2400 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002401 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002402 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002403 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002404 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002405 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002406 return clang_parseTranslationUnit(CIdx, source_filename,
2407 command_line_args, num_command_line_args,
2408 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002409 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002410}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002411
2412struct ParseTranslationUnitInfo {
2413 CXIndex CIdx;
2414 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002415 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002416 int num_command_line_args;
2417 struct CXUnsavedFile *unsaved_files;
2418 unsigned num_unsaved_files;
2419 unsigned options;
2420 CXTranslationUnit result;
2421};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002422static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002423 ParseTranslationUnitInfo *PTUI =
2424 static_cast<ParseTranslationUnitInfo*>(UserData);
2425 CXIndex CIdx = PTUI->CIdx;
2426 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002427 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002428 int num_command_line_args = PTUI->num_command_line_args;
2429 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2430 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2431 unsigned options = PTUI->options;
2432 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002433
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002434 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002435 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002436
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002437 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2438
Douglas Gregor44c181a2010-07-23 00:33:23 +00002439 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002440 bool CompleteTranslationUnit
2441 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002442 bool CacheCodeCompetionResults
2443 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002444 bool CXXPrecompilePreamble
2445 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2446 bool CXXChainedPCH
2447 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002448
Douglas Gregor5352ac02010-01-28 00:27:43 +00002449 // Configure the diagnostics.
2450 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002451 llvm::IntrusiveRefCntPtr<Diagnostic>
2452 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2453 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002454
Ted Kremenek25a11e12011-03-22 01:15:24 +00002455 // Recover resources if we crash before exiting this function.
2456 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2457 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2458 DiagCleanup(Diags.getPtr());
2459
2460 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2461 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2462
2463 // Recover resources if we crash before exiting this function.
2464 llvm::CrashRecoveryContextCleanupRegistrar<
2465 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2466
Douglas Gregor4db64a42010-01-23 00:14:00 +00002467 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002468 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002469 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002470 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002471 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2472 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002473 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002474
Ted Kremenek25a11e12011-03-22 01:15:24 +00002475 llvm::OwningPtr<std::vector<const char *> >
2476 Args(new std::vector<const char*>());
2477
2478 // Recover resources if we crash before exiting this method.
2479 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2480 ArgsCleanup(Args.get());
2481
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002482 // Since the Clang C library is primarily used by batch tools dealing with
2483 // (often very broken) source code, where spell-checking can have a
2484 // significant negative impact on performance (particularly when
2485 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002486 // Only do this if we haven't found a spell-checking-related argument.
2487 bool FoundSpellCheckingArgument = false;
2488 for (int I = 0; I != num_command_line_args; ++I) {
2489 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2490 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2491 FoundSpellCheckingArgument = true;
2492 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002493 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002494 }
2495 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002496 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002497
Ted Kremenek25a11e12011-03-22 01:15:24 +00002498 Args->insert(Args->end(), command_line_args,
2499 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002500
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002501 // The 'source_filename' argument is optional. If the caller does not
2502 // specify it then it is assumed that the source file is specified
2503 // in the actual argument list.
2504 // Put the source file after command_line_args otherwise if '-x' flag is
2505 // present it will be unused.
2506 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002507 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002508
Douglas Gregor44c181a2010-07-23 00:33:23 +00002509 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002510 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002511 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002512 Args->push_back("-Xclang");
2513 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002514 NestedMacroExpansions
2515 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002516 }
2517
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002518 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002519 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002520 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2521 /* vector::data() not portable */,
2522 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002523 Diags,
2524 CXXIdx->getClangResourcesPath(),
2525 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002526 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002527 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002528 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002529 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002530 PrecompilePreamble,
2531 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002532 CacheCodeCompetionResults,
2533 CXXPrecompilePreamble,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002534 CXXChainedPCH,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002535 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002536
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002537 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002538 // Make sure to check that 'Unit' is non-NULL.
2539 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2540 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2541 DEnd = Unit->stored_diag_end();
2542 D != DEnd; ++D) {
2543 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2544 CXString Msg = clang_formatDiagnostic(&Diag,
2545 clang_defaultDiagnosticDisplayOptions());
2546 fprintf(stderr, "%s\n", clang_getCString(Msg));
2547 clang_disposeString(Msg);
2548 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002549#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002550 // On Windows, force a flush, since there may be multiple copies of
2551 // stderr and stdout in the file system, all with different buffers
2552 // but writing to the same device.
2553 fflush(stderr);
2554#endif
2555 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002556 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002557
Ted Kremeneka60ed472010-11-16 08:15:36 +00002558 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002559}
2560CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2561 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002562 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002563 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002564 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002565 unsigned num_unsaved_files,
2566 unsigned options) {
2567 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002568 num_command_line_args, unsaved_files,
2569 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002570 llvm::CrashRecoveryContext CRC;
2571
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002572 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002573 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2574 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2575 fprintf(stderr, " 'command_line_args' : [");
2576 for (int i = 0; i != num_command_line_args; ++i) {
2577 if (i)
2578 fprintf(stderr, ", ");
2579 fprintf(stderr, "'%s'", command_line_args[i]);
2580 }
2581 fprintf(stderr, "],\n");
2582 fprintf(stderr, " 'unsaved_files' : [");
2583 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2584 if (i)
2585 fprintf(stderr, ", ");
2586 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2587 unsaved_files[i].Length);
2588 }
2589 fprintf(stderr, "],\n");
2590 fprintf(stderr, " 'options' : %d,\n", options);
2591 fprintf(stderr, "}\n");
2592
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002593 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002594 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2595 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002596 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002597
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002598 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002599}
2600
Douglas Gregor19998442010-08-13 15:35:05 +00002601unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2602 return CXSaveTranslationUnit_None;
2603}
2604
2605int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2606 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002607 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002608 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002609
Douglas Gregor39c411f2011-07-06 16:43:36 +00002610 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002611 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2612 PrintLibclangResourceUsage(TU);
2613 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002614}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002615
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002616void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002617 if (CTUnit) {
2618 // If the translation unit has been marked as unsafe to free, just discard
2619 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002620 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002621 return;
2622
Ted Kremeneka60ed472010-11-16 08:15:36 +00002623 delete static_cast<ASTUnit *>(CTUnit->TUData);
2624 disposeCXStringPool(CTUnit->StringPool);
2625 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002626 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002627}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002628
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002629unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2630 return CXReparse_None;
2631}
2632
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002633struct ReparseTranslationUnitInfo {
2634 CXTranslationUnit TU;
2635 unsigned num_unsaved_files;
2636 struct CXUnsavedFile *unsaved_files;
2637 unsigned options;
2638 int result;
2639};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002640
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002641static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002642 ReparseTranslationUnitInfo *RTUI =
2643 static_cast<ReparseTranslationUnitInfo*>(UserData);
2644 CXTranslationUnit TU = RTUI->TU;
2645 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2646 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2647 unsigned options = RTUI->options;
2648 (void) options;
2649 RTUI->result = 1;
2650
Douglas Gregorabc563f2010-07-19 21:46:24 +00002651 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002652 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002653
Ted Kremeneka60ed472010-11-16 08:15:36 +00002654 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002655 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002656
Ted Kremenek25a11e12011-03-22 01:15:24 +00002657 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2658 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2659
2660 // Recover resources if we crash before exiting this function.
2661 llvm::CrashRecoveryContextCleanupRegistrar<
2662 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2663
Douglas Gregorabc563f2010-07-19 21:46:24 +00002664 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002665 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002666 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002667 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002668 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2669 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002670 }
2671
Ted Kremenek4ee99262011-03-22 20:16:19 +00002672 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2673 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002674 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002675}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002676
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002677int clang_reparseTranslationUnit(CXTranslationUnit TU,
2678 unsigned num_unsaved_files,
2679 struct CXUnsavedFile *unsaved_files,
2680 unsigned options) {
2681 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2682 options, 0 };
2683 llvm::CrashRecoveryContext CRC;
2684
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002685 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002686 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002687 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002688 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002689 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2690 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002691
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002692 return RTUI.result;
2693}
2694
Douglas Gregordf95a132010-08-09 20:45:32 +00002695
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002696CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002697 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002698 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002699
Ted Kremeneka60ed472010-11-16 08:15:36 +00002700 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002701 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002702}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002703
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002704CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002705 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002706 return Result;
2707}
2708
Ted Kremenekfb480492010-01-13 21:46:36 +00002709} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002710
Ted Kremenekfb480492010-01-13 21:46:36 +00002711//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002712// CXSourceLocation and CXSourceRange Operations.
2713//===----------------------------------------------------------------------===//
2714
Douglas Gregorb9790342010-01-22 21:44:22 +00002715extern "C" {
2716CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002717 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002718 return Result;
2719}
2720
2721unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002722 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2723 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2724 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002725}
2726
2727CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2728 CXFile file,
2729 unsigned line,
2730 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002731 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002732 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002733
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002734 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002735 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002736 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002737 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002738 = CXXUnit->getSourceManager().getLocation(File, line, column);
2739 if (SLoc.isInvalid()) {
2740 if (Logging)
2741 llvm::errs() << "clang_getLocation(\"" << File->getName()
2742 << "\", " << line << ", " << column << ") = invalid\n";
2743 return clang_getNullLocation();
2744 }
2745
2746 if (Logging)
2747 llvm::errs() << "clang_getLocation(\"" << File->getName()
2748 << "\", " << line << ", " << column << ") = "
2749 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002750
2751 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2752}
2753
2754CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2755 CXFile file,
2756 unsigned offset) {
2757 if (!tu || !file)
2758 return clang_getNullLocation();
2759
Ted Kremeneka60ed472010-11-16 08:15:36 +00002760 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002761 SourceLocation Start
2762 = CXXUnit->getSourceManager().getLocation(
2763 static_cast<const FileEntry *>(file),
2764 1, 1);
2765 if (Start.isInvalid()) return clang_getNullLocation();
2766
2767 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2768
2769 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002770
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002771 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002772}
2773
Douglas Gregor5352ac02010-01-28 00:27:43 +00002774CXSourceRange clang_getNullRange() {
2775 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2776 return Result;
2777}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002778
Douglas Gregor5352ac02010-01-28 00:27:43 +00002779CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2780 if (begin.ptr_data[0] != end.ptr_data[0] ||
2781 begin.ptr_data[1] != end.ptr_data[1])
2782 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002783
2784 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002785 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002786 return Result;
2787}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002788
2789unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2790{
2791 return range1.ptr_data[0] == range2.ptr_data[0]
2792 && range1.ptr_data[1] == range2.ptr_data[1]
2793 && range1.begin_int_data == range2.begin_int_data
2794 && range1.end_int_data == range2.end_int_data;
2795}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002796} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002797
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002798static void createNullLocation(CXFile *file, unsigned *line,
2799 unsigned *column, unsigned *offset) {
2800 if (file)
2801 *file = 0;
2802 if (line)
2803 *line = 0;
2804 if (column)
2805 *column = 0;
2806 if (offset)
2807 *offset = 0;
2808 return;
2809}
2810
2811extern "C" {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002812void clang_getInstantiationLocation(CXSourceLocation location,
2813 CXFile *file,
2814 unsigned *line,
2815 unsigned *column,
2816 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002817 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2818
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002819 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002820 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002821 return;
2822 }
2823
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002824 const SourceManager &SM =
2825 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth40278532011-07-25 16:49:02 +00002826 SourceLocation InstLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002827
Chandler Carruthcea731a2011-07-14 16:07:57 +00002828 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002829 // This can manifest in invalid code.
2830 FileID fileID = SM.getFileID(InstLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002831 bool Invalid = false;
2832 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2833 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002834 createNullLocation(file, line, column, offset);
2835 return;
2836 }
2837
Douglas Gregor1db19de2010-01-19 21:36:55 +00002838 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002839 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002840 if (line)
Chandler Carruth64211622011-07-25 21:09:52 +00002841 *line = SM.getExpansionLineNumber(InstLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002842 if (column)
Chandler Carrutha77c0312011-07-25 20:57:57 +00002843 *column = SM.getExpansionColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002844 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002845 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002846}
2847
Douglas Gregora9b06d42010-11-09 06:24:54 +00002848void clang_getSpellingLocation(CXSourceLocation location,
2849 CXFile *file,
2850 unsigned *line,
2851 unsigned *column,
2852 unsigned *offset) {
2853 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2854
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002855 if (!location.ptr_data[0] || Loc.isInvalid())
2856 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002857
2858 const SourceManager &SM =
2859 *static_cast<const SourceManager*>(location.ptr_data[0]);
2860 SourceLocation SpellLoc = Loc;
2861 if (SpellLoc.isMacroID()) {
2862 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2863 if (SimpleSpellingLoc.isFileID() &&
2864 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2865 SpellLoc = SimpleSpellingLoc;
2866 else
Chandler Carruth40278532011-07-25 16:49:02 +00002867 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002868 }
2869
2870 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2871 FileID FID = LocInfo.first;
2872 unsigned FileOffset = LocInfo.second;
2873
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002874 if (FID.isInvalid())
2875 return createNullLocation(file, line, column, offset);
2876
Douglas Gregora9b06d42010-11-09 06:24:54 +00002877 if (file)
2878 *file = (void *)SM.getFileEntryForID(FID);
2879 if (line)
2880 *line = SM.getLineNumber(FID, FileOffset);
2881 if (column)
2882 *column = SM.getColumnNumber(FID, FileOffset);
2883 if (offset)
2884 *offset = FileOffset;
2885}
2886
Douglas Gregor1db19de2010-01-19 21:36:55 +00002887CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002889 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002890 return Result;
2891}
2892
2893CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002894 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002895 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002896 return Result;
2897}
2898
Douglas Gregorb9790342010-01-22 21:44:22 +00002899} // end: extern "C"
2900
Douglas Gregor1db19de2010-01-19 21:36:55 +00002901//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002902// CXFile Operations.
2903//===----------------------------------------------------------------------===//
2904
2905extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002906CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002907 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002908 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002909
Steve Naroff88145032009-10-27 14:35:18 +00002910 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002911 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002912}
2913
2914time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002915 if (!SFile)
2916 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002917
Steve Naroff88145032009-10-27 14:35:18 +00002918 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2919 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002920}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002921
Douglas Gregorb9790342010-01-22 21:44:22 +00002922CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2923 if (!tu)
2924 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002925
Ted Kremeneka60ed472010-11-16 08:15:36 +00002926 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002927
Douglas Gregorb9790342010-01-22 21:44:22 +00002928 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002929 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002930}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002931
Douglas Gregordd3e5542011-05-04 00:14:37 +00002932unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2933 if (!tu || !file)
2934 return 0;
2935
2936 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2937 FileEntry *FEnt = static_cast<FileEntry *>(file);
2938 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2939 .isFileMultipleIncludeGuarded(FEnt);
2940}
2941
Ted Kremenekfb480492010-01-13 21:46:36 +00002942} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002943
Ted Kremenekfb480492010-01-13 21:46:36 +00002944//===----------------------------------------------------------------------===//
2945// CXCursor Operations.
2946//===----------------------------------------------------------------------===//
2947
Ted Kremenekfb480492010-01-13 21:46:36 +00002948static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002949 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2950 return getDeclFromExpr(CE->getSubExpr());
2951
Ted Kremenekfb480492010-01-13 21:46:36 +00002952 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2953 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002954 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2955 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002956 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2957 return ME->getMemberDecl();
2958 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2959 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002960 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002961 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002962
Ted Kremenekfb480492010-01-13 21:46:36 +00002963 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2964 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002965 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002966 if (!CE->isElidable())
2967 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002968 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2969 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002970
Douglas Gregordb1314e2010-10-01 21:11:22 +00002971 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2972 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002973 if (SubstNonTypeTemplateParmPackExpr *NTTP
2974 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2975 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002976 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2977 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2978 isa<ParmVarDecl>(SizeOfPack->getPack()))
2979 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002980
Ted Kremenekfb480492010-01-13 21:46:36 +00002981 return 0;
2982}
2983
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002984static SourceLocation getLocationFromExpr(Expr *E) {
2985 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2986 return /*FIXME:*/Msg->getLeftLoc();
2987 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2988 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002989 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2990 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002991 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2992 return Member->getMemberLoc();
2993 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2994 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002995 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2996 return SizeOfPack->getPackLoc();
2997
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002998 return E->getLocStart();
2999}
3000
Ted Kremenekfb480492010-01-13 21:46:36 +00003001extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003002
3003unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003004 CXCursorVisitor visitor,
3005 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003006 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003007 getCursorASTUnit(parent)->getMaxPCHLevel(),
3008 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003009 return CursorVis.VisitChildren(parent);
3010}
3011
David Chisnall3387c652010-11-03 14:12:26 +00003012#ifndef __has_feature
3013#define __has_feature(x) 0
3014#endif
3015#if __has_feature(blocks)
3016typedef enum CXChildVisitResult
3017 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3018
3019static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3020 CXClientData client_data) {
3021 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3022 return block(cursor, parent);
3023}
3024#else
3025// If we are compiled with a compiler that doesn't have native blocks support,
3026// define and call the block manually, so the
3027typedef struct _CXChildVisitResult
3028{
3029 void *isa;
3030 int flags;
3031 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003032 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3033 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003034} *CXCursorVisitorBlock;
3035
3036static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3037 CXClientData client_data) {
3038 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3039 return block->invoke(block, cursor, parent);
3040}
3041#endif
3042
3043
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003044unsigned clang_visitChildrenWithBlock(CXCursor parent,
3045 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003046 return clang_visitChildren(parent, visitWithBlock, block);
3047}
3048
Douglas Gregor78205d42010-01-20 21:45:58 +00003049static CXString getDeclSpelling(Decl *D) {
3050 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003051 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003052 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003053 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3054 return createCXString(Property->getIdentifier()->getName());
3055
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003056 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003057 }
3058
Douglas Gregor78205d42010-01-20 21:45:58 +00003059 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003060 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003061
Douglas Gregor78205d42010-01-20 21:45:58 +00003062 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3063 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3064 // and returns different names. NamedDecl returns the class name and
3065 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003066 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003067
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003068 if (isa<UsingDirectiveDecl>(D))
3069 return createCXString("");
3070
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003071 llvm::SmallString<1024> S;
3072 llvm::raw_svector_ostream os(S);
3073 ND->printName(os);
3074
3075 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003076}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003077
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003078CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003079 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003080 return clang_getTranslationUnitSpelling(
3081 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003082
Steve Narofff334b4e2009-09-02 18:26:48 +00003083 if (clang_isReference(C.kind)) {
3084 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003085 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003086 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003087 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003088 }
3089 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003090 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003091 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003092 }
3093 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003094 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003095 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003096 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003097 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003098 case CXCursor_CXXBaseSpecifier: {
3099 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3100 return createCXString(B->getType().getAsString());
3101 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003102 case CXCursor_TypeRef: {
3103 TypeDecl *Type = getCursorTypeRef(C).first;
3104 assert(Type && "Missing type decl");
3105
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003106 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3107 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003108 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003109 case CXCursor_TemplateRef: {
3110 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003111 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003112
3113 return createCXString(Template->getNameAsString());
3114 }
Douglas Gregor69319002010-08-31 23:48:11 +00003115
3116 case CXCursor_NamespaceRef: {
3117 NamedDecl *NS = getCursorNamespaceRef(C).first;
3118 assert(NS && "Missing namespace decl");
3119
3120 return createCXString(NS->getNameAsString());
3121 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003122
Douglas Gregora67e03f2010-09-09 21:42:20 +00003123 case CXCursor_MemberRef: {
3124 FieldDecl *Field = getCursorMemberRef(C).first;
3125 assert(Field && "Missing member decl");
3126
3127 return createCXString(Field->getNameAsString());
3128 }
3129
Douglas Gregor36897b02010-09-10 00:22:18 +00003130 case CXCursor_LabelRef: {
3131 LabelStmt *Label = getCursorLabelRef(C).first;
3132 assert(Label && "Missing label");
3133
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003134 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003135 }
3136
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003137 case CXCursor_OverloadedDeclRef: {
3138 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3139 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3140 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3141 return createCXString(ND->getNameAsString());
3142 return createCXString("");
3143 }
3144 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3145 return createCXString(E->getName().getAsString());
3146 OverloadedTemplateStorage *Ovl
3147 = Storage.get<OverloadedTemplateStorage*>();
3148 if (Ovl->size() == 0)
3149 return createCXString("");
3150 return createCXString((*Ovl->begin())->getNameAsString());
3151 }
3152
Daniel Dunbaracca7252009-11-30 20:42:49 +00003153 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003154 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003155 }
3156 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003157
3158 if (clang_isExpression(C.kind)) {
3159 Decl *D = getDeclFromExpr(getCursorExpr(C));
3160 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003161 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003162 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003163 }
3164
Douglas Gregor36897b02010-09-10 00:22:18 +00003165 if (clang_isStatement(C.kind)) {
3166 Stmt *S = getCursorStmt(C);
3167 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003168 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003169
3170 return createCXString("");
3171 }
3172
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003173 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003174 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003175 ->getNameStart());
3176
Douglas Gregor572feb22010-03-18 18:04:21 +00003177 if (C.kind == CXCursor_MacroDefinition)
3178 return createCXString(getCursorMacroDefinition(C)->getName()
3179 ->getNameStart());
3180
Douglas Gregorecdcb882010-10-20 22:00:55 +00003181 if (C.kind == CXCursor_InclusionDirective)
3182 return createCXString(getCursorInclusionDirective(C)->getFileName());
3183
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003184 if (clang_isDeclaration(C.kind))
3185 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003186
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003187 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003188}
3189
Douglas Gregor358559d2010-10-02 22:49:11 +00003190CXString clang_getCursorDisplayName(CXCursor C) {
3191 if (!clang_isDeclaration(C.kind))
3192 return clang_getCursorSpelling(C);
3193
3194 Decl *D = getCursorDecl(C);
3195 if (!D)
3196 return createCXString("");
3197
3198 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3199 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3200 D = FunTmpl->getTemplatedDecl();
3201
3202 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3203 llvm::SmallString<64> Str;
3204 llvm::raw_svector_ostream OS(Str);
3205 OS << Function->getNameAsString();
3206 if (Function->getPrimaryTemplate())
3207 OS << "<>";
3208 OS << "(";
3209 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3210 if (I)
3211 OS << ", ";
3212 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3213 }
3214
3215 if (Function->isVariadic()) {
3216 if (Function->getNumParams())
3217 OS << ", ";
3218 OS << "...";
3219 }
3220 OS << ")";
3221 return createCXString(OS.str());
3222 }
3223
3224 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3225 llvm::SmallString<64> Str;
3226 llvm::raw_svector_ostream OS(Str);
3227 OS << ClassTemplate->getNameAsString();
3228 OS << "<";
3229 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3230 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3231 if (I)
3232 OS << ", ";
3233
3234 NamedDecl *Param = Params->getParam(I);
3235 if (Param->getIdentifier()) {
3236 OS << Param->getIdentifier()->getName();
3237 continue;
3238 }
3239
3240 // There is no parameter name, which makes this tricky. Try to come up
3241 // with something useful that isn't too long.
3242 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3243 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3244 else if (NonTypeTemplateParmDecl *NTTP
3245 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3246 OS << NTTP->getType().getAsString(Policy);
3247 else
3248 OS << "template<...> class";
3249 }
3250
3251 OS << ">";
3252 return createCXString(OS.str());
3253 }
3254
3255 if (ClassTemplateSpecializationDecl *ClassSpec
3256 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3257 // If the type was explicitly written, use that.
3258 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3259 return createCXString(TSInfo->getType().getAsString(Policy));
3260
3261 llvm::SmallString<64> Str;
3262 llvm::raw_svector_ostream OS(Str);
3263 OS << ClassSpec->getNameAsString();
3264 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003265 ClassSpec->getTemplateArgs().data(),
3266 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003267 Policy);
3268 return createCXString(OS.str());
3269 }
3270
3271 return clang_getCursorSpelling(C);
3272}
3273
Ted Kremeneke68fff62010-02-17 00:41:32 +00003274CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003275 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003276 case CXCursor_FunctionDecl:
3277 return createCXString("FunctionDecl");
3278 case CXCursor_TypedefDecl:
3279 return createCXString("TypedefDecl");
3280 case CXCursor_EnumDecl:
3281 return createCXString("EnumDecl");
3282 case CXCursor_EnumConstantDecl:
3283 return createCXString("EnumConstantDecl");
3284 case CXCursor_StructDecl:
3285 return createCXString("StructDecl");
3286 case CXCursor_UnionDecl:
3287 return createCXString("UnionDecl");
3288 case CXCursor_ClassDecl:
3289 return createCXString("ClassDecl");
3290 case CXCursor_FieldDecl:
3291 return createCXString("FieldDecl");
3292 case CXCursor_VarDecl:
3293 return createCXString("VarDecl");
3294 case CXCursor_ParmDecl:
3295 return createCXString("ParmDecl");
3296 case CXCursor_ObjCInterfaceDecl:
3297 return createCXString("ObjCInterfaceDecl");
3298 case CXCursor_ObjCCategoryDecl:
3299 return createCXString("ObjCCategoryDecl");
3300 case CXCursor_ObjCProtocolDecl:
3301 return createCXString("ObjCProtocolDecl");
3302 case CXCursor_ObjCPropertyDecl:
3303 return createCXString("ObjCPropertyDecl");
3304 case CXCursor_ObjCIvarDecl:
3305 return createCXString("ObjCIvarDecl");
3306 case CXCursor_ObjCInstanceMethodDecl:
3307 return createCXString("ObjCInstanceMethodDecl");
3308 case CXCursor_ObjCClassMethodDecl:
3309 return createCXString("ObjCClassMethodDecl");
3310 case CXCursor_ObjCImplementationDecl:
3311 return createCXString("ObjCImplementationDecl");
3312 case CXCursor_ObjCCategoryImplDecl:
3313 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003314 case CXCursor_CXXMethod:
3315 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003316 case CXCursor_UnexposedDecl:
3317 return createCXString("UnexposedDecl");
3318 case CXCursor_ObjCSuperClassRef:
3319 return createCXString("ObjCSuperClassRef");
3320 case CXCursor_ObjCProtocolRef:
3321 return createCXString("ObjCProtocolRef");
3322 case CXCursor_ObjCClassRef:
3323 return createCXString("ObjCClassRef");
3324 case CXCursor_TypeRef:
3325 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003326 case CXCursor_TemplateRef:
3327 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003328 case CXCursor_NamespaceRef:
3329 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003330 case CXCursor_MemberRef:
3331 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003332 case CXCursor_LabelRef:
3333 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003334 case CXCursor_OverloadedDeclRef:
3335 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003336 case CXCursor_UnexposedExpr:
3337 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003338 case CXCursor_BlockExpr:
3339 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003340 case CXCursor_DeclRefExpr:
3341 return createCXString("DeclRefExpr");
3342 case CXCursor_MemberRefExpr:
3343 return createCXString("MemberRefExpr");
3344 case CXCursor_CallExpr:
3345 return createCXString("CallExpr");
3346 case CXCursor_ObjCMessageExpr:
3347 return createCXString("ObjCMessageExpr");
3348 case CXCursor_UnexposedStmt:
3349 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003350 case CXCursor_LabelStmt:
3351 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003352 case CXCursor_InvalidFile:
3353 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003354 case CXCursor_InvalidCode:
3355 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003356 case CXCursor_NoDeclFound:
3357 return createCXString("NoDeclFound");
3358 case CXCursor_NotImplemented:
3359 return createCXString("NotImplemented");
3360 case CXCursor_TranslationUnit:
3361 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003362 case CXCursor_UnexposedAttr:
3363 return createCXString("UnexposedAttr");
3364 case CXCursor_IBActionAttr:
3365 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003366 case CXCursor_IBOutletAttr:
3367 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003368 case CXCursor_IBOutletCollectionAttr:
3369 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003370 case CXCursor_PreprocessingDirective:
3371 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003372 case CXCursor_MacroDefinition:
3373 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003374 case CXCursor_MacroExpansion:
3375 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003376 case CXCursor_InclusionDirective:
3377 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003378 case CXCursor_Namespace:
3379 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003380 case CXCursor_LinkageSpec:
3381 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003382 case CXCursor_CXXBaseSpecifier:
3383 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003384 case CXCursor_Constructor:
3385 return createCXString("CXXConstructor");
3386 case CXCursor_Destructor:
3387 return createCXString("CXXDestructor");
3388 case CXCursor_ConversionFunction:
3389 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003390 case CXCursor_TemplateTypeParameter:
3391 return createCXString("TemplateTypeParameter");
3392 case CXCursor_NonTypeTemplateParameter:
3393 return createCXString("NonTypeTemplateParameter");
3394 case CXCursor_TemplateTemplateParameter:
3395 return createCXString("TemplateTemplateParameter");
3396 case CXCursor_FunctionTemplate:
3397 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003398 case CXCursor_ClassTemplate:
3399 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003400 case CXCursor_ClassTemplatePartialSpecialization:
3401 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003402 case CXCursor_NamespaceAlias:
3403 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003404 case CXCursor_UsingDirective:
3405 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003406 case CXCursor_UsingDeclaration:
3407 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003408 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003409 return createCXString("TypeAliasDecl");
3410 case CXCursor_ObjCSynthesizeDecl:
3411 return createCXString("ObjCSynthesizeDecl");
3412 case CXCursor_ObjCDynamicDecl:
3413 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003414 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003415
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003416 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003417 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003418}
Steve Naroff89922f82009-08-31 00:59:03 +00003419
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003420struct GetCursorData {
3421 SourceLocation TokenBeginLoc;
3422 CXCursor &BestCursor;
3423
3424 GetCursorData(SourceLocation tokenBegin, CXCursor &outputCursor)
3425 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { }
3426};
3427
Ted Kremeneke68fff62010-02-17 00:41:32 +00003428enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3429 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003430 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003431 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3432 CXCursor *BestCursor = &Data->BestCursor;
3433
3434 if (clang_isExpression(cursor.kind) &&
3435 clang_isDeclaration(BestCursor->kind)) {
3436 Decl *D = getCursorDecl(*BestCursor);
3437
3438 // Avoid having the cursor of an expression replace the declaration cursor
3439 // when the expression source range overlaps the declaration range.
3440 // This can happen for C++ constructor expressions whose range generally
3441 // include the variable declaration, e.g.:
3442 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3443 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3444 D->getLocation() == Data->TokenBeginLoc)
3445 return CXChildVisit_Break;
3446 }
3447
Douglas Gregor93798e22010-11-05 21:11:19 +00003448 // If our current best cursor is the construction of a temporary object,
3449 // don't replace that cursor with a type reference, because we want
3450 // clang_getCursor() to point at the constructor.
3451 if (clang_isExpression(BestCursor->kind) &&
3452 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3453 cursor.kind == CXCursor_TypeRef)
3454 return CXChildVisit_Recurse;
3455
Douglas Gregor85fe1562010-12-10 07:23:11 +00003456 // Don't override a preprocessing cursor with another preprocessing
3457 // cursor; we want the outermost preprocessing cursor.
3458 if (clang_isPreprocessing(cursor.kind) &&
3459 clang_isPreprocessing(BestCursor->kind))
3460 return CXChildVisit_Recurse;
3461
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003462 *BestCursor = cursor;
3463 return CXChildVisit_Recurse;
3464}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003465
Douglas Gregorb9790342010-01-22 21:44:22 +00003466CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3467 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003468 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003469
Ted Kremeneka60ed472010-11-16 08:15:36 +00003470 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003471 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3472
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003473 // Translate the given source location to make it point at the beginning of
3474 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003475 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003476
3477 // Guard against an invalid SourceLocation, or we may assert in one
3478 // of the following calls.
3479 if (SLoc.isInvalid())
3480 return clang_getNullCursor();
3481
Douglas Gregor40749ee2010-11-03 00:35:38 +00003482 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003483 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3484 CXXUnit->getASTContext().getLangOptions());
3485
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003486 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3487 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003488 // FIXME: Would be great to have a "hint" cursor, then walk from that
3489 // hint cursor upward until we find a cursor whose source range encloses
3490 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003491 GetCursorData ResultData(SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003492 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003493 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003494 Decl::MaxPCHLevel, true, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003495 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003496 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003497
3498 if (Logging) {
3499 CXFile SearchFile;
3500 unsigned SearchLine, SearchColumn;
3501 CXFile ResultFile;
3502 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003503 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3504 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003505 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3506
3507 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3508 0);
3509 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3510 &ResultColumn, 0);
3511 SearchFileName = clang_getFileName(SearchFile);
3512 ResultFileName = clang_getFileName(ResultFile);
3513 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003514 USR = clang_getCursorUSR(Result);
3515 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003516 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3517 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003518 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3519 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003520 clang_disposeString(SearchFileName);
3521 clang_disposeString(ResultFileName);
3522 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003523 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003524
3525 CXCursor Definition = clang_getCursorDefinition(Result);
3526 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3527 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3528 CXString DefinitionKindSpelling
3529 = clang_getCursorKindSpelling(Definition.kind);
3530 CXFile DefinitionFile;
3531 unsigned DefinitionLine, DefinitionColumn;
3532 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3533 &DefinitionLine, &DefinitionColumn, 0);
3534 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3535 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3536 clang_getCString(DefinitionKindSpelling),
3537 clang_getCString(DefinitionFileName),
3538 DefinitionLine, DefinitionColumn);
3539 clang_disposeString(DefinitionFileName);
3540 clang_disposeString(DefinitionKindSpelling);
3541 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003542 }
3543
Ted Kremeneke68fff62010-02-17 00:41:32 +00003544 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003545}
3546
Ted Kremenek73885552009-11-17 19:28:59 +00003547CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003548 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003549}
3550
3551unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003552 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003553}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003554
Douglas Gregor9ce55842010-11-20 00:09:34 +00003555unsigned clang_hashCursor(CXCursor C) {
3556 unsigned Index = 0;
3557 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3558 Index = 1;
3559
3560 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3561 std::make_pair(C.kind, C.data[Index]));
3562}
3563
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003564unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003565 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3566}
3567
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003568unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003569 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3570}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003571
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003572unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003573 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3574}
3575
Douglas Gregor97b98722010-01-19 23:20:36 +00003576unsigned clang_isExpression(enum CXCursorKind K) {
3577 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3578}
3579
3580unsigned clang_isStatement(enum CXCursorKind K) {
3581 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3582}
3583
Douglas Gregor8be80e12011-07-06 03:00:34 +00003584unsigned clang_isAttribute(enum CXCursorKind K) {
3585 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3586}
3587
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003588unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3589 return K == CXCursor_TranslationUnit;
3590}
3591
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003592unsigned clang_isPreprocessing(enum CXCursorKind K) {
3593 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3594}
3595
Ted Kremenekad6eff62010-03-08 21:17:29 +00003596unsigned clang_isUnexposed(enum CXCursorKind K) {
3597 switch (K) {
3598 case CXCursor_UnexposedDecl:
3599 case CXCursor_UnexposedExpr:
3600 case CXCursor_UnexposedStmt:
3601 case CXCursor_UnexposedAttr:
3602 return true;
3603 default:
3604 return false;
3605 }
3606}
3607
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003608CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003609 return C.kind;
3610}
3611
Douglas Gregor98258af2010-01-18 22:46:11 +00003612CXSourceLocation clang_getCursorLocation(CXCursor C) {
3613 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003614 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003615 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003616 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3617 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003618 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003619 }
3620
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003621 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003622 std::pair<ObjCProtocolDecl *, SourceLocation> P
3623 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003624 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003625 }
3626
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003627 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003628 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3629 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003630 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003631 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003632
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003633 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003634 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003635 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003636 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003637
3638 case CXCursor_TemplateRef: {
3639 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3640 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3641 }
3642
Douglas Gregor69319002010-08-31 23:48:11 +00003643 case CXCursor_NamespaceRef: {
3644 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3645 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3646 }
3647
Douglas Gregora67e03f2010-09-09 21:42:20 +00003648 case CXCursor_MemberRef: {
3649 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3650 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3651 }
3652
Ted Kremenek3064ef92010-08-27 21:34:58 +00003653 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003654 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3655 if (!BaseSpec)
3656 return clang_getNullLocation();
3657
3658 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3659 return cxloc::translateSourceLocation(getCursorContext(C),
3660 TSInfo->getTypeLoc().getBeginLoc());
3661
3662 return cxloc::translateSourceLocation(getCursorContext(C),
3663 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003664 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003665
Douglas Gregor36897b02010-09-10 00:22:18 +00003666 case CXCursor_LabelRef: {
3667 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3668 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3669 }
3670
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003671 case CXCursor_OverloadedDeclRef:
3672 return cxloc::translateSourceLocation(getCursorContext(C),
3673 getCursorOverloadedDeclRef(C).second);
3674
Douglas Gregorf46034a2010-01-18 23:41:10 +00003675 default:
3676 // FIXME: Need a way to enumerate all non-reference cases.
3677 llvm_unreachable("Missed a reference kind");
3678 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003679 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003680
3681 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003682 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003683 getLocationFromExpr(getCursorExpr(C)));
3684
Douglas Gregor36897b02010-09-10 00:22:18 +00003685 if (clang_isStatement(C.kind))
3686 return cxloc::translateSourceLocation(getCursorContext(C),
3687 getCursorStmt(C)->getLocStart());
3688
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003689 if (C.kind == CXCursor_PreprocessingDirective) {
3690 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3691 return cxloc::translateSourceLocation(getCursorContext(C), L);
3692 }
Douglas Gregor48072312010-03-18 15:23:44 +00003693
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003694 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003695 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003696 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003697 return cxloc::translateSourceLocation(getCursorContext(C), L);
3698 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003699
3700 if (C.kind == CXCursor_MacroDefinition) {
3701 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3702 return cxloc::translateSourceLocation(getCursorContext(C), L);
3703 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003704
3705 if (C.kind == CXCursor_InclusionDirective) {
3706 SourceLocation L
3707 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3708 return cxloc::translateSourceLocation(getCursorContext(C), L);
3709 }
3710
Ted Kremenek9a700d22010-05-12 06:16:13 +00003711 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003712 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003713
Douglas Gregorf46034a2010-01-18 23:41:10 +00003714 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003715 SourceLocation Loc = D->getLocation();
3716 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3717 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003718 // FIXME: Multiple variables declared in a single declaration
3719 // currently lack the information needed to correctly determine their
3720 // ranges when accounting for the type-specifier. We use context
3721 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3722 // and if so, whether it is the first decl.
3723 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3724 if (!cxcursor::isFirstInDeclGroup(C))
3725 Loc = VD->getLocation();
3726 }
3727
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003728 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003729}
Douglas Gregora7bde202010-01-19 00:34:46 +00003730
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003731} // end extern "C"
3732
3733static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003734 if (clang_isReference(C.kind)) {
3735 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003736 case CXCursor_ObjCSuperClassRef:
3737 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003738
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003739 case CXCursor_ObjCProtocolRef:
3740 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003741
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003742 case CXCursor_ObjCClassRef:
3743 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003744
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003745 case CXCursor_TypeRef:
3746 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003747
3748 case CXCursor_TemplateRef:
3749 return getCursorTemplateRef(C).second;
3750
Douglas Gregor69319002010-08-31 23:48:11 +00003751 case CXCursor_NamespaceRef:
3752 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003753
3754 case CXCursor_MemberRef:
3755 return getCursorMemberRef(C).second;
3756
Ted Kremenek3064ef92010-08-27 21:34:58 +00003757 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003758 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003759
Douglas Gregor36897b02010-09-10 00:22:18 +00003760 case CXCursor_LabelRef:
3761 return getCursorLabelRef(C).second;
3762
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003763 case CXCursor_OverloadedDeclRef:
3764 return getCursorOverloadedDeclRef(C).second;
3765
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003766 default:
3767 // FIXME: Need a way to enumerate all non-reference cases.
3768 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003769 }
3770 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003771
3772 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003773 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003774
3775 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003776 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003777
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003778 if (C.kind == CXCursor_PreprocessingDirective)
3779 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003780
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003781 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003782 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003783
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003784 if (C.kind == CXCursor_MacroDefinition)
3785 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003786
3787 if (C.kind == CXCursor_InclusionDirective)
3788 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3789
Ted Kremenek007a7c92010-11-01 23:26:51 +00003790 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3791 Decl *D = cxcursor::getCursorDecl(C);
3792 SourceRange R = D->getSourceRange();
3793 // FIXME: Multiple variables declared in a single declaration
3794 // currently lack the information needed to correctly determine their
3795 // ranges when accounting for the type-specifier. We use context
3796 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3797 // and if so, whether it is the first decl.
3798 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3799 if (!cxcursor::isFirstInDeclGroup(C))
3800 R.setBegin(VD->getLocation());
3801 }
3802 return R;
3803 }
Douglas Gregor66537982010-11-17 17:14:07 +00003804 return SourceRange();
3805}
3806
3807/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3808/// the decl-specifier-seq for declarations.
3809static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3810 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3811 Decl *D = cxcursor::getCursorDecl(C);
3812 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003813
Douglas Gregor2494dd02011-03-01 01:34:45 +00003814 // Adjust the start of the location for declarations preceded by
3815 // declaration specifiers.
3816 SourceLocation StartLoc;
3817 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3818 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3819 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3820 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3821 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3822 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3823 }
3824
3825 if (StartLoc.isValid() && R.getBegin().isValid() &&
3826 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3827 R.setBegin(StartLoc);
3828
3829 // FIXME: Multiple variables declared in a single declaration
3830 // currently lack the information needed to correctly determine their
3831 // ranges when accounting for the type-specifier. We use context
3832 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3833 // and if so, whether it is the first decl.
3834 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3835 if (!cxcursor::isFirstInDeclGroup(C))
3836 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003837 }
3838
3839 return R;
3840 }
3841
3842 return getRawCursorExtent(C);
3843}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003844
3845extern "C" {
3846
3847CXSourceRange clang_getCursorExtent(CXCursor C) {
3848 SourceRange R = getRawCursorExtent(C);
3849 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003850 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003852 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003853}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003854
3855CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003856 if (clang_isInvalid(C.kind))
3857 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Ted Kremeneka60ed472010-11-16 08:15:36 +00003859 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003860 if (clang_isDeclaration(C.kind)) {
3861 Decl *D = getCursorDecl(C);
3862 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003863 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003864 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003865 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003866 if (ObjCForwardProtocolDecl *Protocols
3867 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003868 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003869 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003870 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3871 return MakeCXCursor(Property, tu);
3872
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003873 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003874 }
3875
Douglas Gregor97b98722010-01-19 23:20:36 +00003876 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003877 Expr *E = getCursorExpr(C);
3878 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003879 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003880 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003881
3882 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003883 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003884
Douglas Gregor97b98722010-01-19 23:20:36 +00003885 return clang_getNullCursor();
3886 }
3887
Douglas Gregor36897b02010-09-10 00:22:18 +00003888 if (clang_isStatement(C.kind)) {
3889 Stmt *S = getCursorStmt(C);
3890 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003891 if (LabelDecl *label = Goto->getLabel())
3892 if (LabelStmt *labelS = label->getStmt())
3893 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003894
3895 return clang_getNullCursor();
3896 }
3897
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003898 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003899 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003900 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003901 }
3902
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003903 if (!clang_isReference(C.kind))
3904 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003905
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003906 switch (C.kind) {
3907 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003908 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003909
3910 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003911 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003912
3913 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003914 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003915
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003916 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003917 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003918
3919 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003920 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003921
Douglas Gregor69319002010-08-31 23:48:11 +00003922 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003923 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003924
Douglas Gregora67e03f2010-09-09 21:42:20 +00003925 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003926 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003927
Ted Kremenek3064ef92010-08-27 21:34:58 +00003928 case CXCursor_CXXBaseSpecifier: {
3929 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3930 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003931 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003932 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003933
Douglas Gregor36897b02010-09-10 00:22:18 +00003934 case CXCursor_LabelRef:
3935 // FIXME: We end up faking the "parent" declaration here because we
3936 // don't want to make CXCursor larger.
3937 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003938 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3939 .getTranslationUnitDecl(),
3940 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003941
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003942 case CXCursor_OverloadedDeclRef:
3943 return C;
3944
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003945 default:
3946 // We would prefer to enumerate all non-reference cursor kinds here.
3947 llvm_unreachable("Unhandled reference cursor kind");
3948 break;
3949 }
3950 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003951
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003952 return clang_getNullCursor();
3953}
3954
Douglas Gregorb6998662010-01-19 19:34:47 +00003955CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003956 if (clang_isInvalid(C.kind))
3957 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003958
Ted Kremeneka60ed472010-11-16 08:15:36 +00003959 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003960
Douglas Gregorb6998662010-01-19 19:34:47 +00003961 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003962 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003963 C = clang_getCursorReferenced(C);
3964 WasReference = true;
3965 }
3966
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003967 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003968 return clang_getCursorReferenced(C);
3969
Douglas Gregorb6998662010-01-19 19:34:47 +00003970 if (!clang_isDeclaration(C.kind))
3971 return clang_getNullCursor();
3972
3973 Decl *D = getCursorDecl(C);
3974 if (!D)
3975 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003976
Douglas Gregorb6998662010-01-19 19:34:47 +00003977 switch (D->getKind()) {
3978 // Declaration kinds that don't really separate the notions of
3979 // declaration and definition.
3980 case Decl::Namespace:
3981 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003982 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003983 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003984 case Decl::TemplateTypeParm:
3985 case Decl::EnumConstant:
3986 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003987 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003988 case Decl::ObjCIvar:
3989 case Decl::ObjCAtDefsField:
3990 case Decl::ImplicitParam:
3991 case Decl::ParmVar:
3992 case Decl::NonTypeTemplateParm:
3993 case Decl::TemplateTemplateParm:
3994 case Decl::ObjCCategoryImpl:
3995 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003996 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003997 case Decl::LinkageSpec:
3998 case Decl::ObjCPropertyImpl:
3999 case Decl::FileScopeAsm:
4000 case Decl::StaticAssert:
4001 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004002 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00004003 return C;
4004
4005 // Declaration kinds that don't make any sense here, but are
4006 // nonetheless harmless.
4007 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004008 break;
4009
4010 // Declaration kinds for which the definition is not resolvable.
4011 case Decl::UnresolvedUsingTypename:
4012 case Decl::UnresolvedUsingValue:
4013 break;
4014
4015 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004016 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004017 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004018
4019 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004020 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004021
4022 case Decl::Enum:
4023 case Decl::Record:
4024 case Decl::CXXRecord:
4025 case Decl::ClassTemplateSpecialization:
4026 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004027 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004028 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004029 return clang_getNullCursor();
4030
4031 case Decl::Function:
4032 case Decl::CXXMethod:
4033 case Decl::CXXConstructor:
4034 case Decl::CXXDestructor:
4035 case Decl::CXXConversion: {
4036 const FunctionDecl *Def = 0;
4037 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004038 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004039 return clang_getNullCursor();
4040 }
4041
4042 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004043 // Ask the variable if it has a definition.
4044 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004045 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004046 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004047 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004048
Douglas Gregorb6998662010-01-19 19:34:47 +00004049 case Decl::FunctionTemplate: {
4050 const FunctionDecl *Def = 0;
4051 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004052 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004053 return clang_getNullCursor();
4054 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004055
Douglas Gregorb6998662010-01-19 19:34:47 +00004056 case Decl::ClassTemplate: {
4057 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004058 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004059 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004060 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004061 return clang_getNullCursor();
4062 }
4063
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004064 case Decl::Using:
4065 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004066 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004067
4068 case Decl::UsingShadow:
4069 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004070 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004071 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004072
4073 case Decl::ObjCMethod: {
4074 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4075 if (Method->isThisDeclarationADefinition())
4076 return C;
4077
4078 // Dig out the method definition in the associated
4079 // @implementation, if we have it.
4080 // FIXME: The ASTs should make finding the definition easier.
4081 if (ObjCInterfaceDecl *Class
4082 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4083 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4084 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4085 Method->isInstanceMethod()))
4086 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004087 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004088
4089 return clang_getNullCursor();
4090 }
4091
4092 case Decl::ObjCCategory:
4093 if (ObjCCategoryImplDecl *Impl
4094 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004095 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004096 return clang_getNullCursor();
4097
4098 case Decl::ObjCProtocol:
4099 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4100 return C;
4101 return clang_getNullCursor();
4102
4103 case Decl::ObjCInterface:
4104 // There are two notions of a "definition" for an Objective-C
4105 // class: the interface and its implementation. When we resolved a
4106 // reference to an Objective-C class, produce the @interface as
4107 // the definition; when we were provided with the interface,
4108 // produce the @implementation as the definition.
4109 if (WasReference) {
4110 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4111 return C;
4112 } else if (ObjCImplementationDecl *Impl
4113 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004115 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004116
Douglas Gregorb6998662010-01-19 19:34:47 +00004117 case Decl::ObjCProperty:
4118 // FIXME: We don't really know where to find the
4119 // ObjCPropertyImplDecls that implement this property.
4120 return clang_getNullCursor();
4121
4122 case Decl::ObjCCompatibleAlias:
4123 if (ObjCInterfaceDecl *Class
4124 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4125 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004126 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004127
Douglas Gregorb6998662010-01-19 19:34:47 +00004128 return clang_getNullCursor();
4129
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004130 case Decl::ObjCForwardProtocol:
4131 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004132 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004133
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004134 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004135 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004136 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004137
4138 case Decl::Friend:
4139 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004140 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004141 return clang_getNullCursor();
4142
4143 case Decl::FriendTemplate:
4144 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004145 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004146 return clang_getNullCursor();
4147 }
4148
4149 return clang_getNullCursor();
4150}
4151
4152unsigned clang_isCursorDefinition(CXCursor C) {
4153 if (!clang_isDeclaration(C.kind))
4154 return 0;
4155
4156 return clang_getCursorDefinition(C) == C;
4157}
4158
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004159CXCursor clang_getCanonicalCursor(CXCursor C) {
4160 if (!clang_isDeclaration(C.kind))
4161 return C;
4162
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004163 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004164 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4165 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4166 return MakeCXCursor(CatD, getCursorTU(C));
4167
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004168 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4169 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4170 return MakeCXCursor(IFD, getCursorTU(C));
4171
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004172 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004173 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004174
4175 return C;
4176}
4177
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004178unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004179 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004180 return 0;
4181
4182 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4183 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4184 return E->getNumDecls();
4185
4186 if (OverloadedTemplateStorage *S
4187 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4188 return S->size();
4189
4190 Decl *D = Storage.get<Decl*>();
4191 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004192 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004193 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4194 return Classes->size();
4195 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4196 return Protocols->protocol_size();
4197
4198 return 0;
4199}
4200
4201CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004202 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004203 return clang_getNullCursor();
4204
4205 if (index >= clang_getNumOverloadedDecls(cursor))
4206 return clang_getNullCursor();
4207
Ted Kremeneka60ed472010-11-16 08:15:36 +00004208 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004209 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4210 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004211 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004212
4213 if (OverloadedTemplateStorage *S
4214 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004215 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004216
4217 Decl *D = Storage.get<Decl*>();
4218 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4219 // FIXME: This is, unfortunately, linear time.
4220 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4221 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004222 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004223 }
4224
4225 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004226 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004227
4228 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004229 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004230
4231 return clang_getNullCursor();
4232}
4233
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004234void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004235 const char **startBuf,
4236 const char **endBuf,
4237 unsigned *startLine,
4238 unsigned *startColumn,
4239 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004240 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004241 assert(getCursorDecl(C) && "CXCursor has null decl");
4242 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004243 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4244 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004245
Steve Naroff4ade6d62009-09-23 17:52:52 +00004246 SourceManager &SM = FD->getASTContext().getSourceManager();
4247 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4248 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4249 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4250 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4251 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4252 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4253}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004254
Douglas Gregor430d7a12011-07-25 17:48:11 +00004255namespace {
4256typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
4257RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
4258 const DeclarationNameInfo &NI,
4259 const SourceRange &QLoc,
4260 const ExplicitTemplateArgumentList *TemplateArgs = 0){
4261 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
4262 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
4263 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
4264
4265 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
4266
4267 RefNamePieces Pieces;
4268
4269 if (WantQualifier && QLoc.isValid())
4270 Pieces.push_back(QLoc);
4271
4272 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
4273 Pieces.push_back(NI.getLoc());
4274
4275 if (WantTemplateArgs && TemplateArgs)
4276 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
4277 TemplateArgs->RAngleLoc));
4278
4279 if (Kind == DeclarationName::CXXOperatorName) {
4280 Pieces.push_back(SourceLocation::getFromRawEncoding(
4281 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
4282 Pieces.push_back(SourceLocation::getFromRawEncoding(
4283 NI.getInfo().CXXOperatorName.EndOpNameLoc));
4284 }
4285
4286 if (WantSinglePiece) {
4287 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
4288 Pieces.clear();
4289 Pieces.push_back(R);
4290 }
4291
4292 return Pieces;
4293}
4294}
4295
4296CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4297 unsigned PieceIndex) {
4298 RefNamePieces Pieces;
4299
4300 switch (C.kind) {
4301 case CXCursor_MemberRefExpr:
4302 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4303 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4304 E->getQualifierLoc().getSourceRange());
4305 break;
4306
4307 case CXCursor_DeclRefExpr:
4308 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4309 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4310 E->getQualifierLoc().getSourceRange(),
4311 E->getExplicitTemplateArgsOpt());
4312 break;
4313
4314 case CXCursor_CallExpr:
4315 if (CXXOperatorCallExpr *OCE =
4316 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4317 Expr *Callee = OCE->getCallee();
4318 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4319 Callee = ICE->getSubExpr();
4320
4321 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4322 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4323 DRE->getQualifierLoc().getSourceRange());
4324 }
4325 break;
4326
4327 default:
4328 break;
4329 }
4330
4331 if (Pieces.empty()) {
4332 if (PieceIndex == 0)
4333 return clang_getCursorExtent(C);
4334 } else if (PieceIndex < Pieces.size()) {
4335 SourceRange R = Pieces[PieceIndex];
4336 if (R.isValid())
4337 return cxloc::translateSourceRange(getCursorContext(C), R);
4338 }
4339
4340 return clang_getNullRange();
4341}
4342
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004343void clang_enableStackTraces(void) {
4344 llvm::sys::PrintStackTraceOnErrorSignal();
4345}
4346
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004347void clang_executeOnThread(void (*fn)(void*), void *user_data,
4348 unsigned stack_size) {
4349 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4350}
4351
Ted Kremenekfb480492010-01-13 21:46:36 +00004352} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004353
Ted Kremenekfb480492010-01-13 21:46:36 +00004354//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004355// Token-based Operations.
4356//===----------------------------------------------------------------------===//
4357
4358/* CXToken layout:
4359 * int_data[0]: a CXTokenKind
4360 * int_data[1]: starting token location
4361 * int_data[2]: token length
4362 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004363 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004364 * otherwise unused.
4365 */
4366extern "C" {
4367
4368CXTokenKind clang_getTokenKind(CXToken CXTok) {
4369 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4370}
4371
4372CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4373 switch (clang_getTokenKind(CXTok)) {
4374 case CXToken_Identifier:
4375 case CXToken_Keyword:
4376 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004377 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4378 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004379
4380 case CXToken_Literal: {
4381 // We have stashed the starting pointer in the ptr_data field. Use it.
4382 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004383 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004384 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004385
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386 case CXToken_Punctuation:
4387 case CXToken_Comment:
4388 break;
4389 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004390
4391 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004392 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004393 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004394 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004395 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004396
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004397 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4398 std::pair<FileID, unsigned> LocInfo
4399 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004400 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004401 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004402 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4403 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004404 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004405
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004406 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004407}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004408
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004409CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004410 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004411 if (!CXXUnit)
4412 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004413
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004414 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4415 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4416}
4417
4418CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004419 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004420 if (!CXXUnit)
4421 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004422
4423 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004424 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4425}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004426
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004427void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4428 CXToken **Tokens, unsigned *NumTokens) {
4429 if (Tokens)
4430 *Tokens = 0;
4431 if (NumTokens)
4432 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004433
Ted Kremeneka60ed472010-11-16 08:15:36 +00004434 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004435 if (!CXXUnit || !Tokens || !NumTokens)
4436 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004437
Douglas Gregorbdf60622010-03-05 21:16:25 +00004438 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4439
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004440 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004441 if (R.isInvalid())
4442 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004443
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004444 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4445 std::pair<FileID, unsigned> BeginLocInfo
4446 = SourceMgr.getDecomposedLoc(R.getBegin());
4447 std::pair<FileID, unsigned> EndLocInfo
4448 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004449
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004450 // Cannot tokenize across files.
4451 if (BeginLocInfo.first != EndLocInfo.first)
4452 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004453
4454 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004455 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004456 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004457 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004458 if (Invalid)
4459 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004460
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004461 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4462 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004463 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004464 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004465
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004466 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004467 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004468 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004469 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004470 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004471 do {
4472 // Lex the next token
4473 Lex.LexFromRawLexer(Tok);
4474 if (Tok.is(tok::eof))
4475 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004476
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004477 // Initialize the CXToken.
4478 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004479
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004480 // - Common fields
4481 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4482 CXTok.int_data[2] = Tok.getLength();
4483 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004484
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004485 // - Kind-specific fields
4486 if (Tok.isLiteral()) {
4487 CXTok.int_data[0] = CXToken_Literal;
4488 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004489 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004490 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004491 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004492 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004493
David Chisnall096428b2010-10-13 21:44:48 +00004494 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004495 CXTok.int_data[0] = CXToken_Keyword;
4496 }
4497 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004498 CXTok.int_data[0] = Tok.is(tok::identifier)
4499 ? CXToken_Identifier
4500 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004501 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004502 CXTok.ptr_data = II;
4503 } else if (Tok.is(tok::comment)) {
4504 CXTok.int_data[0] = CXToken_Comment;
4505 CXTok.ptr_data = 0;
4506 } else {
4507 CXTok.int_data[0] = CXToken_Punctuation;
4508 CXTok.ptr_data = 0;
4509 }
4510 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004511 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004512 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004513
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004514 if (CXTokens.empty())
4515 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004516
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004517 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4518 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4519 *NumTokens = CXTokens.size();
4520}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004521
Ted Kremenek6db61092010-05-05 00:55:15 +00004522void clang_disposeTokens(CXTranslationUnit TU,
4523 CXToken *Tokens, unsigned NumTokens) {
4524 free(Tokens);
4525}
4526
4527} // end: extern "C"
4528
4529//===----------------------------------------------------------------------===//
4530// Token annotation APIs.
4531//===----------------------------------------------------------------------===//
4532
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004533typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004534static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4535 CXCursor parent,
4536 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004537namespace {
4538class AnnotateTokensWorker {
4539 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004540 CXToken *Tokens;
4541 CXCursor *Cursors;
4542 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004543 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004544 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004545 CursorVisitor AnnotateVis;
4546 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004547 bool HasContextSensitiveKeywords;
4548
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004549 bool MoreTokens() const { return TokIdx < NumTokens; }
4550 unsigned NextToken() const { return TokIdx; }
4551 void AdvanceToken() { ++TokIdx; }
4552 SourceLocation GetTokenLoc(unsigned tokI) {
4553 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4554 }
4555
Ted Kremenek6db61092010-05-05 00:55:15 +00004556public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004557 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004558 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004559 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004560 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004561 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004562 AnnotateVis(tu,
4563 AnnotateTokensVisitor, this,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00004564 Decl::MaxPCHLevel, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004565 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4566 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004567
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004568 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004569 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004570 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004571 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004572 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004573 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004574
4575 /// \brief Determine whether the annotator saw any cursors that have
4576 /// context-sensitive keywords.
4577 bool hasContextSensitiveKeywords() const {
4578 return HasContextSensitiveKeywords;
4579 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004580};
4581}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004582
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004583void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4584 // Walk the AST within the region of interest, annotating tokens
4585 // along the way.
4586 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004587
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004588 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4589 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004590 if (Pos != Annotated.end() &&
4591 (clang_isInvalid(Cursors[I].kind) ||
4592 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004593 Cursors[I] = Pos->second;
4594 }
4595
4596 // Finish up annotating any tokens left.
4597 if (!MoreTokens())
4598 return;
4599
4600 const CXCursor &C = clang_getNullCursor();
4601 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4602 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4603 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004604 }
4605}
4606
Ted Kremenek6db61092010-05-05 00:55:15 +00004607enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004608AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004609 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004610 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004611 if (cursorRange.isInvalid())
4612 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004613
4614 if (!HasContextSensitiveKeywords) {
4615 // Objective-C properties can have context-sensitive keywords.
4616 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4617 if (ObjCPropertyDecl *Property
4618 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4619 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4620 }
4621 // Objective-C methods can have context-sensitive keywords.
4622 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4623 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4624 if (ObjCMethodDecl *Method
4625 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4626 if (Method->getObjCDeclQualifier())
4627 HasContextSensitiveKeywords = true;
4628 else {
4629 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4630 PEnd = Method->param_end();
4631 P != PEnd; ++P) {
4632 if ((*P)->getObjCDeclQualifier()) {
4633 HasContextSensitiveKeywords = true;
4634 break;
4635 }
4636 }
4637 }
4638 }
4639 }
4640 // C++ methods can have context-sensitive keywords.
4641 else if (cursor.kind == CXCursor_CXXMethod) {
4642 if (CXXMethodDecl *Method
4643 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4644 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4645 HasContextSensitiveKeywords = true;
4646 }
4647 }
4648 // C++ classes can have context-sensitive keywords.
4649 else if (cursor.kind == CXCursor_StructDecl ||
4650 cursor.kind == CXCursor_ClassDecl ||
4651 cursor.kind == CXCursor_ClassTemplate ||
4652 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4653 if (Decl *D = getCursorDecl(cursor))
4654 if (D->hasAttr<FinalAttr>())
4655 HasContextSensitiveKeywords = true;
4656 }
4657 }
4658
Douglas Gregor4419b672010-10-21 06:10:04 +00004659 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004660 // For macro expansions, just note where the beginning of the macro
4661 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004662 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004663 Annotated[Loc.int_data] = cursor;
4664 return CXChildVisit_Recurse;
4665 }
4666
Douglas Gregor4419b672010-10-21 06:10:04 +00004667 // Items in the preprocessing record are kept separate from items in
4668 // declarations, so we keep a separate token index.
4669 unsigned SavedTokIdx = TokIdx;
4670 TokIdx = PreprocessingTokIdx;
4671
4672 // Skip tokens up until we catch up to the beginning of the preprocessing
4673 // entry.
4674 while (MoreTokens()) {
4675 const unsigned I = NextToken();
4676 SourceLocation TokLoc = GetTokenLoc(I);
4677 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4678 case RangeBefore:
4679 AdvanceToken();
4680 continue;
4681 case RangeAfter:
4682 case RangeOverlap:
4683 break;
4684 }
4685 break;
4686 }
4687
4688 // Look at all of the tokens within this range.
4689 while (MoreTokens()) {
4690 const unsigned I = NextToken();
4691 SourceLocation TokLoc = GetTokenLoc(I);
4692 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4693 case RangeBefore:
4694 assert(0 && "Infeasible");
4695 case RangeAfter:
4696 break;
4697 case RangeOverlap:
4698 Cursors[I] = cursor;
4699 AdvanceToken();
4700 continue;
4701 }
4702 break;
4703 }
4704
4705 // Save the preprocessing token index; restore the non-preprocessing
4706 // token index.
4707 PreprocessingTokIdx = TokIdx;
4708 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004709 return CXChildVisit_Recurse;
4710 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004711
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004712 if (cursorRange.isInvalid())
4713 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004714
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004715 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4716
Ted Kremeneka333c662010-05-12 05:29:33 +00004717 // Adjust the annotated range based specific declarations.
4718 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4719 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004720 Decl *D = cxcursor::getCursorDecl(cursor);
4721 // Don't visit synthesized ObjC methods, since they have no syntatic
4722 // representation in the source.
4723 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4724 if (MD->isSynthesized())
4725 return CXChildVisit_Continue;
4726 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004727
4728 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004729 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004730 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4731 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4732 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4733 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4734 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004735 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004736
4737 if (StartLoc.isValid() && L.isValid() &&
4738 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4739 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004740 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004741
Ted Kremenek3f404602010-08-14 01:14:06 +00004742 // If the location of the cursor occurs within a macro instantiation, record
4743 // the spelling location of the cursor in our annotation map. We can then
4744 // paper over the token labelings during a post-processing step to try and
4745 // get cursor mappings for tokens that are the *arguments* of a macro
4746 // instantiation.
4747 if (L.isMacroID()) {
4748 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4749 // Only invalidate the old annotation if it isn't part of a preprocessing
4750 // directive. Here we assume that the default construction of CXCursor
4751 // results in CXCursor.kind being an initialized value (i.e., 0). If
4752 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004753
Ted Kremenek3f404602010-08-14 01:14:06 +00004754 CXCursor &oldC = Annotated[rawEncoding];
4755 if (!clang_isPreprocessing(oldC.kind))
4756 oldC = cursor;
4757 }
4758
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004759 const enum CXCursorKind K = clang_getCursorKind(parent);
4760 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004761 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4762 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004763
4764 while (MoreTokens()) {
4765 const unsigned I = NextToken();
4766 SourceLocation TokLoc = GetTokenLoc(I);
4767 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4768 case RangeBefore:
4769 Cursors[I] = updateC;
4770 AdvanceToken();
4771 continue;
4772 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004773 case RangeOverlap:
4774 break;
4775 }
4776 break;
4777 }
4778
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004779 // Avoid having the cursor of an expression "overwrite" the annotation of the
4780 // variable declaration that it belongs to.
4781 // This can happen for C++ constructor expressions whose range generally
4782 // include the variable declaration, e.g.:
4783 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4784 if (clang_isExpression(cursorK)) {
4785 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004786 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004787 const unsigned I = NextToken();
4788 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4789 E->getLocStart() == D->getLocation() &&
4790 E->getLocStart() == GetTokenLoc(I)) {
4791 Cursors[I] = updateC;
4792 AdvanceToken();
4793 }
4794 }
4795 }
4796
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004797 // Visit children to get their cursor information.
4798 const unsigned BeforeChildren = NextToken();
4799 VisitChildren(cursor);
4800 const unsigned AfterChildren = NextToken();
4801
4802 // Adjust 'Last' to the last token within the extent of the cursor.
4803 while (MoreTokens()) {
4804 const unsigned I = NextToken();
4805 SourceLocation TokLoc = GetTokenLoc(I);
4806 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4807 case RangeBefore:
4808 assert(0 && "Infeasible");
4809 case RangeAfter:
4810 break;
4811 case RangeOverlap:
4812 Cursors[I] = updateC;
4813 AdvanceToken();
4814 continue;
4815 }
4816 break;
4817 }
4818 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004819
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004820 // Scan the tokens that are at the beginning of the cursor, but are not
4821 // capture by the child cursors.
4822
4823 // For AST elements within macros, rely on a post-annotate pass to
4824 // to correctly annotate the tokens with cursors. Otherwise we can
4825 // get confusing results of having tokens that map to cursors that really
4826 // are expanded by an instantiation.
4827 if (L.isMacroID())
4828 cursor = clang_getNullCursor();
4829
4830 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4831 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4832 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004833
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004834 Cursors[I] = cursor;
4835 }
4836 // Scan the tokens that are at the end of the cursor, but are not captured
4837 // but the child cursors.
4838 for (unsigned I = AfterChildren; I != Last; ++I)
4839 Cursors[I] = cursor;
4840
4841 TokIdx = Last;
4842 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004843}
4844
Ted Kremenek6db61092010-05-05 00:55:15 +00004845static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4846 CXCursor parent,
4847 CXClientData client_data) {
4848 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4849}
4850
Ted Kremenek6628a612011-03-18 22:51:30 +00004851namespace {
4852 struct clang_annotateTokens_Data {
4853 CXTranslationUnit TU;
4854 ASTUnit *CXXUnit;
4855 CXToken *Tokens;
4856 unsigned NumTokens;
4857 CXCursor *Cursors;
4858 };
4859}
4860
Ted Kremenekab979612010-11-11 08:05:23 +00004861// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004862static void clang_annotateTokensImpl(void *UserData) {
4863 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4864 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4865 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4866 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4867 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4868
4869 // Determine the region of interest, which contains all of the tokens.
4870 SourceRange RegionOfInterest;
4871 RegionOfInterest.setBegin(
4872 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4873 RegionOfInterest.setEnd(
4874 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4875 Tokens[NumTokens-1])));
4876
4877 // A mapping from the source locations found when re-lexing or traversing the
4878 // region of interest to the corresponding cursors.
4879 AnnotateTokensData Annotated;
4880
4881 // Relex the tokens within the source range to look for preprocessing
4882 // directives.
4883 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4884 std::pair<FileID, unsigned> BeginLocInfo
4885 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4886 std::pair<FileID, unsigned> EndLocInfo
4887 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4888
Chris Lattner5f9e2722011-07-23 10:55:15 +00004889 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00004890 bool Invalid = false;
4891 if (BeginLocInfo.first == EndLocInfo.first &&
4892 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4893 !Invalid) {
4894 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4895 CXXUnit->getASTContext().getLangOptions(),
4896 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4897 Buffer.end());
4898 Lex.SetCommentRetentionState(true);
4899
4900 // Lex tokens in raw mode until we hit the end of the range, to avoid
4901 // entering #includes or expanding macros.
4902 while (true) {
4903 Token Tok;
4904 Lex.LexFromRawLexer(Tok);
4905
4906 reprocess:
4907 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4908 // We have found a preprocessing directive. Gobble it up so that we
4909 // don't see it while preprocessing these tokens later, but keep track
4910 // of all of the token locations inside this preprocessing directive so
4911 // that we can annotate them appropriately.
4912 //
4913 // FIXME: Some simple tests here could identify macro definitions and
4914 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004915 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00004916 do {
4917 Locations.push_back(Tok.getLocation());
4918 Lex.LexFromRawLexer(Tok);
4919 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4920
4921 using namespace cxcursor;
4922 CXCursor Cursor
4923 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4924 Locations.back()),
4925 TU);
4926 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4927 Annotated[Locations[I].getRawEncoding()] = Cursor;
4928 }
4929
4930 if (Tok.isAtStartOfLine())
4931 goto reprocess;
4932
4933 continue;
4934 }
4935
4936 if (Tok.is(tok::eof))
4937 break;
4938 }
4939 }
4940
4941 // Annotate all of the source locations in the region of interest that map to
4942 // a specific cursor.
4943 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4944 TU, RegionOfInterest);
4945
4946 // FIXME: We use a ridiculous stack size here because the data-recursion
4947 // algorithm uses a large stack frame than the non-data recursive version,
4948 // and AnnotationTokensWorker currently transforms the data-recursion
4949 // algorithm back into a traditional recursion by explicitly calling
4950 // VisitChildren(). We will need to remove this explicit recursive call.
4951 W.AnnotateTokens();
4952
4953 // If we ran into any entities that involve context-sensitive keywords,
4954 // take another pass through the tokens to mark them as such.
4955 if (W.hasContextSensitiveKeywords()) {
4956 for (unsigned I = 0; I != NumTokens; ++I) {
4957 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4958 continue;
4959
4960 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4961 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4962 if (ObjCPropertyDecl *Property
4963 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4964 if (Property->getPropertyAttributesAsWritten() != 0 &&
4965 llvm::StringSwitch<bool>(II->getName())
4966 .Case("readonly", true)
4967 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00004968 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004969 .Case("readwrite", true)
4970 .Case("retain", true)
4971 .Case("copy", true)
4972 .Case("nonatomic", true)
4973 .Case("atomic", true)
4974 .Case("getter", true)
4975 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00004976 .Case("strong", true)
4977 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004978 .Default(false))
4979 Tokens[I].int_data[0] = CXToken_Keyword;
4980 }
4981 continue;
4982 }
4983
4984 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
4985 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
4986 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4987 if (llvm::StringSwitch<bool>(II->getName())
4988 .Case("in", true)
4989 .Case("out", true)
4990 .Case("inout", true)
4991 .Case("oneway", true)
4992 .Case("bycopy", true)
4993 .Case("byref", true)
4994 .Default(false))
4995 Tokens[I].int_data[0] = CXToken_Keyword;
4996 continue;
4997 }
4998
4999 if (Cursors[I].kind == CXCursor_CXXMethod) {
5000 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5001 if (CXXMethodDecl *Method
5002 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
5003 if ((Method->hasAttr<FinalAttr>() ||
5004 Method->hasAttr<OverrideAttr>()) &&
5005 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
5006 llvm::StringSwitch<bool>(II->getName())
5007 .Case("final", true)
5008 .Case("override", true)
5009 .Default(false))
5010 Tokens[I].int_data[0] = CXToken_Keyword;
5011 }
5012 continue;
5013 }
5014
5015 if (Cursors[I].kind == CXCursor_ClassDecl ||
5016 Cursors[I].kind == CXCursor_StructDecl ||
5017 Cursors[I].kind == CXCursor_ClassTemplate) {
5018 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5019 if (II->getName() == "final") {
5020 // We have to be careful with 'final', since it could be the name
5021 // of a member class rather than the context-sensitive keyword.
5022 // So, check whether the cursor associated with this
5023 Decl *D = getCursorDecl(Cursors[I]);
5024 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
5025 if ((Record->hasAttr<FinalAttr>()) &&
5026 Record->getIdentifier() != II)
5027 Tokens[I].int_data[0] = CXToken_Keyword;
5028 } else if (ClassTemplateDecl *ClassTemplate
5029 = dyn_cast_or_null<ClassTemplateDecl>(D)) {
5030 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
5031 if ((Record->hasAttr<FinalAttr>()) &&
5032 Record->getIdentifier() != II)
5033 Tokens[I].int_data[0] = CXToken_Keyword;
5034 }
5035 }
5036 continue;
5037 }
5038 }
5039 }
Ted Kremenekab979612010-11-11 08:05:23 +00005040}
5041
Ted Kremenek6db61092010-05-05 00:55:15 +00005042extern "C" {
5043
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005044void clang_annotateTokens(CXTranslationUnit TU,
5045 CXToken *Tokens, unsigned NumTokens,
5046 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005047
5048 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005049 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005050
Douglas Gregor4419b672010-10-21 06:10:04 +00005051 // Any token we don't specifically annotate will have a NULL cursor.
5052 CXCursor C = clang_getNullCursor();
5053 for (unsigned I = 0; I != NumTokens; ++I)
5054 Cursors[I] = C;
5055
Ted Kremeneka60ed472010-11-16 08:15:36 +00005056 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005057 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005058 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005059
Douglas Gregorbdf60622010-03-05 21:16:25 +00005060 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005061
5062 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005063 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005064 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005065 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005066 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5067 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005068}
Ted Kremenek6628a612011-03-18 22:51:30 +00005069
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005070} // end: extern "C"
5071
5072//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005073// Operations for querying linkage of a cursor.
5074//===----------------------------------------------------------------------===//
5075
5076extern "C" {
5077CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005078 if (!clang_isDeclaration(cursor.kind))
5079 return CXLinkage_Invalid;
5080
Ted Kremenek16b42592010-03-03 06:36:57 +00005081 Decl *D = cxcursor::getCursorDecl(cursor);
5082 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5083 switch (ND->getLinkage()) {
5084 case NoLinkage: return CXLinkage_NoLinkage;
5085 case InternalLinkage: return CXLinkage_Internal;
5086 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5087 case ExternalLinkage: return CXLinkage_External;
5088 };
5089
5090 return CXLinkage_Invalid;
5091}
5092} // end: extern "C"
5093
5094//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005095// Operations for querying language of a cursor.
5096//===----------------------------------------------------------------------===//
5097
5098static CXLanguageKind getDeclLanguage(const Decl *D) {
5099 switch (D->getKind()) {
5100 default:
5101 break;
5102 case Decl::ImplicitParam:
5103 case Decl::ObjCAtDefsField:
5104 case Decl::ObjCCategory:
5105 case Decl::ObjCCategoryImpl:
5106 case Decl::ObjCClass:
5107 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005108 case Decl::ObjCForwardProtocol:
5109 case Decl::ObjCImplementation:
5110 case Decl::ObjCInterface:
5111 case Decl::ObjCIvar:
5112 case Decl::ObjCMethod:
5113 case Decl::ObjCProperty:
5114 case Decl::ObjCPropertyImpl:
5115 case Decl::ObjCProtocol:
5116 return CXLanguage_ObjC;
5117 case Decl::CXXConstructor:
5118 case Decl::CXXConversion:
5119 case Decl::CXXDestructor:
5120 case Decl::CXXMethod:
5121 case Decl::CXXRecord:
5122 case Decl::ClassTemplate:
5123 case Decl::ClassTemplatePartialSpecialization:
5124 case Decl::ClassTemplateSpecialization:
5125 case Decl::Friend:
5126 case Decl::FriendTemplate:
5127 case Decl::FunctionTemplate:
5128 case Decl::LinkageSpec:
5129 case Decl::Namespace:
5130 case Decl::NamespaceAlias:
5131 case Decl::NonTypeTemplateParm:
5132 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005133 case Decl::TemplateTemplateParm:
5134 case Decl::TemplateTypeParm:
5135 case Decl::UnresolvedUsingTypename:
5136 case Decl::UnresolvedUsingValue:
5137 case Decl::Using:
5138 case Decl::UsingDirective:
5139 case Decl::UsingShadow:
5140 return CXLanguage_CPlusPlus;
5141 }
5142
5143 return CXLanguage_C;
5144}
5145
5146extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005147
5148enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5149 if (clang_isDeclaration(cursor.kind))
5150 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005151 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005152 return CXAvailability_Available;
5153
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005154 switch (D->getAvailability()) {
5155 case AR_Available:
5156 case AR_NotYetIntroduced:
5157 return CXAvailability_Available;
5158
5159 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005160 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005161
5162 case AR_Unavailable:
5163 return CXAvailability_NotAvailable;
5164 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005165 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005166
Douglas Gregor58ddb602010-08-23 23:00:57 +00005167 return CXAvailability_Available;
5168}
5169
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005170CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5171 if (clang_isDeclaration(cursor.kind))
5172 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5173
5174 return CXLanguage_Invalid;
5175}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005176
5177 /// \brief If the given cursor is the "templated" declaration
5178 /// descibing a class or function template, return the class or
5179 /// function template.
5180static Decl *maybeGetTemplateCursor(Decl *D) {
5181 if (!D)
5182 return 0;
5183
5184 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5185 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5186 return FunTmpl;
5187
5188 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5189 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5190 return ClassTmpl;
5191
5192 return D;
5193}
5194
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005195CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5196 if (clang_isDeclaration(cursor.kind)) {
5197 if (Decl *D = getCursorDecl(cursor)) {
5198 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005199 if (!DC)
5200 return clang_getNullCursor();
5201
5202 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5203 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005204 }
5205 }
5206
5207 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5208 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005209 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005210 }
5211
5212 return clang_getNullCursor();
5213}
5214
5215CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5216 if (clang_isDeclaration(cursor.kind)) {
5217 if (Decl *D = getCursorDecl(cursor)) {
5218 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005219 if (!DC)
5220 return clang_getNullCursor();
5221
5222 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5223 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005224 }
5225 }
5226
5227 // FIXME: Note that we can't easily compute the lexical context of a
5228 // statement or expression, so we return nothing.
5229 return clang_getNullCursor();
5230}
5231
Douglas Gregor9f592342010-10-01 20:25:15 +00005232static void CollectOverriddenMethods(DeclContext *Ctx,
5233 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005234 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005235 if (!Ctx)
5236 return;
5237
5238 // If we have a class or category implementation, jump straight to the
5239 // interface.
5240 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5241 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5242
5243 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5244 if (!Container)
5245 return;
5246
5247 // Check whether we have a matching method at this level.
5248 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5249 Method->isInstanceMethod()))
5250 if (Method != Overridden) {
5251 // We found an override at this level; there is no need to look
5252 // into other protocols or categories.
5253 Methods.push_back(Overridden);
5254 return;
5255 }
5256
5257 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5258 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5259 PEnd = Protocol->protocol_end();
5260 P != PEnd; ++P)
5261 CollectOverriddenMethods(*P, Method, Methods);
5262 }
5263
5264 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5265 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5266 PEnd = Category->protocol_end();
5267 P != PEnd; ++P)
5268 CollectOverriddenMethods(*P, Method, Methods);
5269 }
5270
5271 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5272 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5273 PEnd = Interface->protocol_end();
5274 P != PEnd; ++P)
5275 CollectOverriddenMethods(*P, Method, Methods);
5276
5277 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5278 Category; Category = Category->getNextClassCategory())
5279 CollectOverriddenMethods(Category, Method, Methods);
5280
5281 // We only look into the superclass if we haven't found anything yet.
5282 if (Methods.empty())
5283 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5284 return CollectOverriddenMethods(Super, Method, Methods);
5285 }
5286}
5287
5288void clang_getOverriddenCursors(CXCursor cursor,
5289 CXCursor **overridden,
5290 unsigned *num_overridden) {
5291 if (overridden)
5292 *overridden = 0;
5293 if (num_overridden)
5294 *num_overridden = 0;
5295 if (!overridden || !num_overridden)
5296 return;
5297
5298 if (!clang_isDeclaration(cursor.kind))
5299 return;
5300
5301 Decl *D = getCursorDecl(cursor);
5302 if (!D)
5303 return;
5304
5305 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005306 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005307 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5308 *num_overridden = CXXMethod->size_overridden_methods();
5309 if (!*num_overridden)
5310 return;
5311
5312 *overridden = new CXCursor [*num_overridden];
5313 unsigned I = 0;
5314 for (CXXMethodDecl::method_iterator
5315 M = CXXMethod->begin_overridden_methods(),
5316 MEnd = CXXMethod->end_overridden_methods();
5317 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005318 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005319 return;
5320 }
5321
5322 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5323 if (!Method)
5324 return;
5325
5326 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005327 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005328 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5329
5330 if (Methods.empty())
5331 return;
5332
5333 *num_overridden = Methods.size();
5334 *overridden = new CXCursor [Methods.size()];
5335 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005336 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005337}
5338
5339void clang_disposeOverriddenCursors(CXCursor *overridden) {
5340 delete [] overridden;
5341}
5342
Douglas Gregorecdcb882010-10-20 22:00:55 +00005343CXFile clang_getIncludedFile(CXCursor cursor) {
5344 if (cursor.kind != CXCursor_InclusionDirective)
5345 return 0;
5346
5347 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5348 return (void *)ID->getFile();
5349}
5350
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005351} // end: extern "C"
5352
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005353
5354//===----------------------------------------------------------------------===//
5355// C++ AST instrospection.
5356//===----------------------------------------------------------------------===//
5357
5358extern "C" {
5359unsigned clang_CXXMethod_isStatic(CXCursor C) {
5360 if (!clang_isDeclaration(C.kind))
5361 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005362
5363 CXXMethodDecl *Method = 0;
5364 Decl *D = cxcursor::getCursorDecl(C);
5365 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5366 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5367 else
5368 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5369 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005370}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005371
Douglas Gregor211924b2011-05-12 15:17:24 +00005372unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5373 if (!clang_isDeclaration(C.kind))
5374 return 0;
5375
5376 CXXMethodDecl *Method = 0;
5377 Decl *D = cxcursor::getCursorDecl(C);
5378 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5379 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5380 else
5381 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5382 return (Method && Method->isVirtual()) ? 1 : 0;
5383}
5384
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005385} // end: extern "C"
5386
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005387//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005388// Attribute introspection.
5389//===----------------------------------------------------------------------===//
5390
5391extern "C" {
5392CXType clang_getIBOutletCollectionType(CXCursor C) {
5393 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005394 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005395
5396 IBOutletCollectionAttr *A =
5397 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5398
Douglas Gregor841b2382011-03-06 18:55:32 +00005399 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005400}
5401} // end: extern "C"
5402
5403//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005404// Inspecting memory usage.
5405//===----------------------------------------------------------------------===//
5406
Ted Kremenekf7870022011-04-20 16:41:07 +00005407typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005408
Ted Kremenekf7870022011-04-20 16:41:07 +00005409static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5410 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005411 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005412 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005413 entries.push_back(entry);
5414}
5415
5416extern "C" {
5417
Ted Kremenekf7870022011-04-20 16:41:07 +00005418const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005419 const char *str = "";
5420 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005421 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005422 str = "ASTContext: expressions, declarations, and types";
5423 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005424 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005425 str = "ASTContext: identifiers";
5426 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005427 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005428 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005429 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005430 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005431 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005432 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005433 case CXTUResourceUsage_SourceManagerContentCache:
5434 str = "SourceManager: content cache allocator";
5435 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005436 case CXTUResourceUsage_AST_SideTables:
5437 str = "ASTContext: side tables";
5438 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005439 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5440 str = "SourceManager: malloc'ed memory buffers";
5441 break;
5442 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5443 str = "SourceManager: mmap'ed memory buffers";
5444 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005445 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5446 str = "ExternalASTSource: malloc'ed memory buffers";
5447 break;
5448 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5449 str = "ExternalASTSource: mmap'ed memory buffers";
5450 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005451 case CXTUResourceUsage_Preprocessor:
5452 str = "Preprocessor: malloc'ed memory";
5453 break;
5454 case CXTUResourceUsage_PreprocessingRecord:
5455 str = "Preprocessor: PreprocessingRecord";
5456 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005457 }
5458 return str;
5459}
5460
Ted Kremenekf7870022011-04-20 16:41:07 +00005461CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005462 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005463 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005464 return usage;
5465 }
5466
5467 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5468 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5469 ASTContext &astContext = astUnit->getASTContext();
5470
5471 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005472 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005473 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005474
5475 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005476 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005477 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5478
5479 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005480 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005481 (unsigned long) astContext.Selectors.getTotalMemory());
5482
Ted Kremenekba29bd22011-04-28 04:53:38 +00005483 // How much memory is used by ASTContext's side tables?
5484 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5485 (unsigned long) astContext.getSideTableAllocatedMemory());
5486
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005487 // How much memory is used for caching global code completion results?
5488 unsigned long completionBytes = 0;
5489 if (GlobalCodeCompletionAllocator *completionAllocator =
5490 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005491 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005492 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005493 createCXTUResourceUsageEntry(*entries,
5494 CXTUResourceUsage_GlobalCompletionResults,
5495 completionBytes);
5496
5497 // How much memory is being used by SourceManager's content cache?
5498 createCXTUResourceUsageEntry(*entries,
5499 CXTUResourceUsage_SourceManagerContentCache,
5500 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005501
5502 // How much memory is being used by the MemoryBuffer's in SourceManager?
5503 const SourceManager::MemoryBufferSizes &srcBufs =
5504 astUnit->getSourceManager().getMemoryBufferSizes();
5505
5506 createCXTUResourceUsageEntry(*entries,
5507 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5508 (unsigned long) srcBufs.malloc_bytes);
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005509 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005510 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5511 (unsigned long) srcBufs.mmap_bytes);
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005512
5513 // How much memory is being used by the ExternalASTSource?
5514 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5515 const ExternalASTSource::MemoryBufferSizes &sizes =
5516 esrc->getMemoryBufferSizes();
5517
5518 createCXTUResourceUsageEntry(*entries,
5519 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5520 (unsigned long) sizes.malloc_bytes);
5521 createCXTUResourceUsageEntry(*entries,
5522 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5523 (unsigned long) sizes.mmap_bytes);
5524 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005525
5526 // How much memory is being used by the Preprocessor?
5527 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005528 createCXTUResourceUsageEntry(*entries,
5529 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005530 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005531
5532 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5533 createCXTUResourceUsageEntry(*entries,
5534 CXTUResourceUsage_PreprocessingRecord,
5535 pRec->getTotalMemory());
5536 }
5537
5538
Ted Kremenekf7870022011-04-20 16:41:07 +00005539 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005540 (unsigned) entries->size(),
5541 entries->size() ? &(*entries)[0] : 0 };
5542 entries.take();
5543 return usage;
5544}
5545
Ted Kremenekf7870022011-04-20 16:41:07 +00005546void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005547 if (usage.data)
5548 delete (MemUsageEntries*) usage.data;
5549}
5550
5551} // end extern "C"
5552
Douglas Gregor6df78732011-05-05 20:27:22 +00005553void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5554 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5555 for (unsigned I = 0; I != Usage.numEntries; ++I)
5556 fprintf(stderr, " %s: %lu\n",
5557 clang_getTUResourceUsageName(Usage.entries[I].kind),
5558 Usage.entries[I].amount);
5559
5560 clang_disposeCXTUResourceUsage(Usage);
5561}
5562
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005563//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005564// Misc. utility functions.
5565//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005566
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005567/// Default to using an 8 MB stack size on "safety" threads.
5568static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005569
5570namespace clang {
5571
5572bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005573 void (*Fn)(void*), void *UserData,
5574 unsigned Size) {
5575 if (!Size)
5576 Size = GetSafetyThreadStackSize();
5577 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005578 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5579 return CRC.RunSafely(Fn, UserData);
5580}
5581
5582unsigned GetSafetyThreadStackSize() {
5583 return SafetyStackThreadSize;
5584}
5585
5586void SetSafetyThreadStackSize(unsigned Value) {
5587 SafetyStackThreadSize = Value;
5588}
5589
5590}
5591
Ted Kremenek04bb7162010-01-22 22:44:15 +00005592extern "C" {
5593
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005594CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005595 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005596}
5597
5598} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005599