blob: 7f8f759ccbd414882a15d78503b2ffbc9d0f7962 [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
442 = AU->getSourceManager().getDecomposedInstantiationLoc(
443 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
466 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
467 std::pair<FileID, unsigned> End
468 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
469
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
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000480 = SM.getDecomposedInstantiationLoc(
481 (*First)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000482
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000483 ByFileMap[P.first].push_back(*First);
484 }
485 }
486
487 return visitPreprocessedEntities(ByFileMap[Begin.first].begin(),
488 ByFileMap[Begin.first].end());
489}
490
491template<typename InputIterator>
492bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
493 InputIterator Last) {
494 for (; First != Last; ++First) {
495 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
496 if (Visit(MakeMacroExpansionCursor(ME, TU)))
497 return true;
498
499 continue;
500 }
501
502 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
503 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
504 return true;
505
506 continue;
507 }
508
509 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
510 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
511 return true;
512
513 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000514 }
515 }
516
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000517 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000518}
519
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000521///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522/// \returns true if the visitation should be aborted, false if it
523/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000524bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000525 if (clang_isReference(Cursor.kind) &&
526 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000527 // By definition, references have no children.
528 return false;
529 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000530
531 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000532 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000533 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000534
Douglas Gregorb1373d02010-01-20 20:59:29 +0000535 if (clang_isDeclaration(Cursor.kind)) {
536 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000537 if (!D)
538 return false;
539
Ted Kremenek539311e2010-02-18 18:47:01 +0000540 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000542
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000543 if (clang_isStatement(Cursor.kind)) {
544 if (Stmt *S = getCursorStmt(Cursor))
545 return Visit(S);
546
547 return false;
548 }
549
550 if (clang_isExpression(Cursor.kind)) {
551 if (Expr *E = getCursorExpr(Cursor))
552 return Visit(E);
553
554 return false;
555 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000556
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000558 CXTranslationUnit tu = getCursorTU(Cursor);
559 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000560
561 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
562 for (unsigned I = 0; I != 2; ++I) {
563 if (VisitOrder[I]) {
564 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
565 RegionOfInterest.isInvalid()) {
566 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
567 TLEnd = CXXUnit->top_level_end();
568 TL != TLEnd; ++TL) {
569 if (Visit(MakeCXCursor(*TL, tu), true))
570 return true;
571 }
572 } else if (VisitDeclContext(
573 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000574 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000575 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000576 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000577
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000578 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000579 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
580 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000581 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000582
Douglas Gregor7b691f332010-01-20 21:13:59 +0000583 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000585
Douglas Gregorc314aa42011-03-02 19:17:03 +0000586 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
587 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
588 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
589 return Visit(BaseTSInfo->getTypeLoc());
590 }
591 }
592 }
593
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595 return false;
596}
597
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000598bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000599 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
600 if (Visit(TSInfo->getTypeLoc()))
601 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000602
Ted Kremenek664cffd2010-07-22 11:30:19 +0000603 if (Stmt *Body = B->getBody())
604 return Visit(MakeCXCursor(Body, StmtParent, TU));
605
606 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000607}
608
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000609llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
610 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000611 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000612 if (Range.isInvalid())
613 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000614
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000615 switch (CompareRegionOfInterest(Range)) {
616 case RangeBefore:
617 // This declaration comes before the region of interest; skip it.
618 return llvm::Optional<bool>();
619
620 case RangeAfter:
621 // This declaration comes after the region of interest; we're done.
622 return false;
623
624 case RangeOverlap:
625 // This declaration overlaps the region of interest; visit it.
626 break;
627 }
628 }
629 return true;
630}
631
632bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
633 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
634
635 // FIXME: Eventually remove. This part of a hack to support proper
636 // iteration over all Decls contained lexically within an ObjC container.
637 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
638 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
639
640 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000641 Decl *D = *I;
642 if (D->getLexicalDeclContext() != DC)
643 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000644 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000645 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
646 if (!V.hasValue())
647 continue;
648 if (!V.getValue())
649 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000650 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000651 return true;
652 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000653 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000654}
655
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000656bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
657 llvm_unreachable("Translation units are visited directly by Visit()");
658 return false;
659}
660
Richard Smith162e1c12011-04-15 14:24:37 +0000661bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
662 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
663 return Visit(TSInfo->getTypeLoc());
664
665 return false;
666}
667
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000668bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
669 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
670 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000671
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000672 return false;
673}
674
675bool CursorVisitor::VisitTagDecl(TagDecl *D) {
676 return VisitDeclContext(D);
677}
678
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000679bool CursorVisitor::VisitClassTemplateSpecializationDecl(
680 ClassTemplateSpecializationDecl *D) {
681 bool ShouldVisitBody = false;
682 switch (D->getSpecializationKind()) {
683 case TSK_Undeclared:
684 case TSK_ImplicitInstantiation:
685 // Nothing to visit
686 return false;
687
688 case TSK_ExplicitInstantiationDeclaration:
689 case TSK_ExplicitInstantiationDefinition:
690 break;
691
692 case TSK_ExplicitSpecialization:
693 ShouldVisitBody = true;
694 break;
695 }
696
697 // Visit the template arguments used in the specialization.
698 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
699 TypeLoc TL = SpecType->getTypeLoc();
700 if (TemplateSpecializationTypeLoc *TSTLoc
701 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
702 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
703 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
704 return true;
705 }
706 }
707
708 if (ShouldVisitBody && VisitCXXRecordDecl(D))
709 return true;
710
711 return false;
712}
713
Douglas Gregor74dbe642010-08-31 19:31:58 +0000714bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
715 ClassTemplatePartialSpecializationDecl *D) {
716 // FIXME: Visit the "outer" template parameter lists on the TagDecl
717 // before visiting these template parameters.
718 if (VisitTemplateParameters(D->getTemplateParameters()))
719 return true;
720
721 // Visit the partial specialization arguments.
722 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
723 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
724 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
725 return true;
726
727 return VisitCXXRecordDecl(D);
728}
729
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000730bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000731 // Visit the default argument.
732 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
733 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
734 if (Visit(DefArg->getTypeLoc()))
735 return true;
736
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000737 return false;
738}
739
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000740bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
741 if (Expr *Init = D->getInitExpr())
742 return Visit(MakeCXCursor(Init, StmtParent, TU));
743 return false;
744}
745
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000746bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
747 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
748 if (Visit(TSInfo->getTypeLoc()))
749 return true;
750
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000751 // Visit the nested-name-specifier, if present.
752 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
753 if (VisitNestedNameSpecifierLoc(QualifierLoc))
754 return true;
755
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000756 return false;
757}
758
Douglas Gregora67e03f2010-09-09 21:42:20 +0000759/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000760static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
761 CXXCtorInitializer const * const *X
762 = static_cast<CXXCtorInitializer const * const *>(Xp);
763 CXXCtorInitializer const * const *Y
764 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000765
766 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
767 return -1;
768 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
769 return 1;
770 else
771 return 0;
772}
773
Douglas Gregorb1373d02010-01-20 20:59:29 +0000774bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000775 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
776 // Visit the function declaration's syntactic components in the order
777 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000778 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000779 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
780
781 // If we have a function declared directly (without the use of a typedef),
782 // visit just the return type. Otherwise, just visit the function's type
783 // now.
784 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
785 (!FTL && Visit(TL)))
786 return true;
787
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000788 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000789 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
790 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000791 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000792
793 // Visit the declaration name.
794 if (VisitDeclarationNameInfo(ND->getNameInfo()))
795 return true;
796
797 // FIXME: Visit explicitly-specified template arguments!
798
799 // Visit the function parameters, if we have a function type.
800 if (FTL && VisitFunctionTypeLoc(*FTL, true))
801 return true;
802
803 // FIXME: Attributes?
804 }
805
Sean Hunt10620eb2011-05-06 20:44:56 +0000806 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000807 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
808 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000809 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000810 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
811 IEnd = Constructor->init_end();
812 I != IEnd; ++I) {
813 if (!(*I)->isWritten())
814 continue;
815
816 WrittenInits.push_back(*I);
817 }
818
819 // Sort the initializers in source order
820 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000821 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000822
823 // Visit the initializers in source order
824 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000825 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000826 if (Init->isAnyMemberInitializer()) {
827 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000828 Init->getMemberLocation(), TU)))
829 return true;
830 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
831 if (Visit(BaseInfo->getTypeLoc()))
832 return true;
833 }
834
835 // Visit the initializer value.
836 if (Expr *Initializer = Init->getInit())
837 if (Visit(MakeCXCursor(Initializer, ND, TU)))
838 return true;
839 }
840 }
841
842 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
843 return true;
844 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845
Douglas Gregorb1373d02010-01-20 20:59:29 +0000846 return false;
847}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000848
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
850 if (VisitDeclaratorDecl(D))
851 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853 if (Expr *BitWidth = D->getBitWidth())
854 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000855
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856 return false;
857}
858
859bool CursorVisitor::VisitVarDecl(VarDecl *D) {
860 if (VisitDeclaratorDecl(D))
861 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000862
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000863 if (Expr *Init = D->getInit())
864 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000865
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000866 return false;
867}
868
Douglas Gregor84b51d72010-09-01 20:16:53 +0000869bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
870 if (VisitDeclaratorDecl(D))
871 return true;
872
873 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
874 if (Expr *DefArg = D->getDefaultArgument())
875 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
876
877 return false;
878}
879
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000880bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
881 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
882 // before visiting these template parameters.
883 if (VisitTemplateParameters(D->getTemplateParameters()))
884 return true;
885
886 return VisitFunctionDecl(D->getTemplatedDecl());
887}
888
Douglas Gregor39d6f072010-08-31 19:02:00 +0000889bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
890 // FIXME: Visit the "outer" template parameter lists on the TagDecl
891 // before visiting these template parameters.
892 if (VisitTemplateParameters(D->getTemplateParameters()))
893 return true;
894
895 return VisitCXXRecordDecl(D->getTemplatedDecl());
896}
897
Douglas Gregor84b51d72010-09-01 20:16:53 +0000898bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
899 if (VisitTemplateParameters(D->getTemplateParameters()))
900 return true;
901
902 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
903 VisitTemplateArgumentLoc(D->getDefaultArgument()))
904 return true;
905
906 return false;
907}
908
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000909bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000910 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
911 if (Visit(TSInfo->getTypeLoc()))
912 return true;
913
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000914 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000915 PEnd = ND->param_end();
916 P != PEnd; ++P) {
917 if (Visit(MakeCXCursor(*P, TU)))
918 return true;
919 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000920
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000921 if (ND->isThisDeclarationADefinition() &&
922 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
923 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000924
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000925 return false;
926}
927
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000928namespace {
929 struct ContainerDeclsSort {
930 SourceManager &SM;
931 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
932 bool operator()(Decl *A, Decl *B) {
933 SourceLocation L_A = A->getLocStart();
934 SourceLocation L_B = B->getLocStart();
935 assert(L_A.isValid() && L_B.isValid());
936 return SM.isBeforeInTranslationUnit(L_A, L_B);
937 }
938 };
939}
940
Douglas Gregora59e3902010-01-21 23:27:09 +0000941bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000942 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
943 // an @implementation can lexically contain Decls that are not properly
944 // nested in the AST. When we identify such cases, we need to retrofit
945 // this nesting here.
946 if (!DI_current)
947 return VisitDeclContext(D);
948
949 // Scan the Decls that immediately come after the container
950 // in the current DeclContext. If any fall within the
951 // container's lexical region, stash them into a vector
952 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000953 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000954 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000955 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000956 if (EndLoc.isValid()) {
957 DeclContext::decl_iterator next = *DI_current;
958 while (++next != DE_current) {
959 Decl *D_next = *next;
960 if (!D_next)
961 break;
962 SourceLocation L = D_next->getLocStart();
963 if (!L.isValid())
964 break;
965 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
966 *DI_current = next;
967 DeclsInContainer.push_back(D_next);
968 continue;
969 }
970 break;
971 }
972 }
973
974 // The common case.
975 if (DeclsInContainer.empty())
976 return VisitDeclContext(D);
977
978 // Get all the Decls in the DeclContext, and sort them with the
979 // additional ones we've collected. Then visit them.
980 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
981 I!=E; ++I) {
982 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000983 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
984 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000985 continue;
986 DeclsInContainer.push_back(subDecl);
987 }
988
989 // Now sort the Decls so that they appear in lexical order.
990 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
991 ContainerDeclsSort(SM));
992
993 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000994 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000995 E = DeclsInContainer.end(); I != E; ++I) {
996 CXCursor Cursor = MakeCXCursor(*I, TU);
997 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
998 if (!V.hasValue())
999 continue;
1000 if (!V.getValue())
1001 return false;
1002 if (Visit(Cursor, true))
1003 return true;
1004 }
1005 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001006}
1007
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001009 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1010 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001013 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1014 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1015 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001016 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001017 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018
Douglas Gregora59e3902010-01-21 23:27:09 +00001019 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1023 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1024 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1025 E = PID->protocol_end(); I != E; ++I, ++PL)
1026 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1027 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029 return VisitObjCContainerDecl(PID);
1030}
1031
Ted Kremenek23173d72010-05-18 21:09:07 +00001032bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001033 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001034 return true;
1035
Ted Kremenek23173d72010-05-18 21:09:07 +00001036 // FIXME: This implements a workaround with @property declarations also being
1037 // installed in the DeclContext for the @interface. Eventually this code
1038 // should be removed.
1039 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1040 if (!CDecl || !CDecl->IsClassExtension())
1041 return false;
1042
1043 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1044 if (!ID)
1045 return false;
1046
1047 IdentifierInfo *PropertyId = PD->getIdentifier();
1048 ObjCPropertyDecl *prevDecl =
1049 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1050
1051 if (!prevDecl)
1052 return false;
1053
1054 // Visit synthesized methods since they will be skipped when visiting
1055 // the @interface.
1056 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001057 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001058 if (Visit(MakeCXCursor(MD, TU)))
1059 return true;
1060
1061 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001062 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001063 if (Visit(MakeCXCursor(MD, TU)))
1064 return true;
1065
1066 return false;
1067}
1068
Douglas Gregorb1373d02010-01-20 20:59:29 +00001069bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001070 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001071 if (D->getSuperClass() &&
1072 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001073 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001074 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001075 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001076
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001077 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1078 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1079 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001080 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001081 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001082
Douglas Gregora59e3902010-01-21 23:27:09 +00001083 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001084}
1085
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001086bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1087 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001088}
1089
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001090bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001091 // 'ID' could be null when dealing with invalid code.
1092 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1093 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1094 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001095
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001096 return VisitObjCImplDecl(D);
1097}
1098
1099bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1100#if 0
1101 // Issue callbacks for super class.
1102 // FIXME: No source location information!
1103 if (D->getSuperClass() &&
1104 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001105 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001106 TU)))
1107 return true;
1108#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001109
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001110 return VisitObjCImplDecl(D);
1111}
1112
1113bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1114 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1115 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1116 E = D->protocol_end();
1117 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001118 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001119 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001120
1121 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001122}
1123
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001124bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1125 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1126 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1127 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001128
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001129 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001130}
1131
Douglas Gregora4ffd852010-11-17 01:03:52 +00001132bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1133 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1134 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1135
1136 return false;
1137}
1138
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001139bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1140 return VisitDeclContext(D);
1141}
1142
Douglas Gregor69319002010-08-31 23:48:11 +00001143bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001144 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001145 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1146 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001147 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001148
1149 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1150 D->getTargetNameLoc(), TU));
1151}
1152
Douglas Gregor7e242562010-09-01 19:52:22 +00001153bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001154 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001155 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1156 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001157 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001158 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001159
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001160 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1161 return true;
1162
Douglas Gregor7e242562010-09-01 19:52:22 +00001163 return VisitDeclarationNameInfo(D->getNameInfo());
1164}
1165
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001166bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001167 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001168 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1169 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001170 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001171
1172 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1173 D->getIdentLocation(), TU));
1174}
1175
Douglas Gregor7e242562010-09-01 19:52:22 +00001176bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001177 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001178 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1179 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001180 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001181 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001182
Douglas Gregor7e242562010-09-01 19:52:22 +00001183 return VisitDeclarationNameInfo(D->getNameInfo());
1184}
1185
1186bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1187 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001188 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001189 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1190 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001191 return true;
1192
Douglas Gregor7e242562010-09-01 19:52:22 +00001193 return false;
1194}
1195
Douglas Gregor01829d32010-08-31 14:41:23 +00001196bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1197 switch (Name.getName().getNameKind()) {
1198 case clang::DeclarationName::Identifier:
1199 case clang::DeclarationName::CXXLiteralOperatorName:
1200 case clang::DeclarationName::CXXOperatorName:
1201 case clang::DeclarationName::CXXUsingDirective:
1202 return false;
1203
1204 case clang::DeclarationName::CXXConstructorName:
1205 case clang::DeclarationName::CXXDestructorName:
1206 case clang::DeclarationName::CXXConversionFunctionName:
1207 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1208 return Visit(TSInfo->getTypeLoc());
1209 return false;
1210
1211 case clang::DeclarationName::ObjCZeroArgSelector:
1212 case clang::DeclarationName::ObjCOneArgSelector:
1213 case clang::DeclarationName::ObjCMultiArgSelector:
1214 // FIXME: Per-identifier location info?
1215 return false;
1216 }
1217
1218 return false;
1219}
1220
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001221bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1222 SourceRange Range) {
1223 // FIXME: This whole routine is a hack to work around the lack of proper
1224 // source information in nested-name-specifiers (PR5791). Since we do have
1225 // a beginning source location, we can visit the first component of the
1226 // nested-name-specifier, if it's a single-token component.
1227 if (!NNS)
1228 return false;
1229
1230 // Get the first component in the nested-name-specifier.
1231 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1232 NNS = Prefix;
1233
1234 switch (NNS->getKind()) {
1235 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001236 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1237 TU));
1238
Douglas Gregor14aba762011-02-24 02:36:08 +00001239 case NestedNameSpecifier::NamespaceAlias:
1240 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1241 Range.getBegin(), TU));
1242
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001243 case NestedNameSpecifier::TypeSpec: {
1244 // If the type has a form where we know that the beginning of the source
1245 // range matches up with a reference cursor. Visit the appropriate reference
1246 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001247 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001248 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1249 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1250 if (const TagType *Tag = dyn_cast<TagType>(T))
1251 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1252 if (const TemplateSpecializationType *TST
1253 = dyn_cast<TemplateSpecializationType>(T))
1254 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1255 break;
1256 }
1257
1258 case NestedNameSpecifier::TypeSpecWithTemplate:
1259 case NestedNameSpecifier::Global:
1260 case NestedNameSpecifier::Identifier:
1261 break;
1262 }
1263
1264 return false;
1265}
1266
Douglas Gregordc355712011-02-25 00:36:19 +00001267bool
1268CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001269 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001270 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1271 Qualifiers.push_back(Qualifier);
1272
1273 while (!Qualifiers.empty()) {
1274 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1275 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1276 switch (NNS->getKind()) {
1277 case NestedNameSpecifier::Namespace:
1278 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001279 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001280 TU)))
1281 return true;
1282
1283 break;
1284
1285 case NestedNameSpecifier::NamespaceAlias:
1286 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001287 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001288 TU)))
1289 return true;
1290
1291 break;
1292
1293 case NestedNameSpecifier::TypeSpec:
1294 case NestedNameSpecifier::TypeSpecWithTemplate:
1295 if (Visit(Q.getTypeLoc()))
1296 return true;
1297
1298 break;
1299
1300 case NestedNameSpecifier::Global:
1301 case NestedNameSpecifier::Identifier:
1302 break;
1303 }
1304 }
1305
1306 return false;
1307}
1308
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001309bool CursorVisitor::VisitTemplateParameters(
1310 const TemplateParameterList *Params) {
1311 if (!Params)
1312 return false;
1313
1314 for (TemplateParameterList::const_iterator P = Params->begin(),
1315 PEnd = Params->end();
1316 P != PEnd; ++P) {
1317 if (Visit(MakeCXCursor(*P, TU)))
1318 return true;
1319 }
1320
1321 return false;
1322}
1323
Douglas Gregor0b36e612010-08-31 20:37:03 +00001324bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1325 switch (Name.getKind()) {
1326 case TemplateName::Template:
1327 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1328
1329 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001330 // Visit the overloaded template set.
1331 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1332 return true;
1333
Douglas Gregor0b36e612010-08-31 20:37:03 +00001334 return false;
1335
1336 case TemplateName::DependentTemplate:
1337 // FIXME: Visit nested-name-specifier.
1338 return false;
1339
1340 case TemplateName::QualifiedTemplate:
1341 // FIXME: Visit nested-name-specifier.
1342 return Visit(MakeCursorTemplateRef(
1343 Name.getAsQualifiedTemplateName()->getDecl(),
1344 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001345
1346 case TemplateName::SubstTemplateTemplateParm:
1347 return Visit(MakeCursorTemplateRef(
1348 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1349 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001350
1351 case TemplateName::SubstTemplateTemplateParmPack:
1352 return Visit(MakeCursorTemplateRef(
1353 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1354 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001355 }
1356
1357 return false;
1358}
1359
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001360bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1361 switch (TAL.getArgument().getKind()) {
1362 case TemplateArgument::Null:
1363 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001364 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001365 return false;
1366
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001367 case TemplateArgument::Type:
1368 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1369 return Visit(TSInfo->getTypeLoc());
1370 return false;
1371
1372 case TemplateArgument::Declaration:
1373 if (Expr *E = TAL.getSourceDeclExpression())
1374 return Visit(MakeCXCursor(E, StmtParent, TU));
1375 return false;
1376
1377 case TemplateArgument::Expression:
1378 if (Expr *E = TAL.getSourceExpression())
1379 return Visit(MakeCXCursor(E, StmtParent, TU));
1380 return false;
1381
1382 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001383 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001384 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1385 return true;
1386
Douglas Gregora7fc9012011-01-05 18:58:31 +00001387 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001388 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001389 }
1390
1391 return false;
1392}
1393
Ted Kremeneka0536d82010-05-07 01:04:29 +00001394bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1395 return VisitDeclContext(D);
1396}
1397
Douglas Gregor01829d32010-08-31 14:41:23 +00001398bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1399 return Visit(TL.getUnqualifiedLoc());
1400}
1401
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001402bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001403 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001404
1405 // Some builtin types (such as Objective-C's "id", "sel", and
1406 // "Class") have associated declarations. Create cursors for those.
1407 QualType VisitType;
1408 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001409 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001410 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001411 case BuiltinType::Char_U:
1412 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001413 case BuiltinType::Char16:
1414 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001415 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001416 case BuiltinType::UInt:
1417 case BuiltinType::ULong:
1418 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001419 case BuiltinType::UInt128:
1420 case BuiltinType::Char_S:
1421 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001422 case BuiltinType::WChar_U:
1423 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001424 case BuiltinType::Short:
1425 case BuiltinType::Int:
1426 case BuiltinType::Long:
1427 case BuiltinType::LongLong:
1428 case BuiltinType::Int128:
1429 case BuiltinType::Float:
1430 case BuiltinType::Double:
1431 case BuiltinType::LongDouble:
1432 case BuiltinType::NullPtr:
1433 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001434 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001435 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001436 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001437 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001438
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001439 case BuiltinType::ObjCId:
1440 VisitType = Context.getObjCIdType();
1441 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001442
1443 case BuiltinType::ObjCClass:
1444 VisitType = Context.getObjCClassType();
1445 break;
1446
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001447 case BuiltinType::ObjCSel:
1448 VisitType = Context.getObjCSelType();
1449 break;
1450 }
1451
1452 if (!VisitType.isNull()) {
1453 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455 TU));
1456 }
1457
1458 return false;
1459}
1460
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001461bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001462 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001463}
1464
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001465bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1466 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1467}
1468
1469bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1470 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1471}
1472
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001473bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001474 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001475}
1476
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001477bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1478 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1479 return true;
1480
John McCallc12c5bb2010-05-15 11:32:37 +00001481 return false;
1482}
1483
1484bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1485 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1486 return true;
1487
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001488 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1489 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1490 TU)))
1491 return true;
1492 }
1493
1494 return false;
1495}
1496
1497bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001498 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001499}
1500
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001501bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1502 return Visit(TL.getInnerLoc());
1503}
1504
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001505bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1506 return Visit(TL.getPointeeLoc());
1507}
1508
1509bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1510 return Visit(TL.getPointeeLoc());
1511}
1512
1513bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1514 return Visit(TL.getPointeeLoc());
1515}
1516
1517bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001518 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001519}
1520
1521bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001522 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001523}
1524
Douglas Gregor01829d32010-08-31 14:41:23 +00001525bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1526 bool SkipResultType) {
1527 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001528 return true;
1529
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001530 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001531 if (Decl *D = TL.getArg(I))
1532 if (Visit(MakeCXCursor(D, TU)))
1533 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001534
1535 return false;
1536}
1537
1538bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1539 if (Visit(TL.getElementLoc()))
1540 return true;
1541
1542 if (Expr *Size = TL.getSizeExpr())
1543 return Visit(MakeCXCursor(Size, StmtParent, TU));
1544
1545 return false;
1546}
1547
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001548bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1549 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001550 // Visit the template name.
1551 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1552 TL.getTemplateNameLoc()))
1553 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001554
1555 // Visit the template arguments.
1556 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1557 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1558 return true;
1559
1560 return false;
1561}
1562
Douglas Gregor2332c112010-01-21 20:48:56 +00001563bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1564 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1565}
1566
1567bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1568 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1569 return Visit(TSInfo->getTypeLoc());
1570
1571 return false;
1572}
1573
Sean Huntca63c202011-05-24 22:41:36 +00001574bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1575 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1576 return Visit(TSInfo->getTypeLoc());
1577
1578 return false;
1579}
1580
Douglas Gregor2494dd02011-03-01 01:34:45 +00001581bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1582 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1583 return true;
1584
1585 return false;
1586}
1587
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001588bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1589 DependentTemplateSpecializationTypeLoc TL) {
1590 // Visit the nested-name-specifier, if there is one.
1591 if (TL.getQualifierLoc() &&
1592 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1593 return true;
1594
1595 // Visit the template arguments.
1596 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1597 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1598 return true;
1599
1600 return false;
1601}
1602
Douglas Gregor9e876872011-03-01 18:12:44 +00001603bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1604 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1605 return true;
1606
1607 return Visit(TL.getNamedTypeLoc());
1608}
1609
Douglas Gregor7536dd52010-12-20 02:24:11 +00001610bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1611 return Visit(TL.getPatternLoc());
1612}
1613
Ted Kremenek3064ef92010-08-27 21:34:58 +00001614bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001615 // Visit the nested-name-specifier, if present.
1616 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1617 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1618 return true;
1619
Ted Kremenek3064ef92010-08-27 21:34:58 +00001620 if (D->isDefinition()) {
1621 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1622 E = D->bases_end(); I != E; ++I) {
1623 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1624 return true;
1625 }
1626 }
1627
1628 return VisitTagDecl(D);
1629}
1630
Ted Kremenek09dfa372010-02-18 05:46:33 +00001631bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001632 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1633 i != e; ++i)
1634 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001635 return true;
1636
1637 return false;
1638}
1639
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001640//===----------------------------------------------------------------------===//
1641// Data-recursive visitor methods.
1642//===----------------------------------------------------------------------===//
1643
Ted Kremenek28a71942010-11-13 00:36:47 +00001644namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001645#define DEF_JOB(NAME, DATA, KIND)\
1646class NAME : public VisitorJob {\
1647public:\
1648 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1649 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001650 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001651};
1652
1653DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1654DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001655DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001656DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001657DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1658 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001659DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001660#undef DEF_JOB
1661
1662class DeclVisit : public VisitorJob {
1663public:
1664 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1665 VisitorJob(parent, VisitorJob::DeclVisitKind,
1666 d, isFirst ? (void*) 1 : (void*) 0) {}
1667 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001668 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001669 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001670 Decl *get() const { return static_cast<Decl*>(data[0]); }
1671 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001672};
Ted Kremenek035dc412010-11-13 00:36:50 +00001673class TypeLocVisit : public VisitorJob {
1674public:
1675 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1676 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1677 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1678
1679 static bool classof(const VisitorJob *VJ) {
1680 return VJ->getKind() == TypeLocVisitKind;
1681 }
1682
Ted Kremenek82f3c502010-11-15 22:23:26 +00001683 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001684 QualType T = QualType::getFromOpaquePtr(data[0]);
1685 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001686 }
1687};
1688
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001689class LabelRefVisit : public VisitorJob {
1690public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001691 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1692 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001693 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001694
1695 static bool classof(const VisitorJob *VJ) {
1696 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1697 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001698 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001699 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001700 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001701};
1702class NestedNameSpecifierVisit : public VisitorJob {
1703public:
1704 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1705 CXCursor parent)
1706 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001707 NS, R.getBegin().getPtrEncoding(),
1708 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001709 static bool classof(const VisitorJob *VJ) {
1710 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1711 }
1712 NestedNameSpecifier *get() const {
1713 return static_cast<NestedNameSpecifier*>(data[0]);
1714 }
1715 SourceRange getSourceRange() const {
1716 SourceLocation A =
1717 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1718 SourceLocation B =
1719 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1720 return SourceRange(A, B);
1721 }
1722};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001723
1724class NestedNameSpecifierLocVisit : public VisitorJob {
1725public:
1726 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1727 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1728 Qualifier.getNestedNameSpecifier(),
1729 Qualifier.getOpaqueData()) { }
1730
1731 static bool classof(const VisitorJob *VJ) {
1732 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1733 }
1734
1735 NestedNameSpecifierLoc get() const {
1736 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1737 data[1]);
1738 }
1739};
1740
Ted Kremenekf64d8032010-11-18 00:02:32 +00001741class DeclarationNameInfoVisit : public VisitorJob {
1742public:
1743 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1744 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1745 static bool classof(const VisitorJob *VJ) {
1746 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1747 }
1748 DeclarationNameInfo get() const {
1749 Stmt *S = static_cast<Stmt*>(data[0]);
1750 switch (S->getStmtClass()) {
1751 default:
1752 llvm_unreachable("Unhandled Stmt");
1753 case Stmt::CXXDependentScopeMemberExprClass:
1754 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1755 case Stmt::DependentScopeDeclRefExprClass:
1756 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1757 }
1758 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001759};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001760class MemberRefVisit : public VisitorJob {
1761public:
1762 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1763 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001764 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001765 static bool classof(const VisitorJob *VJ) {
1766 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1767 }
1768 FieldDecl *get() const {
1769 return static_cast<FieldDecl*>(data[0]);
1770 }
1771 SourceLocation getLoc() const {
1772 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1773 }
1774};
Ted Kremenek28a71942010-11-13 00:36:47 +00001775class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1776 VisitorWorkList &WL;
1777 CXCursor Parent;
1778public:
1779 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1780 : WL(wl), Parent(parent) {}
1781
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001782 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001783 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001784 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001785 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001786 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001787 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001788 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001789 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001790 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001791 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001792 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001793 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001794 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001795 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001796 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001797 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001798 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001799 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001800 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1801 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001802 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001803 void VisitIfStmt(IfStmt *If);
1804 void VisitInitListExpr(InitListExpr *IE);
1805 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001806 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001807 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001808 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1809 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001810 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001811 void VisitStmt(Stmt *S);
1812 void VisitSwitchStmt(SwitchStmt *S);
1813 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001814 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001815 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001816 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001817 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001818 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001819 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001820 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001821
Ted Kremenek28a71942010-11-13 00:36:47 +00001822private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001823 void AddDeclarationNameInfo(Stmt *S);
1824 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001825 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001826 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001827 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001828 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001829 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001830 void AddTypeLoc(TypeSourceInfo *TI);
1831 void EnqueueChildren(Stmt *S);
1832};
1833} // end anonyous namespace
1834
Ted Kremenekf64d8032010-11-18 00:02:32 +00001835void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1836 // 'S' should always be non-null, since it comes from the
1837 // statement we are visiting.
1838 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1839}
1840void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1841 SourceRange R) {
1842 if (N)
1843 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1844}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001845
1846void
1847EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1848 if (Qualifier)
1849 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1850}
1851
Ted Kremenek28a71942010-11-13 00:36:47 +00001852void EnqueueVisitor::AddStmt(Stmt *S) {
1853 if (S)
1854 WL.push_back(StmtVisit(S, Parent));
1855}
Ted Kremenek035dc412010-11-13 00:36:50 +00001856void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001857 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001858 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001859}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001860void EnqueueVisitor::
1861 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1862 if (A)
1863 WL.push_back(ExplicitTemplateArgsVisit(
1864 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1865}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001866void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1867 if (D)
1868 WL.push_back(MemberRefVisit(D, L, Parent));
1869}
Ted Kremenek28a71942010-11-13 00:36:47 +00001870void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1871 if (TI)
1872 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1873 }
1874void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001875 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001876 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001877 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001878 }
1879 if (size == WL.size())
1880 return;
1881 // Now reverse the entries we just added. This will match the DFS
1882 // ordering performed by the worklist.
1883 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1884 std::reverse(I, E);
1885}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001886void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1887 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1888}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001889void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1890 AddDecl(B->getBlockDecl());
1891}
Ted Kremenek28a71942010-11-13 00:36:47 +00001892void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1893 EnqueueChildren(E);
1894 AddTypeLoc(E->getTypeSourceInfo());
1895}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001896void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1897 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1898 E = S->body_rend(); I != E; ++I) {
1899 AddStmt(*I);
1900 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001901}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001902void EnqueueVisitor::
1903VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1904 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1905 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001906 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1907 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001908 if (!E->isImplicitAccess())
1909 AddStmt(E->getBase());
1910}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001911void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1912 // Enqueue the initializer or constructor arguments.
1913 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1914 AddStmt(E->getConstructorArg(I-1));
1915 // Enqueue the array size, if any.
1916 AddStmt(E->getArraySize());
1917 // Enqueue the allocated type.
1918 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1919 // Enqueue the placement arguments.
1920 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1921 AddStmt(E->getPlacementArg(I-1));
1922}
Ted Kremenek28a71942010-11-13 00:36:47 +00001923void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001924 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1925 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001926 AddStmt(CE->getCallee());
1927 AddStmt(CE->getArg(0));
1928}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001929void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1930 // Visit the name of the type being destroyed.
1931 AddTypeLoc(E->getDestroyedTypeInfo());
1932 // Visit the scope type that looks disturbingly like the nested-name-specifier
1933 // but isn't.
1934 AddTypeLoc(E->getScopeTypeInfo());
1935 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001936 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1937 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001938 // Visit base expression.
1939 AddStmt(E->getBase());
1940}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001941void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1942 AddTypeLoc(E->getTypeSourceInfo());
1943}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001944void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1945 EnqueueChildren(E);
1946 AddTypeLoc(E->getTypeSourceInfo());
1947}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001948void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1949 EnqueueChildren(E);
1950 if (E->isTypeOperand())
1951 AddTypeLoc(E->getTypeOperandSourceInfo());
1952}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001953
1954void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1955 *E) {
1956 EnqueueChildren(E);
1957 AddTypeLoc(E->getTypeSourceInfo());
1958}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001959void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1960 EnqueueChildren(E);
1961 if (E->isTypeOperand())
1962 AddTypeLoc(E->getTypeOperandSourceInfo());
1963}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001964void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001965 if (DR->hasExplicitTemplateArgs()) {
1966 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1967 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001968 WL.push_back(DeclRefExprParts(DR, Parent));
1969}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001970void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1971 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1972 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001973 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001974}
Ted Kremenek035dc412010-11-13 00:36:50 +00001975void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1976 unsigned size = WL.size();
1977 bool isFirst = true;
1978 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1979 D != DEnd; ++D) {
1980 AddDecl(*D, isFirst);
1981 isFirst = false;
1982 }
1983 if (size == WL.size())
1984 return;
1985 // Now reverse the entries we just added. This will match the DFS
1986 // ordering performed by the worklist.
1987 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1988 std::reverse(I, E);
1989}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001990void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1991 AddStmt(E->getInit());
1992 typedef DesignatedInitExpr::Designator Designator;
1993 for (DesignatedInitExpr::reverse_designators_iterator
1994 D = E->designators_rbegin(), DEnd = E->designators_rend();
1995 D != DEnd; ++D) {
1996 if (D->isFieldDesignator()) {
1997 if (FieldDecl *Field = D->getField())
1998 AddMemberRef(Field, D->getFieldLoc());
1999 continue;
2000 }
2001 if (D->isArrayDesignator()) {
2002 AddStmt(E->getArrayIndex(*D));
2003 continue;
2004 }
2005 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2006 AddStmt(E->getArrayRangeEnd(*D));
2007 AddStmt(E->getArrayRangeStart(*D));
2008 }
2009}
Ted Kremenek28a71942010-11-13 00:36:47 +00002010void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
2011 EnqueueChildren(E);
2012 AddTypeLoc(E->getTypeInfoAsWritten());
2013}
2014void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2015 AddStmt(FS->getBody());
2016 AddStmt(FS->getInc());
2017 AddStmt(FS->getCond());
2018 AddDecl(FS->getConditionVariable());
2019 AddStmt(FS->getInit());
2020}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002021void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2022 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2023}
Ted Kremenek28a71942010-11-13 00:36:47 +00002024void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2025 AddStmt(If->getElse());
2026 AddStmt(If->getThen());
2027 AddStmt(If->getCond());
2028 AddDecl(If->getConditionVariable());
2029}
2030void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2031 // We care about the syntactic form of the initializer list, only.
2032 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2033 IE = Syntactic;
2034 EnqueueChildren(IE);
2035}
2036void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002037 WL.push_back(MemberExprParts(M, Parent));
2038
2039 // If the base of the member access expression is an implicit 'this', don't
2040 // visit it.
2041 // FIXME: If we ever want to show these implicit accesses, this will be
2042 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002043 if (!M->isImplicitAccess())
2044 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002045}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002046void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2047 AddTypeLoc(E->getEncodedTypeSourceInfo());
2048}
Ted Kremenek28a71942010-11-13 00:36:47 +00002049void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2050 EnqueueChildren(M);
2051 AddTypeLoc(M->getClassReceiverTypeInfo());
2052}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002053void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2054 // Visit the components of the offsetof expression.
2055 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2056 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2057 const OffsetOfNode &Node = E->getComponent(I-1);
2058 switch (Node.getKind()) {
2059 case OffsetOfNode::Array:
2060 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2061 break;
2062 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002063 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002064 break;
2065 case OffsetOfNode::Identifier:
2066 case OffsetOfNode::Base:
2067 continue;
2068 }
2069 }
2070 // Visit the type into which we're computing the offset.
2071 AddTypeLoc(E->getTypeSourceInfo());
2072}
Ted Kremenek28a71942010-11-13 00:36:47 +00002073void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002074 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002075 WL.push_back(OverloadExprParts(E, Parent));
2076}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002077void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2078 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002079 EnqueueChildren(E);
2080 if (E->isArgumentType())
2081 AddTypeLoc(E->getArgumentTypeInfo());
2082}
Ted Kremenek28a71942010-11-13 00:36:47 +00002083void EnqueueVisitor::VisitStmt(Stmt *S) {
2084 EnqueueChildren(S);
2085}
2086void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2087 AddStmt(S->getBody());
2088 AddStmt(S->getCond());
2089 AddDecl(S->getConditionVariable());
2090}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002091
Ted Kremenek28a71942010-11-13 00:36:47 +00002092void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2093 AddStmt(W->getBody());
2094 AddStmt(W->getCond());
2095 AddDecl(W->getConditionVariable());
2096}
John Wiegley21ff2e52011-04-28 00:16:57 +00002097
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002098void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2099 AddTypeLoc(E->getQueriedTypeSourceInfo());
2100}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002101
2102void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002103 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002104 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002105}
2106
John Wiegley21ff2e52011-04-28 00:16:57 +00002107void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2108 AddTypeLoc(E->getQueriedTypeSourceInfo());
2109}
2110
John Wiegley55262202011-04-25 06:54:41 +00002111void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2112 EnqueueChildren(E);
2113}
2114
Ted Kremenek28a71942010-11-13 00:36:47 +00002115void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2116 VisitOverloadExpr(U);
2117 if (!U->isImplicitAccess())
2118 AddStmt(U->getBase());
2119}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002120void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2121 AddStmt(E->getSubExpr());
2122 AddTypeLoc(E->getWrittenTypeInfo());
2123}
Douglas Gregor94d96292011-01-19 20:34:17 +00002124void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2125 WL.push_back(SizeOfPackExprParts(E, Parent));
2126}
Ted Kremenek60458782010-11-12 21:34:16 +00002127
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002128void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002129 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002130}
2131
2132bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2133 if (RegionOfInterest.isValid()) {
2134 SourceRange Range = getRawCursorExtent(C);
2135 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2136 return false;
2137 }
2138 return true;
2139}
2140
2141bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2142 while (!WL.empty()) {
2143 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002144 VisitorJob LI = WL.back();
2145 WL.pop_back();
2146
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002147 // Set the Parent field, then back to its old value once we're done.
2148 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2149
2150 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002151 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002152 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002153 if (!D)
2154 continue;
2155
2156 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002157 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002158 return true;
2159
2160 continue;
2161 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002162 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2163 const ExplicitTemplateArgumentList *ArgList =
2164 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2165 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2166 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2167 Arg != ArgEnd; ++Arg) {
2168 if (VisitTemplateArgumentLoc(*Arg))
2169 return true;
2170 }
2171 continue;
2172 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002173 case VisitorJob::TypeLocVisitKind: {
2174 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002175 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002176 return true;
2177 continue;
2178 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002179 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002180 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002181 if (LabelStmt *stmt = LS->getStmt()) {
2182 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2183 TU))) {
2184 return true;
2185 }
2186 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002187 continue;
2188 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002189
Ted Kremenekf64d8032010-11-18 00:02:32 +00002190 case VisitorJob::NestedNameSpecifierVisitKind: {
2191 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2192 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2193 return true;
2194 continue;
2195 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002196
2197 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2198 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2199 if (VisitNestedNameSpecifierLoc(V->get()))
2200 return true;
2201 continue;
2202 }
2203
Ted Kremenekf64d8032010-11-18 00:02:32 +00002204 case VisitorJob::DeclarationNameInfoVisitKind: {
2205 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2206 ->get()))
2207 return true;
2208 continue;
2209 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002210 case VisitorJob::MemberRefVisitKind: {
2211 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2212 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2213 return true;
2214 continue;
2215 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002216 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002217 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002218 if (!S)
2219 continue;
2220
Ted Kremenekf1107452010-11-12 18:26:56 +00002221 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002222 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002223 if (!IsInRegionOfInterest(Cursor))
2224 continue;
2225 switch (Visitor(Cursor, Parent, ClientData)) {
2226 case CXChildVisit_Break: return true;
2227 case CXChildVisit_Continue: break;
2228 case CXChildVisit_Recurse:
2229 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002230 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002231 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002232 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002233 }
2234 case VisitorJob::MemberExprPartsKind: {
2235 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002236 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002237
2238 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002239 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2240 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002241 return true;
2242
2243 // Visit the declaration name.
2244 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2245 return true;
2246
2247 // Visit the explicitly-specified template arguments, if any.
2248 if (M->hasExplicitTemplateArgs()) {
2249 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2250 *ArgEnd = Arg + M->getNumTemplateArgs();
2251 Arg != ArgEnd; ++Arg) {
2252 if (VisitTemplateArgumentLoc(*Arg))
2253 return true;
2254 }
2255 }
2256 continue;
2257 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002258 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002259 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002260 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002261 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2262 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002263 return true;
2264 // Visit declaration name.
2265 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2266 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002267 continue;
2268 }
Ted Kremenek60458782010-11-12 21:34:16 +00002269 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002270 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002271 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002272 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2273 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002274 return true;
2275 // Visit the declaration name.
2276 if (VisitDeclarationNameInfo(O->getNameInfo()))
2277 return true;
2278 // Visit the overloaded declaration reference.
2279 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2280 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002281 continue;
2282 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002283 case VisitorJob::SizeOfPackExprPartsKind: {
2284 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2285 NamedDecl *Pack = E->getPack();
2286 if (isa<TemplateTypeParmDecl>(Pack)) {
2287 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2288 E->getPackLoc(), TU)))
2289 return true;
2290
2291 continue;
2292 }
2293
2294 if (isa<TemplateTemplateParmDecl>(Pack)) {
2295 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2296 E->getPackLoc(), TU)))
2297 return true;
2298
2299 continue;
2300 }
2301
2302 // Non-type template parameter packs and function parameter packs are
2303 // treated like DeclRefExpr cursors.
2304 continue;
2305 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002306 }
2307 }
2308 return false;
2309}
2310
Ted Kremenekcdba6592010-11-18 00:42:18 +00002311bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002312 VisitorWorkList *WL = 0;
2313 if (!WorkListFreeList.empty()) {
2314 WL = WorkListFreeList.back();
2315 WL->clear();
2316 WorkListFreeList.pop_back();
2317 }
2318 else {
2319 WL = new VisitorWorkList();
2320 WorkListCache.push_back(WL);
2321 }
2322 EnqueueWorkList(*WL, S);
2323 bool result = RunVisitorWorkList(*WL);
2324 WorkListFreeList.push_back(WL);
2325 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002326}
2327
2328//===----------------------------------------------------------------------===//
2329// Misc. API hooks.
2330//===----------------------------------------------------------------------===//
2331
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002332static llvm::sys::Mutex EnableMultithreadingMutex;
2333static bool EnabledMultithreading;
2334
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002335extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002336CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2337 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002338 // Disable pretty stack trace functionality, which will otherwise be a very
2339 // poor citizen of the world and set up all sorts of signal handlers.
2340 llvm::DisablePrettyStackTrace = true;
2341
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002342 // We use crash recovery to make some of our APIs more reliable, implicitly
2343 // enable it.
2344 llvm::CrashRecoveryContext::Enable();
2345
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002346 // Enable support for multithreading in LLVM.
2347 {
2348 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2349 if (!EnabledMultithreading) {
2350 llvm::llvm_start_multithreaded();
2351 EnabledMultithreading = true;
2352 }
2353 }
2354
Douglas Gregora030b7c2010-01-22 20:35:53 +00002355 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002356 if (excludeDeclarationsFromPCH)
2357 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002358 if (displayDiagnostics)
2359 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002360 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002361}
2362
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002363void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002364 if (CIdx)
2365 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002366}
2367
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002368void clang_toggleCrashRecovery(unsigned isEnabled) {
2369 if (isEnabled)
2370 llvm::CrashRecoveryContext::Enable();
2371 else
2372 llvm::CrashRecoveryContext::Disable();
2373}
2374
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002375CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002376 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002377 if (!CIdx)
2378 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002379
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002380 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002381 FileSystemOptions FileSystemOpts;
2382 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002383
Douglas Gregor28019772010-04-05 23:52:57 +00002384 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002385 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002386 CXXIdx->getOnlyLocalDecls(),
2387 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002388 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002389}
2390
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002391unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002392 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002393 CXTranslationUnit_CacheCompletionResults |
John McCallf85e1932011-06-15 23:02:42 +00002394 CXTranslationUnit_CXXPrecompiledPreamble |
2395 CXTranslationUnit_CXXChainedPCH;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002396}
2397
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002398CXTranslationUnit
2399clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2400 const char *source_filename,
2401 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002402 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002403 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002404 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002405 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002406 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002407 return clang_parseTranslationUnit(CIdx, source_filename,
2408 command_line_args, num_command_line_args,
2409 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002410 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002411}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002412
2413struct ParseTranslationUnitInfo {
2414 CXIndex CIdx;
2415 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002416 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002417 int num_command_line_args;
2418 struct CXUnsavedFile *unsaved_files;
2419 unsigned num_unsaved_files;
2420 unsigned options;
2421 CXTranslationUnit result;
2422};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002423static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002424 ParseTranslationUnitInfo *PTUI =
2425 static_cast<ParseTranslationUnitInfo*>(UserData);
2426 CXIndex CIdx = PTUI->CIdx;
2427 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002428 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002429 int num_command_line_args = PTUI->num_command_line_args;
2430 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2431 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2432 unsigned options = PTUI->options;
2433 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002434
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002435 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002436 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002437
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002438 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2439
Douglas Gregor44c181a2010-07-23 00:33:23 +00002440 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002441 bool CompleteTranslationUnit
2442 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002443 bool CacheCodeCompetionResults
2444 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002445 bool CXXPrecompilePreamble
2446 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2447 bool CXXChainedPCH
2448 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002449
Douglas Gregor5352ac02010-01-28 00:27:43 +00002450 // Configure the diagnostics.
2451 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002452 llvm::IntrusiveRefCntPtr<Diagnostic>
2453 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2454 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002455
Ted Kremenek25a11e12011-03-22 01:15:24 +00002456 // Recover resources if we crash before exiting this function.
2457 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2458 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2459 DiagCleanup(Diags.getPtr());
2460
2461 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2462 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2463
2464 // Recover resources if we crash before exiting this function.
2465 llvm::CrashRecoveryContextCleanupRegistrar<
2466 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2467
Douglas Gregor4db64a42010-01-23 00:14:00 +00002468 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002469 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002470 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002471 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002472 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2473 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002474 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002475
Ted Kremenek25a11e12011-03-22 01:15:24 +00002476 llvm::OwningPtr<std::vector<const char *> >
2477 Args(new std::vector<const char*>());
2478
2479 // Recover resources if we crash before exiting this method.
2480 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2481 ArgsCleanup(Args.get());
2482
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002483 // Since the Clang C library is primarily used by batch tools dealing with
2484 // (often very broken) source code, where spell-checking can have a
2485 // significant negative impact on performance (particularly when
2486 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002487 // Only do this if we haven't found a spell-checking-related argument.
2488 bool FoundSpellCheckingArgument = false;
2489 for (int I = 0; I != num_command_line_args; ++I) {
2490 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2491 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2492 FoundSpellCheckingArgument = true;
2493 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002494 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002495 }
2496 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002497 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002498
Ted Kremenek25a11e12011-03-22 01:15:24 +00002499 Args->insert(Args->end(), command_line_args,
2500 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002501
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002502 // The 'source_filename' argument is optional. If the caller does not
2503 // specify it then it is assumed that the source file is specified
2504 // in the actual argument list.
2505 // Put the source file after command_line_args otherwise if '-x' flag is
2506 // present it will be unused.
2507 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002508 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002509
Douglas Gregor44c181a2010-07-23 00:33:23 +00002510 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002511 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002512 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002513 Args->push_back("-Xclang");
2514 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002515 NestedMacroExpansions
2516 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002517 }
2518
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002519 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002520 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002521 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2522 /* vector::data() not portable */,
2523 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002524 Diags,
2525 CXXIdx->getClangResourcesPath(),
2526 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002527 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002528 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002529 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002530 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002531 PrecompilePreamble,
2532 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002533 CacheCodeCompetionResults,
2534 CXXPrecompilePreamble,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002535 CXXChainedPCH,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002536 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002537
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002538 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002539 // Make sure to check that 'Unit' is non-NULL.
2540 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2541 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2542 DEnd = Unit->stored_diag_end();
2543 D != DEnd; ++D) {
2544 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2545 CXString Msg = clang_formatDiagnostic(&Diag,
2546 clang_defaultDiagnosticDisplayOptions());
2547 fprintf(stderr, "%s\n", clang_getCString(Msg));
2548 clang_disposeString(Msg);
2549 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002550#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002551 // On Windows, force a flush, since there may be multiple copies of
2552 // stderr and stdout in the file system, all with different buffers
2553 // but writing to the same device.
2554 fflush(stderr);
2555#endif
2556 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002557 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002558
Ted Kremeneka60ed472010-11-16 08:15:36 +00002559 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002560}
2561CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2562 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002563 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002564 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002565 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002566 unsigned num_unsaved_files,
2567 unsigned options) {
2568 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002569 num_command_line_args, unsaved_files,
2570 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002571 llvm::CrashRecoveryContext CRC;
2572
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002573 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002574 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2575 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2576 fprintf(stderr, " 'command_line_args' : [");
2577 for (int i = 0; i != num_command_line_args; ++i) {
2578 if (i)
2579 fprintf(stderr, ", ");
2580 fprintf(stderr, "'%s'", command_line_args[i]);
2581 }
2582 fprintf(stderr, "],\n");
2583 fprintf(stderr, " 'unsaved_files' : [");
2584 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2585 if (i)
2586 fprintf(stderr, ", ");
2587 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2588 unsaved_files[i].Length);
2589 }
2590 fprintf(stderr, "],\n");
2591 fprintf(stderr, " 'options' : %d,\n", options);
2592 fprintf(stderr, "}\n");
2593
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002594 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002595 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2596 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002597 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002598
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002599 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002600}
2601
Douglas Gregor19998442010-08-13 15:35:05 +00002602unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2603 return CXSaveTranslationUnit_None;
2604}
2605
2606int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2607 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002608 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002609 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002610
Douglas Gregor39c411f2011-07-06 16:43:36 +00002611 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002612 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2613 PrintLibclangResourceUsage(TU);
2614 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002615}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002616
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002617void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002618 if (CTUnit) {
2619 // If the translation unit has been marked as unsafe to free, just discard
2620 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002621 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002622 return;
2623
Ted Kremeneka60ed472010-11-16 08:15:36 +00002624 delete static_cast<ASTUnit *>(CTUnit->TUData);
2625 disposeCXStringPool(CTUnit->StringPool);
2626 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002627 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002628}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002629
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002630unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2631 return CXReparse_None;
2632}
2633
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002634struct ReparseTranslationUnitInfo {
2635 CXTranslationUnit TU;
2636 unsigned num_unsaved_files;
2637 struct CXUnsavedFile *unsaved_files;
2638 unsigned options;
2639 int result;
2640};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002641
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002642static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002643 ReparseTranslationUnitInfo *RTUI =
2644 static_cast<ReparseTranslationUnitInfo*>(UserData);
2645 CXTranslationUnit TU = RTUI->TU;
2646 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2647 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2648 unsigned options = RTUI->options;
2649 (void) options;
2650 RTUI->result = 1;
2651
Douglas Gregorabc563f2010-07-19 21:46:24 +00002652 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002653 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002654
Ted Kremeneka60ed472010-11-16 08:15:36 +00002655 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002656 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002657
Ted Kremenek25a11e12011-03-22 01:15:24 +00002658 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2659 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2660
2661 // Recover resources if we crash before exiting this function.
2662 llvm::CrashRecoveryContextCleanupRegistrar<
2663 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2664
Douglas Gregorabc563f2010-07-19 21:46:24 +00002665 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002666 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002667 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002668 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002669 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2670 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002671 }
2672
Ted Kremenek4ee99262011-03-22 20:16:19 +00002673 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2674 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002675 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002676}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002677
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002678int clang_reparseTranslationUnit(CXTranslationUnit TU,
2679 unsigned num_unsaved_files,
2680 struct CXUnsavedFile *unsaved_files,
2681 unsigned options) {
2682 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2683 options, 0 };
2684 llvm::CrashRecoveryContext CRC;
2685
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002686 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002687 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002688 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002689 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002690 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2691 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002692
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002693 return RTUI.result;
2694}
2695
Douglas Gregordf95a132010-08-09 20:45:32 +00002696
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002697CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002698 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002699 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002700
Ted Kremeneka60ed472010-11-16 08:15:36 +00002701 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002702 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002703}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002704
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002705CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002706 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002707 return Result;
2708}
2709
Ted Kremenekfb480492010-01-13 21:46:36 +00002710} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002711
Ted Kremenekfb480492010-01-13 21:46:36 +00002712//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002713// CXSourceLocation and CXSourceRange Operations.
2714//===----------------------------------------------------------------------===//
2715
Douglas Gregorb9790342010-01-22 21:44:22 +00002716extern "C" {
2717CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002718 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002719 return Result;
2720}
2721
2722unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002723 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2724 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2725 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002726}
2727
2728CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2729 CXFile file,
2730 unsigned line,
2731 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002732 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002733 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002734
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002735 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002736 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002737 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002738 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002739 = CXXUnit->getSourceManager().getLocation(File, line, column);
2740 if (SLoc.isInvalid()) {
2741 if (Logging)
2742 llvm::errs() << "clang_getLocation(\"" << File->getName()
2743 << "\", " << line << ", " << column << ") = invalid\n";
2744 return clang_getNullLocation();
2745 }
2746
2747 if (Logging)
2748 llvm::errs() << "clang_getLocation(\"" << File->getName()
2749 << "\", " << line << ", " << column << ") = "
2750 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002751
2752 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2753}
2754
2755CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2756 CXFile file,
2757 unsigned offset) {
2758 if (!tu || !file)
2759 return clang_getNullLocation();
2760
Ted Kremeneka60ed472010-11-16 08:15:36 +00002761 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002762 SourceLocation Start
2763 = CXXUnit->getSourceManager().getLocation(
2764 static_cast<const FileEntry *>(file),
2765 1, 1);
2766 if (Start.isInvalid()) return clang_getNullLocation();
2767
2768 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2769
2770 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002771
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002772 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002773}
2774
Douglas Gregor5352ac02010-01-28 00:27:43 +00002775CXSourceRange clang_getNullRange() {
2776 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2777 return Result;
2778}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002779
Douglas Gregor5352ac02010-01-28 00:27:43 +00002780CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2781 if (begin.ptr_data[0] != end.ptr_data[0] ||
2782 begin.ptr_data[1] != end.ptr_data[1])
2783 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002784
2785 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002786 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002787 return Result;
2788}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002789
2790unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2791{
2792 return range1.ptr_data[0] == range2.ptr_data[0]
2793 && range1.ptr_data[1] == range2.ptr_data[1]
2794 && range1.begin_int_data == range2.begin_int_data
2795 && range1.end_int_data == range2.end_int_data;
2796}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002797} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002798
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002799static void createNullLocation(CXFile *file, unsigned *line,
2800 unsigned *column, unsigned *offset) {
2801 if (file)
2802 *file = 0;
2803 if (line)
2804 *line = 0;
2805 if (column)
2806 *column = 0;
2807 if (offset)
2808 *offset = 0;
2809 return;
2810}
2811
2812extern "C" {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002813void clang_getInstantiationLocation(CXSourceLocation location,
2814 CXFile *file,
2815 unsigned *line,
2816 unsigned *column,
2817 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002818 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2819
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002820 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002821 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002822 return;
2823 }
2824
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002825 const SourceManager &SM =
2826 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth40278532011-07-25 16:49:02 +00002827 SourceLocation InstLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002828
Chandler Carruthcea731a2011-07-14 16:07:57 +00002829 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002830 // This can manifest in invalid code.
2831 FileID fileID = SM.getFileID(InstLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002832 bool Invalid = false;
2833 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2834 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002835 createNullLocation(file, line, column, offset);
2836 return;
2837 }
2838
Douglas Gregor1db19de2010-01-19 21:36:55 +00002839 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002840 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002841 if (line)
2842 *line = SM.getInstantiationLineNumber(InstLoc);
2843 if (column)
2844 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002845 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002846 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002847}
2848
Douglas Gregora9b06d42010-11-09 06:24:54 +00002849void clang_getSpellingLocation(CXSourceLocation location,
2850 CXFile *file,
2851 unsigned *line,
2852 unsigned *column,
2853 unsigned *offset) {
2854 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2855
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002856 if (!location.ptr_data[0] || Loc.isInvalid())
2857 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002858
2859 const SourceManager &SM =
2860 *static_cast<const SourceManager*>(location.ptr_data[0]);
2861 SourceLocation SpellLoc = Loc;
2862 if (SpellLoc.isMacroID()) {
2863 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2864 if (SimpleSpellingLoc.isFileID() &&
2865 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2866 SpellLoc = SimpleSpellingLoc;
2867 else
Chandler Carruth40278532011-07-25 16:49:02 +00002868 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002869 }
2870
2871 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2872 FileID FID = LocInfo.first;
2873 unsigned FileOffset = LocInfo.second;
2874
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002875 if (FID.isInvalid())
2876 return createNullLocation(file, line, column, offset);
2877
Douglas Gregora9b06d42010-11-09 06:24:54 +00002878 if (file)
2879 *file = (void *)SM.getFileEntryForID(FID);
2880 if (line)
2881 *line = SM.getLineNumber(FID, FileOffset);
2882 if (column)
2883 *column = SM.getColumnNumber(FID, FileOffset);
2884 if (offset)
2885 *offset = FileOffset;
2886}
2887
Douglas Gregor1db19de2010-01-19 21:36:55 +00002888CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002889 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002890 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002891 return Result;
2892}
2893
2894CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002895 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002896 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002897 return Result;
2898}
2899
Douglas Gregorb9790342010-01-22 21:44:22 +00002900} // end: extern "C"
2901
Douglas Gregor1db19de2010-01-19 21:36:55 +00002902//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002903// CXFile Operations.
2904//===----------------------------------------------------------------------===//
2905
2906extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002907CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002908 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002909 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002910
Steve Naroff88145032009-10-27 14:35:18 +00002911 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002912 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002913}
2914
2915time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002916 if (!SFile)
2917 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002918
Steve Naroff88145032009-10-27 14:35:18 +00002919 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2920 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002921}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002922
Douglas Gregorb9790342010-01-22 21:44:22 +00002923CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2924 if (!tu)
2925 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002926
Ted Kremeneka60ed472010-11-16 08:15:36 +00002927 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002928
Douglas Gregorb9790342010-01-22 21:44:22 +00002929 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002930 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002931}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002932
Douglas Gregordd3e5542011-05-04 00:14:37 +00002933unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2934 if (!tu || !file)
2935 return 0;
2936
2937 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2938 FileEntry *FEnt = static_cast<FileEntry *>(file);
2939 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2940 .isFileMultipleIncludeGuarded(FEnt);
2941}
2942
Ted Kremenekfb480492010-01-13 21:46:36 +00002943} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002944
Ted Kremenekfb480492010-01-13 21:46:36 +00002945//===----------------------------------------------------------------------===//
2946// CXCursor Operations.
2947//===----------------------------------------------------------------------===//
2948
Ted Kremenekfb480492010-01-13 21:46:36 +00002949static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002950 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2951 return getDeclFromExpr(CE->getSubExpr());
2952
Ted Kremenekfb480492010-01-13 21:46:36 +00002953 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2954 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002955 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2956 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002957 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2958 return ME->getMemberDecl();
2959 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2960 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002961 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002962 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002963
Ted Kremenekfb480492010-01-13 21:46:36 +00002964 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2965 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002966 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002967 if (!CE->isElidable())
2968 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002969 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2970 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002971
Douglas Gregordb1314e2010-10-01 21:11:22 +00002972 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2973 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002974 if (SubstNonTypeTemplateParmPackExpr *NTTP
2975 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2976 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002977 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2978 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2979 isa<ParmVarDecl>(SizeOfPack->getPack()))
2980 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002981
Ted Kremenekfb480492010-01-13 21:46:36 +00002982 return 0;
2983}
2984
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002985static SourceLocation getLocationFromExpr(Expr *E) {
2986 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2987 return /*FIXME:*/Msg->getLeftLoc();
2988 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2989 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002990 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2991 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002992 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2993 return Member->getMemberLoc();
2994 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2995 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002996 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2997 return SizeOfPack->getPackLoc();
2998
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002999 return E->getLocStart();
3000}
3001
Ted Kremenekfb480492010-01-13 21:46:36 +00003002extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003003
3004unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003005 CXCursorVisitor visitor,
3006 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003007 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003008 getCursorASTUnit(parent)->getMaxPCHLevel(),
3009 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003010 return CursorVis.VisitChildren(parent);
3011}
3012
David Chisnall3387c652010-11-03 14:12:26 +00003013#ifndef __has_feature
3014#define __has_feature(x) 0
3015#endif
3016#if __has_feature(blocks)
3017typedef enum CXChildVisitResult
3018 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3019
3020static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3021 CXClientData client_data) {
3022 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3023 return block(cursor, parent);
3024}
3025#else
3026// If we are compiled with a compiler that doesn't have native blocks support,
3027// define and call the block manually, so the
3028typedef struct _CXChildVisitResult
3029{
3030 void *isa;
3031 int flags;
3032 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003033 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3034 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003035} *CXCursorVisitorBlock;
3036
3037static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3038 CXClientData client_data) {
3039 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3040 return block->invoke(block, cursor, parent);
3041}
3042#endif
3043
3044
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003045unsigned clang_visitChildrenWithBlock(CXCursor parent,
3046 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003047 return clang_visitChildren(parent, visitWithBlock, block);
3048}
3049
Douglas Gregor78205d42010-01-20 21:45:58 +00003050static CXString getDeclSpelling(Decl *D) {
3051 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003052 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003053 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003054 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3055 return createCXString(Property->getIdentifier()->getName());
3056
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003057 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003058 }
3059
Douglas Gregor78205d42010-01-20 21:45:58 +00003060 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003061 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003062
Douglas Gregor78205d42010-01-20 21:45:58 +00003063 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3064 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3065 // and returns different names. NamedDecl returns the class name and
3066 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003067 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003068
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003069 if (isa<UsingDirectiveDecl>(D))
3070 return createCXString("");
3071
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003072 llvm::SmallString<1024> S;
3073 llvm::raw_svector_ostream os(S);
3074 ND->printName(os);
3075
3076 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003077}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003078
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003079CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003080 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003081 return clang_getTranslationUnitSpelling(
3082 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003083
Steve Narofff334b4e2009-09-02 18:26:48 +00003084 if (clang_isReference(C.kind)) {
3085 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003086 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003087 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003088 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003089 }
3090 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003091 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003092 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003093 }
3094 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003095 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003096 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003097 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003098 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003099 case CXCursor_CXXBaseSpecifier: {
3100 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3101 return createCXString(B->getType().getAsString());
3102 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003103 case CXCursor_TypeRef: {
3104 TypeDecl *Type = getCursorTypeRef(C).first;
3105 assert(Type && "Missing type decl");
3106
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003107 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3108 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003109 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003110 case CXCursor_TemplateRef: {
3111 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003112 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003113
3114 return createCXString(Template->getNameAsString());
3115 }
Douglas Gregor69319002010-08-31 23:48:11 +00003116
3117 case CXCursor_NamespaceRef: {
3118 NamedDecl *NS = getCursorNamespaceRef(C).first;
3119 assert(NS && "Missing namespace decl");
3120
3121 return createCXString(NS->getNameAsString());
3122 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003123
Douglas Gregora67e03f2010-09-09 21:42:20 +00003124 case CXCursor_MemberRef: {
3125 FieldDecl *Field = getCursorMemberRef(C).first;
3126 assert(Field && "Missing member decl");
3127
3128 return createCXString(Field->getNameAsString());
3129 }
3130
Douglas Gregor36897b02010-09-10 00:22:18 +00003131 case CXCursor_LabelRef: {
3132 LabelStmt *Label = getCursorLabelRef(C).first;
3133 assert(Label && "Missing label");
3134
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003135 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003136 }
3137
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003138 case CXCursor_OverloadedDeclRef: {
3139 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3140 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3141 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3142 return createCXString(ND->getNameAsString());
3143 return createCXString("");
3144 }
3145 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3146 return createCXString(E->getName().getAsString());
3147 OverloadedTemplateStorage *Ovl
3148 = Storage.get<OverloadedTemplateStorage*>();
3149 if (Ovl->size() == 0)
3150 return createCXString("");
3151 return createCXString((*Ovl->begin())->getNameAsString());
3152 }
3153
Daniel Dunbaracca7252009-11-30 20:42:49 +00003154 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003155 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003156 }
3157 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003158
3159 if (clang_isExpression(C.kind)) {
3160 Decl *D = getDeclFromExpr(getCursorExpr(C));
3161 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003162 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003163 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003164 }
3165
Douglas Gregor36897b02010-09-10 00:22:18 +00003166 if (clang_isStatement(C.kind)) {
3167 Stmt *S = getCursorStmt(C);
3168 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003169 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003170
3171 return createCXString("");
3172 }
3173
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003174 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003175 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003176 ->getNameStart());
3177
Douglas Gregor572feb22010-03-18 18:04:21 +00003178 if (C.kind == CXCursor_MacroDefinition)
3179 return createCXString(getCursorMacroDefinition(C)->getName()
3180 ->getNameStart());
3181
Douglas Gregorecdcb882010-10-20 22:00:55 +00003182 if (C.kind == CXCursor_InclusionDirective)
3183 return createCXString(getCursorInclusionDirective(C)->getFileName());
3184
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003185 if (clang_isDeclaration(C.kind))
3186 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003187
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003188 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003189}
3190
Douglas Gregor358559d2010-10-02 22:49:11 +00003191CXString clang_getCursorDisplayName(CXCursor C) {
3192 if (!clang_isDeclaration(C.kind))
3193 return clang_getCursorSpelling(C);
3194
3195 Decl *D = getCursorDecl(C);
3196 if (!D)
3197 return createCXString("");
3198
3199 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3200 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3201 D = FunTmpl->getTemplatedDecl();
3202
3203 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3204 llvm::SmallString<64> Str;
3205 llvm::raw_svector_ostream OS(Str);
3206 OS << Function->getNameAsString();
3207 if (Function->getPrimaryTemplate())
3208 OS << "<>";
3209 OS << "(";
3210 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3211 if (I)
3212 OS << ", ";
3213 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3214 }
3215
3216 if (Function->isVariadic()) {
3217 if (Function->getNumParams())
3218 OS << ", ";
3219 OS << "...";
3220 }
3221 OS << ")";
3222 return createCXString(OS.str());
3223 }
3224
3225 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3226 llvm::SmallString<64> Str;
3227 llvm::raw_svector_ostream OS(Str);
3228 OS << ClassTemplate->getNameAsString();
3229 OS << "<";
3230 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3231 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3232 if (I)
3233 OS << ", ";
3234
3235 NamedDecl *Param = Params->getParam(I);
3236 if (Param->getIdentifier()) {
3237 OS << Param->getIdentifier()->getName();
3238 continue;
3239 }
3240
3241 // There is no parameter name, which makes this tricky. Try to come up
3242 // with something useful that isn't too long.
3243 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3244 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3245 else if (NonTypeTemplateParmDecl *NTTP
3246 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3247 OS << NTTP->getType().getAsString(Policy);
3248 else
3249 OS << "template<...> class";
3250 }
3251
3252 OS << ">";
3253 return createCXString(OS.str());
3254 }
3255
3256 if (ClassTemplateSpecializationDecl *ClassSpec
3257 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3258 // If the type was explicitly written, use that.
3259 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3260 return createCXString(TSInfo->getType().getAsString(Policy));
3261
3262 llvm::SmallString<64> Str;
3263 llvm::raw_svector_ostream OS(Str);
3264 OS << ClassSpec->getNameAsString();
3265 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003266 ClassSpec->getTemplateArgs().data(),
3267 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003268 Policy);
3269 return createCXString(OS.str());
3270 }
3271
3272 return clang_getCursorSpelling(C);
3273}
3274
Ted Kremeneke68fff62010-02-17 00:41:32 +00003275CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003276 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003277 case CXCursor_FunctionDecl:
3278 return createCXString("FunctionDecl");
3279 case CXCursor_TypedefDecl:
3280 return createCXString("TypedefDecl");
3281 case CXCursor_EnumDecl:
3282 return createCXString("EnumDecl");
3283 case CXCursor_EnumConstantDecl:
3284 return createCXString("EnumConstantDecl");
3285 case CXCursor_StructDecl:
3286 return createCXString("StructDecl");
3287 case CXCursor_UnionDecl:
3288 return createCXString("UnionDecl");
3289 case CXCursor_ClassDecl:
3290 return createCXString("ClassDecl");
3291 case CXCursor_FieldDecl:
3292 return createCXString("FieldDecl");
3293 case CXCursor_VarDecl:
3294 return createCXString("VarDecl");
3295 case CXCursor_ParmDecl:
3296 return createCXString("ParmDecl");
3297 case CXCursor_ObjCInterfaceDecl:
3298 return createCXString("ObjCInterfaceDecl");
3299 case CXCursor_ObjCCategoryDecl:
3300 return createCXString("ObjCCategoryDecl");
3301 case CXCursor_ObjCProtocolDecl:
3302 return createCXString("ObjCProtocolDecl");
3303 case CXCursor_ObjCPropertyDecl:
3304 return createCXString("ObjCPropertyDecl");
3305 case CXCursor_ObjCIvarDecl:
3306 return createCXString("ObjCIvarDecl");
3307 case CXCursor_ObjCInstanceMethodDecl:
3308 return createCXString("ObjCInstanceMethodDecl");
3309 case CXCursor_ObjCClassMethodDecl:
3310 return createCXString("ObjCClassMethodDecl");
3311 case CXCursor_ObjCImplementationDecl:
3312 return createCXString("ObjCImplementationDecl");
3313 case CXCursor_ObjCCategoryImplDecl:
3314 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003315 case CXCursor_CXXMethod:
3316 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003317 case CXCursor_UnexposedDecl:
3318 return createCXString("UnexposedDecl");
3319 case CXCursor_ObjCSuperClassRef:
3320 return createCXString("ObjCSuperClassRef");
3321 case CXCursor_ObjCProtocolRef:
3322 return createCXString("ObjCProtocolRef");
3323 case CXCursor_ObjCClassRef:
3324 return createCXString("ObjCClassRef");
3325 case CXCursor_TypeRef:
3326 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003327 case CXCursor_TemplateRef:
3328 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003329 case CXCursor_NamespaceRef:
3330 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003331 case CXCursor_MemberRef:
3332 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003333 case CXCursor_LabelRef:
3334 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003335 case CXCursor_OverloadedDeclRef:
3336 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003337 case CXCursor_UnexposedExpr:
3338 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003339 case CXCursor_BlockExpr:
3340 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003341 case CXCursor_DeclRefExpr:
3342 return createCXString("DeclRefExpr");
3343 case CXCursor_MemberRefExpr:
3344 return createCXString("MemberRefExpr");
3345 case CXCursor_CallExpr:
3346 return createCXString("CallExpr");
3347 case CXCursor_ObjCMessageExpr:
3348 return createCXString("ObjCMessageExpr");
3349 case CXCursor_UnexposedStmt:
3350 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003351 case CXCursor_LabelStmt:
3352 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003353 case CXCursor_InvalidFile:
3354 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003355 case CXCursor_InvalidCode:
3356 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003357 case CXCursor_NoDeclFound:
3358 return createCXString("NoDeclFound");
3359 case CXCursor_NotImplemented:
3360 return createCXString("NotImplemented");
3361 case CXCursor_TranslationUnit:
3362 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003363 case CXCursor_UnexposedAttr:
3364 return createCXString("UnexposedAttr");
3365 case CXCursor_IBActionAttr:
3366 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003367 case CXCursor_IBOutletAttr:
3368 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003369 case CXCursor_IBOutletCollectionAttr:
3370 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003371 case CXCursor_PreprocessingDirective:
3372 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003373 case CXCursor_MacroDefinition:
3374 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003375 case CXCursor_MacroExpansion:
3376 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003377 case CXCursor_InclusionDirective:
3378 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003379 case CXCursor_Namespace:
3380 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003381 case CXCursor_LinkageSpec:
3382 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003383 case CXCursor_CXXBaseSpecifier:
3384 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003385 case CXCursor_Constructor:
3386 return createCXString("CXXConstructor");
3387 case CXCursor_Destructor:
3388 return createCXString("CXXDestructor");
3389 case CXCursor_ConversionFunction:
3390 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003391 case CXCursor_TemplateTypeParameter:
3392 return createCXString("TemplateTypeParameter");
3393 case CXCursor_NonTypeTemplateParameter:
3394 return createCXString("NonTypeTemplateParameter");
3395 case CXCursor_TemplateTemplateParameter:
3396 return createCXString("TemplateTemplateParameter");
3397 case CXCursor_FunctionTemplate:
3398 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003399 case CXCursor_ClassTemplate:
3400 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003401 case CXCursor_ClassTemplatePartialSpecialization:
3402 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003403 case CXCursor_NamespaceAlias:
3404 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003405 case CXCursor_UsingDirective:
3406 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003407 case CXCursor_UsingDeclaration:
3408 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003409 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003410 return createCXString("TypeAliasDecl");
3411 case CXCursor_ObjCSynthesizeDecl:
3412 return createCXString("ObjCSynthesizeDecl");
3413 case CXCursor_ObjCDynamicDecl:
3414 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003415 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003416
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003417 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003418 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003419}
Steve Naroff89922f82009-08-31 00:59:03 +00003420
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003421struct GetCursorData {
3422 SourceLocation TokenBeginLoc;
3423 CXCursor &BestCursor;
3424
3425 GetCursorData(SourceLocation tokenBegin, CXCursor &outputCursor)
3426 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { }
3427};
3428
Ted Kremeneke68fff62010-02-17 00:41:32 +00003429enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3430 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003431 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003432 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3433 CXCursor *BestCursor = &Data->BestCursor;
3434
3435 if (clang_isExpression(cursor.kind) &&
3436 clang_isDeclaration(BestCursor->kind)) {
3437 Decl *D = getCursorDecl(*BestCursor);
3438
3439 // Avoid having the cursor of an expression replace the declaration cursor
3440 // when the expression source range overlaps the declaration range.
3441 // This can happen for C++ constructor expressions whose range generally
3442 // include the variable declaration, e.g.:
3443 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3444 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3445 D->getLocation() == Data->TokenBeginLoc)
3446 return CXChildVisit_Break;
3447 }
3448
Douglas Gregor93798e22010-11-05 21:11:19 +00003449 // If our current best cursor is the construction of a temporary object,
3450 // don't replace that cursor with a type reference, because we want
3451 // clang_getCursor() to point at the constructor.
3452 if (clang_isExpression(BestCursor->kind) &&
3453 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3454 cursor.kind == CXCursor_TypeRef)
3455 return CXChildVisit_Recurse;
3456
Douglas Gregor85fe1562010-12-10 07:23:11 +00003457 // Don't override a preprocessing cursor with another preprocessing
3458 // cursor; we want the outermost preprocessing cursor.
3459 if (clang_isPreprocessing(cursor.kind) &&
3460 clang_isPreprocessing(BestCursor->kind))
3461 return CXChildVisit_Recurse;
3462
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003463 *BestCursor = cursor;
3464 return CXChildVisit_Recurse;
3465}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003466
Douglas Gregorb9790342010-01-22 21:44:22 +00003467CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3468 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003469 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003470
Ted Kremeneka60ed472010-11-16 08:15:36 +00003471 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003472 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3473
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003474 // Translate the given source location to make it point at the beginning of
3475 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003476 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003477
3478 // Guard against an invalid SourceLocation, or we may assert in one
3479 // of the following calls.
3480 if (SLoc.isInvalid())
3481 return clang_getNullCursor();
3482
Douglas Gregor40749ee2010-11-03 00:35:38 +00003483 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003484 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3485 CXXUnit->getASTContext().getLangOptions());
3486
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003487 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3488 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003489 // FIXME: Would be great to have a "hint" cursor, then walk from that
3490 // hint cursor upward until we find a cursor whose source range encloses
3491 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003492 GetCursorData ResultData(SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003493 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003494 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003495 Decl::MaxPCHLevel, true, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003496 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003497 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003498
3499 if (Logging) {
3500 CXFile SearchFile;
3501 unsigned SearchLine, SearchColumn;
3502 CXFile ResultFile;
3503 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003504 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3505 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003506 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3507
3508 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3509 0);
3510 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3511 &ResultColumn, 0);
3512 SearchFileName = clang_getFileName(SearchFile);
3513 ResultFileName = clang_getFileName(ResultFile);
3514 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003515 USR = clang_getCursorUSR(Result);
3516 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003517 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3518 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003519 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3520 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003521 clang_disposeString(SearchFileName);
3522 clang_disposeString(ResultFileName);
3523 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003524 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003525
3526 CXCursor Definition = clang_getCursorDefinition(Result);
3527 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3528 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3529 CXString DefinitionKindSpelling
3530 = clang_getCursorKindSpelling(Definition.kind);
3531 CXFile DefinitionFile;
3532 unsigned DefinitionLine, DefinitionColumn;
3533 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3534 &DefinitionLine, &DefinitionColumn, 0);
3535 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3536 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3537 clang_getCString(DefinitionKindSpelling),
3538 clang_getCString(DefinitionFileName),
3539 DefinitionLine, DefinitionColumn);
3540 clang_disposeString(DefinitionFileName);
3541 clang_disposeString(DefinitionKindSpelling);
3542 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003543 }
3544
Ted Kremeneke68fff62010-02-17 00:41:32 +00003545 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003546}
3547
Ted Kremenek73885552009-11-17 19:28:59 +00003548CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003549 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003550}
3551
3552unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003553 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003554}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003555
Douglas Gregor9ce55842010-11-20 00:09:34 +00003556unsigned clang_hashCursor(CXCursor C) {
3557 unsigned Index = 0;
3558 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3559 Index = 1;
3560
3561 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3562 std::make_pair(C.kind, C.data[Index]));
3563}
3564
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003565unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003566 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3567}
3568
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003569unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003570 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3571}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003572
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003573unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003574 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3575}
3576
Douglas Gregor97b98722010-01-19 23:20:36 +00003577unsigned clang_isExpression(enum CXCursorKind K) {
3578 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3579}
3580
3581unsigned clang_isStatement(enum CXCursorKind K) {
3582 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3583}
3584
Douglas Gregor8be80e12011-07-06 03:00:34 +00003585unsigned clang_isAttribute(enum CXCursorKind K) {
3586 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3587}
3588
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003589unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3590 return K == CXCursor_TranslationUnit;
3591}
3592
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003593unsigned clang_isPreprocessing(enum CXCursorKind K) {
3594 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3595}
3596
Ted Kremenekad6eff62010-03-08 21:17:29 +00003597unsigned clang_isUnexposed(enum CXCursorKind K) {
3598 switch (K) {
3599 case CXCursor_UnexposedDecl:
3600 case CXCursor_UnexposedExpr:
3601 case CXCursor_UnexposedStmt:
3602 case CXCursor_UnexposedAttr:
3603 return true;
3604 default:
3605 return false;
3606 }
3607}
3608
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003609CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003610 return C.kind;
3611}
3612
Douglas Gregor98258af2010-01-18 22:46:11 +00003613CXSourceLocation clang_getCursorLocation(CXCursor C) {
3614 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003615 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003616 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003617 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3618 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003619 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003620 }
3621
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003622 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003623 std::pair<ObjCProtocolDecl *, SourceLocation> P
3624 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003625 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003626 }
3627
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003628 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003629 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3630 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003631 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003632 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003633
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003634 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003635 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003636 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003637 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003638
3639 case CXCursor_TemplateRef: {
3640 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3641 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3642 }
3643
Douglas Gregor69319002010-08-31 23:48:11 +00003644 case CXCursor_NamespaceRef: {
3645 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3646 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3647 }
3648
Douglas Gregora67e03f2010-09-09 21:42:20 +00003649 case CXCursor_MemberRef: {
3650 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3651 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3652 }
3653
Ted Kremenek3064ef92010-08-27 21:34:58 +00003654 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003655 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3656 if (!BaseSpec)
3657 return clang_getNullLocation();
3658
3659 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3660 return cxloc::translateSourceLocation(getCursorContext(C),
3661 TSInfo->getTypeLoc().getBeginLoc());
3662
3663 return cxloc::translateSourceLocation(getCursorContext(C),
3664 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003665 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003666
Douglas Gregor36897b02010-09-10 00:22:18 +00003667 case CXCursor_LabelRef: {
3668 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3669 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3670 }
3671
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003672 case CXCursor_OverloadedDeclRef:
3673 return cxloc::translateSourceLocation(getCursorContext(C),
3674 getCursorOverloadedDeclRef(C).second);
3675
Douglas Gregorf46034a2010-01-18 23:41:10 +00003676 default:
3677 // FIXME: Need a way to enumerate all non-reference cases.
3678 llvm_unreachable("Missed a reference kind");
3679 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003680 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003681
3682 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003683 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003684 getLocationFromExpr(getCursorExpr(C)));
3685
Douglas Gregor36897b02010-09-10 00:22:18 +00003686 if (clang_isStatement(C.kind))
3687 return cxloc::translateSourceLocation(getCursorContext(C),
3688 getCursorStmt(C)->getLocStart());
3689
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003690 if (C.kind == CXCursor_PreprocessingDirective) {
3691 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3692 return cxloc::translateSourceLocation(getCursorContext(C), L);
3693 }
Douglas Gregor48072312010-03-18 15:23:44 +00003694
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003695 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003696 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003697 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003698 return cxloc::translateSourceLocation(getCursorContext(C), L);
3699 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003700
3701 if (C.kind == CXCursor_MacroDefinition) {
3702 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3703 return cxloc::translateSourceLocation(getCursorContext(C), L);
3704 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003705
3706 if (C.kind == CXCursor_InclusionDirective) {
3707 SourceLocation L
3708 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3709 return cxloc::translateSourceLocation(getCursorContext(C), L);
3710 }
3711
Ted Kremenek9a700d22010-05-12 06:16:13 +00003712 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003713 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003714
Douglas Gregorf46034a2010-01-18 23:41:10 +00003715 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003716 SourceLocation Loc = D->getLocation();
3717 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3718 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003719 // FIXME: Multiple variables declared in a single declaration
3720 // currently lack the information needed to correctly determine their
3721 // ranges when accounting for the type-specifier. We use context
3722 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3723 // and if so, whether it is the first decl.
3724 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3725 if (!cxcursor::isFirstInDeclGroup(C))
3726 Loc = VD->getLocation();
3727 }
3728
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003729 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003730}
Douglas Gregora7bde202010-01-19 00:34:46 +00003731
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003732} // end extern "C"
3733
3734static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003735 if (clang_isReference(C.kind)) {
3736 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003737 case CXCursor_ObjCSuperClassRef:
3738 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003739
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003740 case CXCursor_ObjCProtocolRef:
3741 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003742
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003743 case CXCursor_ObjCClassRef:
3744 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003745
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003746 case CXCursor_TypeRef:
3747 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003748
3749 case CXCursor_TemplateRef:
3750 return getCursorTemplateRef(C).second;
3751
Douglas Gregor69319002010-08-31 23:48:11 +00003752 case CXCursor_NamespaceRef:
3753 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003754
3755 case CXCursor_MemberRef:
3756 return getCursorMemberRef(C).second;
3757
Ted Kremenek3064ef92010-08-27 21:34:58 +00003758 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003759 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003760
Douglas Gregor36897b02010-09-10 00:22:18 +00003761 case CXCursor_LabelRef:
3762 return getCursorLabelRef(C).second;
3763
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003764 case CXCursor_OverloadedDeclRef:
3765 return getCursorOverloadedDeclRef(C).second;
3766
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003767 default:
3768 // FIXME: Need a way to enumerate all non-reference cases.
3769 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003770 }
3771 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003772
3773 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003774 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003775
3776 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003777 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003778
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003779 if (C.kind == CXCursor_PreprocessingDirective)
3780 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003781
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003782 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003783 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003784
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003785 if (C.kind == CXCursor_MacroDefinition)
3786 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003787
3788 if (C.kind == CXCursor_InclusionDirective)
3789 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3790
Ted Kremenek007a7c92010-11-01 23:26:51 +00003791 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3792 Decl *D = cxcursor::getCursorDecl(C);
3793 SourceRange R = D->getSourceRange();
3794 // FIXME: Multiple variables declared in a single declaration
3795 // currently lack the information needed to correctly determine their
3796 // ranges when accounting for the type-specifier. We use context
3797 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3798 // and if so, whether it is the first decl.
3799 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3800 if (!cxcursor::isFirstInDeclGroup(C))
3801 R.setBegin(VD->getLocation());
3802 }
3803 return R;
3804 }
Douglas Gregor66537982010-11-17 17:14:07 +00003805 return SourceRange();
3806}
3807
3808/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3809/// the decl-specifier-seq for declarations.
3810static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3811 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3812 Decl *D = cxcursor::getCursorDecl(C);
3813 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003814
Douglas Gregor2494dd02011-03-01 01:34:45 +00003815 // Adjust the start of the location for declarations preceded by
3816 // declaration specifiers.
3817 SourceLocation StartLoc;
3818 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3819 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3820 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3821 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3822 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3823 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3824 }
3825
3826 if (StartLoc.isValid() && R.getBegin().isValid() &&
3827 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3828 R.setBegin(StartLoc);
3829
3830 // FIXME: Multiple variables declared in a single declaration
3831 // currently lack the information needed to correctly determine their
3832 // ranges when accounting for the type-specifier. We use context
3833 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3834 // and if so, whether it is the first decl.
3835 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3836 if (!cxcursor::isFirstInDeclGroup(C))
3837 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003838 }
3839
3840 return R;
3841 }
3842
3843 return getRawCursorExtent(C);
3844}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003845
3846extern "C" {
3847
3848CXSourceRange clang_getCursorExtent(CXCursor C) {
3849 SourceRange R = getRawCursorExtent(C);
3850 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003851 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003852
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003853 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003854}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003855
3856CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003857 if (clang_isInvalid(C.kind))
3858 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Ted Kremeneka60ed472010-11-16 08:15:36 +00003860 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003861 if (clang_isDeclaration(C.kind)) {
3862 Decl *D = getCursorDecl(C);
3863 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003864 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003865 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003866 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003867 if (ObjCForwardProtocolDecl *Protocols
3868 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003869 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003870 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003871 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3872 return MakeCXCursor(Property, tu);
3873
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003874 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003875 }
3876
Douglas Gregor97b98722010-01-19 23:20:36 +00003877 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003878 Expr *E = getCursorExpr(C);
3879 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003880 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003881 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003882
3883 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003884 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003885
Douglas Gregor97b98722010-01-19 23:20:36 +00003886 return clang_getNullCursor();
3887 }
3888
Douglas Gregor36897b02010-09-10 00:22:18 +00003889 if (clang_isStatement(C.kind)) {
3890 Stmt *S = getCursorStmt(C);
3891 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003892 if (LabelDecl *label = Goto->getLabel())
3893 if (LabelStmt *labelS = label->getStmt())
3894 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003895
3896 return clang_getNullCursor();
3897 }
3898
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003899 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003900 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003901 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003902 }
3903
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003904 if (!clang_isReference(C.kind))
3905 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003906
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003907 switch (C.kind) {
3908 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003909 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003910
3911 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003912 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003913
3914 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003915 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003916
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003917 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003918 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003919
3920 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003921 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003922
Douglas Gregor69319002010-08-31 23:48:11 +00003923 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003924 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003925
Douglas Gregora67e03f2010-09-09 21:42:20 +00003926 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003927 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003928
Ted Kremenek3064ef92010-08-27 21:34:58 +00003929 case CXCursor_CXXBaseSpecifier: {
3930 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3931 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003932 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003933 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003934
Douglas Gregor36897b02010-09-10 00:22:18 +00003935 case CXCursor_LabelRef:
3936 // FIXME: We end up faking the "parent" declaration here because we
3937 // don't want to make CXCursor larger.
3938 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003939 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3940 .getTranslationUnitDecl(),
3941 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003942
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003943 case CXCursor_OverloadedDeclRef:
3944 return C;
3945
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003946 default:
3947 // We would prefer to enumerate all non-reference cursor kinds here.
3948 llvm_unreachable("Unhandled reference cursor kind");
3949 break;
3950 }
3951 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003952
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003953 return clang_getNullCursor();
3954}
3955
Douglas Gregorb6998662010-01-19 19:34:47 +00003956CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003957 if (clang_isInvalid(C.kind))
3958 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003959
Ted Kremeneka60ed472010-11-16 08:15:36 +00003960 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003961
Douglas Gregorb6998662010-01-19 19:34:47 +00003962 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003963 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003964 C = clang_getCursorReferenced(C);
3965 WasReference = true;
3966 }
3967
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003968 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003969 return clang_getCursorReferenced(C);
3970
Douglas Gregorb6998662010-01-19 19:34:47 +00003971 if (!clang_isDeclaration(C.kind))
3972 return clang_getNullCursor();
3973
3974 Decl *D = getCursorDecl(C);
3975 if (!D)
3976 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003977
Douglas Gregorb6998662010-01-19 19:34:47 +00003978 switch (D->getKind()) {
3979 // Declaration kinds that don't really separate the notions of
3980 // declaration and definition.
3981 case Decl::Namespace:
3982 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003983 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003984 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003985 case Decl::TemplateTypeParm:
3986 case Decl::EnumConstant:
3987 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003988 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003989 case Decl::ObjCIvar:
3990 case Decl::ObjCAtDefsField:
3991 case Decl::ImplicitParam:
3992 case Decl::ParmVar:
3993 case Decl::NonTypeTemplateParm:
3994 case Decl::TemplateTemplateParm:
3995 case Decl::ObjCCategoryImpl:
3996 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003997 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003998 case Decl::LinkageSpec:
3999 case Decl::ObjCPropertyImpl:
4000 case Decl::FileScopeAsm:
4001 case Decl::StaticAssert:
4002 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004003 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00004004 return C;
4005
4006 // Declaration kinds that don't make any sense here, but are
4007 // nonetheless harmless.
4008 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004009 break;
4010
4011 // Declaration kinds for which the definition is not resolvable.
4012 case Decl::UnresolvedUsingTypename:
4013 case Decl::UnresolvedUsingValue:
4014 break;
4015
4016 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004017 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004018 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004019
4020 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004021 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004022
4023 case Decl::Enum:
4024 case Decl::Record:
4025 case Decl::CXXRecord:
4026 case Decl::ClassTemplateSpecialization:
4027 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004028 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004029 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004030 return clang_getNullCursor();
4031
4032 case Decl::Function:
4033 case Decl::CXXMethod:
4034 case Decl::CXXConstructor:
4035 case Decl::CXXDestructor:
4036 case Decl::CXXConversion: {
4037 const FunctionDecl *Def = 0;
4038 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004039 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004040 return clang_getNullCursor();
4041 }
4042
4043 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004044 // Ask the variable if it has a definition.
4045 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004046 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004047 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004048 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004049
Douglas Gregorb6998662010-01-19 19:34:47 +00004050 case Decl::FunctionTemplate: {
4051 const FunctionDecl *Def = 0;
4052 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004053 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004054 return clang_getNullCursor();
4055 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004056
Douglas Gregorb6998662010-01-19 19:34:47 +00004057 case Decl::ClassTemplate: {
4058 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004059 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004060 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004061 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004062 return clang_getNullCursor();
4063 }
4064
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004065 case Decl::Using:
4066 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004067 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004068
4069 case Decl::UsingShadow:
4070 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004071 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004072 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004073
4074 case Decl::ObjCMethod: {
4075 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4076 if (Method->isThisDeclarationADefinition())
4077 return C;
4078
4079 // Dig out the method definition in the associated
4080 // @implementation, if we have it.
4081 // FIXME: The ASTs should make finding the definition easier.
4082 if (ObjCInterfaceDecl *Class
4083 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4084 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4085 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4086 Method->isInstanceMethod()))
4087 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004088 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004089
4090 return clang_getNullCursor();
4091 }
4092
4093 case Decl::ObjCCategory:
4094 if (ObjCCategoryImplDecl *Impl
4095 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004096 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004097 return clang_getNullCursor();
4098
4099 case Decl::ObjCProtocol:
4100 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4101 return C;
4102 return clang_getNullCursor();
4103
4104 case Decl::ObjCInterface:
4105 // There are two notions of a "definition" for an Objective-C
4106 // class: the interface and its implementation. When we resolved a
4107 // reference to an Objective-C class, produce the @interface as
4108 // the definition; when we were provided with the interface,
4109 // produce the @implementation as the definition.
4110 if (WasReference) {
4111 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4112 return C;
4113 } else if (ObjCImplementationDecl *Impl
4114 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004115 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004116 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004117
Douglas Gregorb6998662010-01-19 19:34:47 +00004118 case Decl::ObjCProperty:
4119 // FIXME: We don't really know where to find the
4120 // ObjCPropertyImplDecls that implement this property.
4121 return clang_getNullCursor();
4122
4123 case Decl::ObjCCompatibleAlias:
4124 if (ObjCInterfaceDecl *Class
4125 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4126 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004127 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004128
Douglas Gregorb6998662010-01-19 19:34:47 +00004129 return clang_getNullCursor();
4130
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004131 case Decl::ObjCForwardProtocol:
4132 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004133 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004134
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004135 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004136 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004137 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004138
4139 case Decl::Friend:
4140 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004141 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004142 return clang_getNullCursor();
4143
4144 case Decl::FriendTemplate:
4145 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004146 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004147 return clang_getNullCursor();
4148 }
4149
4150 return clang_getNullCursor();
4151}
4152
4153unsigned clang_isCursorDefinition(CXCursor C) {
4154 if (!clang_isDeclaration(C.kind))
4155 return 0;
4156
4157 return clang_getCursorDefinition(C) == C;
4158}
4159
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004160CXCursor clang_getCanonicalCursor(CXCursor C) {
4161 if (!clang_isDeclaration(C.kind))
4162 return C;
4163
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004164 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004165 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4166 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4167 return MakeCXCursor(CatD, getCursorTU(C));
4168
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004169 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4170 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4171 return MakeCXCursor(IFD, getCursorTU(C));
4172
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004173 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004174 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004175
4176 return C;
4177}
4178
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004179unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004180 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004181 return 0;
4182
4183 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4184 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4185 return E->getNumDecls();
4186
4187 if (OverloadedTemplateStorage *S
4188 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4189 return S->size();
4190
4191 Decl *D = Storage.get<Decl*>();
4192 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004193 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004194 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4195 return Classes->size();
4196 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4197 return Protocols->protocol_size();
4198
4199 return 0;
4200}
4201
4202CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004203 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004204 return clang_getNullCursor();
4205
4206 if (index >= clang_getNumOverloadedDecls(cursor))
4207 return clang_getNullCursor();
4208
Ted Kremeneka60ed472010-11-16 08:15:36 +00004209 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004210 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4211 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004212 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004213
4214 if (OverloadedTemplateStorage *S
4215 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004216 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004217
4218 Decl *D = Storage.get<Decl*>();
4219 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4220 // FIXME: This is, unfortunately, linear time.
4221 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4222 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004223 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004224 }
4225
4226 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004227 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004228
4229 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004230 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004231
4232 return clang_getNullCursor();
4233}
4234
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004235void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004236 const char **startBuf,
4237 const char **endBuf,
4238 unsigned *startLine,
4239 unsigned *startColumn,
4240 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004241 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004242 assert(getCursorDecl(C) && "CXCursor has null decl");
4243 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004244 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4245 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004246
Steve Naroff4ade6d62009-09-23 17:52:52 +00004247 SourceManager &SM = FD->getASTContext().getSourceManager();
4248 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4249 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4250 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4251 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4252 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4253 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4254}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004255
Douglas Gregor430d7a12011-07-25 17:48:11 +00004256namespace {
4257typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
4258RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
4259 const DeclarationNameInfo &NI,
4260 const SourceRange &QLoc,
4261 const ExplicitTemplateArgumentList *TemplateArgs = 0){
4262 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
4263 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
4264 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
4265
4266 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
4267
4268 RefNamePieces Pieces;
4269
4270 if (WantQualifier && QLoc.isValid())
4271 Pieces.push_back(QLoc);
4272
4273 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
4274 Pieces.push_back(NI.getLoc());
4275
4276 if (WantTemplateArgs && TemplateArgs)
4277 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
4278 TemplateArgs->RAngleLoc));
4279
4280 if (Kind == DeclarationName::CXXOperatorName) {
4281 Pieces.push_back(SourceLocation::getFromRawEncoding(
4282 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
4283 Pieces.push_back(SourceLocation::getFromRawEncoding(
4284 NI.getInfo().CXXOperatorName.EndOpNameLoc));
4285 }
4286
4287 if (WantSinglePiece) {
4288 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
4289 Pieces.clear();
4290 Pieces.push_back(R);
4291 }
4292
4293 return Pieces;
4294}
4295}
4296
4297CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4298 unsigned PieceIndex) {
4299 RefNamePieces Pieces;
4300
4301 switch (C.kind) {
4302 case CXCursor_MemberRefExpr:
4303 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4304 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4305 E->getQualifierLoc().getSourceRange());
4306 break;
4307
4308 case CXCursor_DeclRefExpr:
4309 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4310 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4311 E->getQualifierLoc().getSourceRange(),
4312 E->getExplicitTemplateArgsOpt());
4313 break;
4314
4315 case CXCursor_CallExpr:
4316 if (CXXOperatorCallExpr *OCE =
4317 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4318 Expr *Callee = OCE->getCallee();
4319 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4320 Callee = ICE->getSubExpr();
4321
4322 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4323 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4324 DRE->getQualifierLoc().getSourceRange());
4325 }
4326 break;
4327
4328 default:
4329 break;
4330 }
4331
4332 if (Pieces.empty()) {
4333 if (PieceIndex == 0)
4334 return clang_getCursorExtent(C);
4335 } else if (PieceIndex < Pieces.size()) {
4336 SourceRange R = Pieces[PieceIndex];
4337 if (R.isValid())
4338 return cxloc::translateSourceRange(getCursorContext(C), R);
4339 }
4340
4341 return clang_getNullRange();
4342}
4343
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004344void clang_enableStackTraces(void) {
4345 llvm::sys::PrintStackTraceOnErrorSignal();
4346}
4347
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004348void clang_executeOnThread(void (*fn)(void*), void *user_data,
4349 unsigned stack_size) {
4350 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4351}
4352
Ted Kremenekfb480492010-01-13 21:46:36 +00004353} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004354
Ted Kremenekfb480492010-01-13 21:46:36 +00004355//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004356// Token-based Operations.
4357//===----------------------------------------------------------------------===//
4358
4359/* CXToken layout:
4360 * int_data[0]: a CXTokenKind
4361 * int_data[1]: starting token location
4362 * int_data[2]: token length
4363 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004364 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004365 * otherwise unused.
4366 */
4367extern "C" {
4368
4369CXTokenKind clang_getTokenKind(CXToken CXTok) {
4370 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4371}
4372
4373CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4374 switch (clang_getTokenKind(CXTok)) {
4375 case CXToken_Identifier:
4376 case CXToken_Keyword:
4377 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004378 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4379 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004380
4381 case CXToken_Literal: {
4382 // We have stashed the starting pointer in the ptr_data field. Use it.
4383 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004384 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004385 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004386
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004387 case CXToken_Punctuation:
4388 case CXToken_Comment:
4389 break;
4390 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004391
4392 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004393 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004394 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004395 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004396 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004397
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004398 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4399 std::pair<FileID, unsigned> LocInfo
4400 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004401 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004402 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004403 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4404 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004405 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004406
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004407 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004408}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004409
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004410CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004411 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004412 if (!CXXUnit)
4413 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004414
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004415 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4416 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4417}
4418
4419CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004420 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004421 if (!CXXUnit)
4422 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004423
4424 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004425 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4426}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004427
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004428void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4429 CXToken **Tokens, unsigned *NumTokens) {
4430 if (Tokens)
4431 *Tokens = 0;
4432 if (NumTokens)
4433 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004434
Ted Kremeneka60ed472010-11-16 08:15:36 +00004435 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004436 if (!CXXUnit || !Tokens || !NumTokens)
4437 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004438
Douglas Gregorbdf60622010-03-05 21:16:25 +00004439 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4440
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004441 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004442 if (R.isInvalid())
4443 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004444
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004445 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4446 std::pair<FileID, unsigned> BeginLocInfo
4447 = SourceMgr.getDecomposedLoc(R.getBegin());
4448 std::pair<FileID, unsigned> EndLocInfo
4449 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004450
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004451 // Cannot tokenize across files.
4452 if (BeginLocInfo.first != EndLocInfo.first)
4453 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004454
4455 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004456 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004457 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004458 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004459 if (Invalid)
4460 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004461
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004462 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4463 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004464 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004465 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004466
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004467 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004468 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004469 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004470 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004471 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004472 do {
4473 // Lex the next token
4474 Lex.LexFromRawLexer(Tok);
4475 if (Tok.is(tok::eof))
4476 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004477
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004478 // Initialize the CXToken.
4479 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004480
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004481 // - Common fields
4482 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4483 CXTok.int_data[2] = Tok.getLength();
4484 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004485
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004486 // - Kind-specific fields
4487 if (Tok.isLiteral()) {
4488 CXTok.int_data[0] = CXToken_Literal;
4489 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004490 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004491 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004492 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004493 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004494
David Chisnall096428b2010-10-13 21:44:48 +00004495 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004496 CXTok.int_data[0] = CXToken_Keyword;
4497 }
4498 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004499 CXTok.int_data[0] = Tok.is(tok::identifier)
4500 ? CXToken_Identifier
4501 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004502 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004503 CXTok.ptr_data = II;
4504 } else if (Tok.is(tok::comment)) {
4505 CXTok.int_data[0] = CXToken_Comment;
4506 CXTok.ptr_data = 0;
4507 } else {
4508 CXTok.int_data[0] = CXToken_Punctuation;
4509 CXTok.ptr_data = 0;
4510 }
4511 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004512 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004513 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004514
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004515 if (CXTokens.empty())
4516 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004517
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004518 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4519 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4520 *NumTokens = CXTokens.size();
4521}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004522
Ted Kremenek6db61092010-05-05 00:55:15 +00004523void clang_disposeTokens(CXTranslationUnit TU,
4524 CXToken *Tokens, unsigned NumTokens) {
4525 free(Tokens);
4526}
4527
4528} // end: extern "C"
4529
4530//===----------------------------------------------------------------------===//
4531// Token annotation APIs.
4532//===----------------------------------------------------------------------===//
4533
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004534typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004535static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4536 CXCursor parent,
4537 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004538namespace {
4539class AnnotateTokensWorker {
4540 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004541 CXToken *Tokens;
4542 CXCursor *Cursors;
4543 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004544 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004545 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004546 CursorVisitor AnnotateVis;
4547 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004548 bool HasContextSensitiveKeywords;
4549
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004550 bool MoreTokens() const { return TokIdx < NumTokens; }
4551 unsigned NextToken() const { return TokIdx; }
4552 void AdvanceToken() { ++TokIdx; }
4553 SourceLocation GetTokenLoc(unsigned tokI) {
4554 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4555 }
4556
Ted Kremenek6db61092010-05-05 00:55:15 +00004557public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004558 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004559 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004560 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004561 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004562 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004563 AnnotateVis(tu,
4564 AnnotateTokensVisitor, this,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00004565 Decl::MaxPCHLevel, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004566 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4567 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004568
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004569 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004570 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004571 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004572 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004573 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004574 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004575
4576 /// \brief Determine whether the annotator saw any cursors that have
4577 /// context-sensitive keywords.
4578 bool hasContextSensitiveKeywords() const {
4579 return HasContextSensitiveKeywords;
4580 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004581};
4582}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004583
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004584void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4585 // Walk the AST within the region of interest, annotating tokens
4586 // along the way.
4587 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004588
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004589 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4590 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004591 if (Pos != Annotated.end() &&
4592 (clang_isInvalid(Cursors[I].kind) ||
4593 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004594 Cursors[I] = Pos->second;
4595 }
4596
4597 // Finish up annotating any tokens left.
4598 if (!MoreTokens())
4599 return;
4600
4601 const CXCursor &C = clang_getNullCursor();
4602 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4603 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4604 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004605 }
4606}
4607
Ted Kremenek6db61092010-05-05 00:55:15 +00004608enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004609AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004610 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004611 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004612 if (cursorRange.isInvalid())
4613 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004614
4615 if (!HasContextSensitiveKeywords) {
4616 // Objective-C properties can have context-sensitive keywords.
4617 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4618 if (ObjCPropertyDecl *Property
4619 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4620 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4621 }
4622 // Objective-C methods can have context-sensitive keywords.
4623 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4624 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4625 if (ObjCMethodDecl *Method
4626 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4627 if (Method->getObjCDeclQualifier())
4628 HasContextSensitiveKeywords = true;
4629 else {
4630 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4631 PEnd = Method->param_end();
4632 P != PEnd; ++P) {
4633 if ((*P)->getObjCDeclQualifier()) {
4634 HasContextSensitiveKeywords = true;
4635 break;
4636 }
4637 }
4638 }
4639 }
4640 }
4641 // C++ methods can have context-sensitive keywords.
4642 else if (cursor.kind == CXCursor_CXXMethod) {
4643 if (CXXMethodDecl *Method
4644 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4645 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4646 HasContextSensitiveKeywords = true;
4647 }
4648 }
4649 // C++ classes can have context-sensitive keywords.
4650 else if (cursor.kind == CXCursor_StructDecl ||
4651 cursor.kind == CXCursor_ClassDecl ||
4652 cursor.kind == CXCursor_ClassTemplate ||
4653 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4654 if (Decl *D = getCursorDecl(cursor))
4655 if (D->hasAttr<FinalAttr>())
4656 HasContextSensitiveKeywords = true;
4657 }
4658 }
4659
Douglas Gregor4419b672010-10-21 06:10:04 +00004660 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004661 // For macro expansions, just note where the beginning of the macro
4662 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004663 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004664 Annotated[Loc.int_data] = cursor;
4665 return CXChildVisit_Recurse;
4666 }
4667
Douglas Gregor4419b672010-10-21 06:10:04 +00004668 // Items in the preprocessing record are kept separate from items in
4669 // declarations, so we keep a separate token index.
4670 unsigned SavedTokIdx = TokIdx;
4671 TokIdx = PreprocessingTokIdx;
4672
4673 // Skip tokens up until we catch up to the beginning of the preprocessing
4674 // entry.
4675 while (MoreTokens()) {
4676 const unsigned I = NextToken();
4677 SourceLocation TokLoc = GetTokenLoc(I);
4678 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4679 case RangeBefore:
4680 AdvanceToken();
4681 continue;
4682 case RangeAfter:
4683 case RangeOverlap:
4684 break;
4685 }
4686 break;
4687 }
4688
4689 // Look at all of the tokens within this range.
4690 while (MoreTokens()) {
4691 const unsigned I = NextToken();
4692 SourceLocation TokLoc = GetTokenLoc(I);
4693 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4694 case RangeBefore:
4695 assert(0 && "Infeasible");
4696 case RangeAfter:
4697 break;
4698 case RangeOverlap:
4699 Cursors[I] = cursor;
4700 AdvanceToken();
4701 continue;
4702 }
4703 break;
4704 }
4705
4706 // Save the preprocessing token index; restore the non-preprocessing
4707 // token index.
4708 PreprocessingTokIdx = TokIdx;
4709 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004710 return CXChildVisit_Recurse;
4711 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004712
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004713 if (cursorRange.isInvalid())
4714 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004715
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004716 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4717
Ted Kremeneka333c662010-05-12 05:29:33 +00004718 // Adjust the annotated range based specific declarations.
4719 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4720 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004721 Decl *D = cxcursor::getCursorDecl(cursor);
4722 // Don't visit synthesized ObjC methods, since they have no syntatic
4723 // representation in the source.
4724 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4725 if (MD->isSynthesized())
4726 return CXChildVisit_Continue;
4727 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004728
4729 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004730 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004731 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4732 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4733 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4734 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4735 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004736 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004737
4738 if (StartLoc.isValid() && L.isValid() &&
4739 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4740 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004741 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004742
Ted Kremenek3f404602010-08-14 01:14:06 +00004743 // If the location of the cursor occurs within a macro instantiation, record
4744 // the spelling location of the cursor in our annotation map. We can then
4745 // paper over the token labelings during a post-processing step to try and
4746 // get cursor mappings for tokens that are the *arguments* of a macro
4747 // instantiation.
4748 if (L.isMacroID()) {
4749 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4750 // Only invalidate the old annotation if it isn't part of a preprocessing
4751 // directive. Here we assume that the default construction of CXCursor
4752 // results in CXCursor.kind being an initialized value (i.e., 0). If
4753 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004754
Ted Kremenek3f404602010-08-14 01:14:06 +00004755 CXCursor &oldC = Annotated[rawEncoding];
4756 if (!clang_isPreprocessing(oldC.kind))
4757 oldC = cursor;
4758 }
4759
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004760 const enum CXCursorKind K = clang_getCursorKind(parent);
4761 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004762 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4763 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004764
4765 while (MoreTokens()) {
4766 const unsigned I = NextToken();
4767 SourceLocation TokLoc = GetTokenLoc(I);
4768 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4769 case RangeBefore:
4770 Cursors[I] = updateC;
4771 AdvanceToken();
4772 continue;
4773 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004774 case RangeOverlap:
4775 break;
4776 }
4777 break;
4778 }
4779
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004780 // Avoid having the cursor of an expression "overwrite" the annotation of the
4781 // variable declaration that it belongs to.
4782 // This can happen for C++ constructor expressions whose range generally
4783 // include the variable declaration, e.g.:
4784 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4785 if (clang_isExpression(cursorK)) {
4786 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004787 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004788 const unsigned I = NextToken();
4789 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4790 E->getLocStart() == D->getLocation() &&
4791 E->getLocStart() == GetTokenLoc(I)) {
4792 Cursors[I] = updateC;
4793 AdvanceToken();
4794 }
4795 }
4796 }
4797
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004798 // Visit children to get their cursor information.
4799 const unsigned BeforeChildren = NextToken();
4800 VisitChildren(cursor);
4801 const unsigned AfterChildren = NextToken();
4802
4803 // Adjust 'Last' to the last token within the extent of the cursor.
4804 while (MoreTokens()) {
4805 const unsigned I = NextToken();
4806 SourceLocation TokLoc = GetTokenLoc(I);
4807 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4808 case RangeBefore:
4809 assert(0 && "Infeasible");
4810 case RangeAfter:
4811 break;
4812 case RangeOverlap:
4813 Cursors[I] = updateC;
4814 AdvanceToken();
4815 continue;
4816 }
4817 break;
4818 }
4819 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004820
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004821 // Scan the tokens that are at the beginning of the cursor, but are not
4822 // capture by the child cursors.
4823
4824 // For AST elements within macros, rely on a post-annotate pass to
4825 // to correctly annotate the tokens with cursors. Otherwise we can
4826 // get confusing results of having tokens that map to cursors that really
4827 // are expanded by an instantiation.
4828 if (L.isMacroID())
4829 cursor = clang_getNullCursor();
4830
4831 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4832 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4833 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004834
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004835 Cursors[I] = cursor;
4836 }
4837 // Scan the tokens that are at the end of the cursor, but are not captured
4838 // but the child cursors.
4839 for (unsigned I = AfterChildren; I != Last; ++I)
4840 Cursors[I] = cursor;
4841
4842 TokIdx = Last;
4843 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004844}
4845
Ted Kremenek6db61092010-05-05 00:55:15 +00004846static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4847 CXCursor parent,
4848 CXClientData client_data) {
4849 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4850}
4851
Ted Kremenek6628a612011-03-18 22:51:30 +00004852namespace {
4853 struct clang_annotateTokens_Data {
4854 CXTranslationUnit TU;
4855 ASTUnit *CXXUnit;
4856 CXToken *Tokens;
4857 unsigned NumTokens;
4858 CXCursor *Cursors;
4859 };
4860}
4861
Ted Kremenekab979612010-11-11 08:05:23 +00004862// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004863static void clang_annotateTokensImpl(void *UserData) {
4864 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4865 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4866 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4867 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4868 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4869
4870 // Determine the region of interest, which contains all of the tokens.
4871 SourceRange RegionOfInterest;
4872 RegionOfInterest.setBegin(
4873 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4874 RegionOfInterest.setEnd(
4875 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4876 Tokens[NumTokens-1])));
4877
4878 // A mapping from the source locations found when re-lexing or traversing the
4879 // region of interest to the corresponding cursors.
4880 AnnotateTokensData Annotated;
4881
4882 // Relex the tokens within the source range to look for preprocessing
4883 // directives.
4884 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4885 std::pair<FileID, unsigned> BeginLocInfo
4886 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4887 std::pair<FileID, unsigned> EndLocInfo
4888 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4889
Chris Lattner5f9e2722011-07-23 10:55:15 +00004890 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00004891 bool Invalid = false;
4892 if (BeginLocInfo.first == EndLocInfo.first &&
4893 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4894 !Invalid) {
4895 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4896 CXXUnit->getASTContext().getLangOptions(),
4897 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4898 Buffer.end());
4899 Lex.SetCommentRetentionState(true);
4900
4901 // Lex tokens in raw mode until we hit the end of the range, to avoid
4902 // entering #includes or expanding macros.
4903 while (true) {
4904 Token Tok;
4905 Lex.LexFromRawLexer(Tok);
4906
4907 reprocess:
4908 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4909 // We have found a preprocessing directive. Gobble it up so that we
4910 // don't see it while preprocessing these tokens later, but keep track
4911 // of all of the token locations inside this preprocessing directive so
4912 // that we can annotate them appropriately.
4913 //
4914 // FIXME: Some simple tests here could identify macro definitions and
4915 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004916 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00004917 do {
4918 Locations.push_back(Tok.getLocation());
4919 Lex.LexFromRawLexer(Tok);
4920 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4921
4922 using namespace cxcursor;
4923 CXCursor Cursor
4924 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4925 Locations.back()),
4926 TU);
4927 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4928 Annotated[Locations[I].getRawEncoding()] = Cursor;
4929 }
4930
4931 if (Tok.isAtStartOfLine())
4932 goto reprocess;
4933
4934 continue;
4935 }
4936
4937 if (Tok.is(tok::eof))
4938 break;
4939 }
4940 }
4941
4942 // Annotate all of the source locations in the region of interest that map to
4943 // a specific cursor.
4944 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4945 TU, RegionOfInterest);
4946
4947 // FIXME: We use a ridiculous stack size here because the data-recursion
4948 // algorithm uses a large stack frame than the non-data recursive version,
4949 // and AnnotationTokensWorker currently transforms the data-recursion
4950 // algorithm back into a traditional recursion by explicitly calling
4951 // VisitChildren(). We will need to remove this explicit recursive call.
4952 W.AnnotateTokens();
4953
4954 // If we ran into any entities that involve context-sensitive keywords,
4955 // take another pass through the tokens to mark them as such.
4956 if (W.hasContextSensitiveKeywords()) {
4957 for (unsigned I = 0; I != NumTokens; ++I) {
4958 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4959 continue;
4960
4961 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4962 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4963 if (ObjCPropertyDecl *Property
4964 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4965 if (Property->getPropertyAttributesAsWritten() != 0 &&
4966 llvm::StringSwitch<bool>(II->getName())
4967 .Case("readonly", true)
4968 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00004969 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004970 .Case("readwrite", true)
4971 .Case("retain", true)
4972 .Case("copy", true)
4973 .Case("nonatomic", true)
4974 .Case("atomic", true)
4975 .Case("getter", true)
4976 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00004977 .Case("strong", true)
4978 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004979 .Default(false))
4980 Tokens[I].int_data[0] = CXToken_Keyword;
4981 }
4982 continue;
4983 }
4984
4985 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
4986 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
4987 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4988 if (llvm::StringSwitch<bool>(II->getName())
4989 .Case("in", true)
4990 .Case("out", true)
4991 .Case("inout", true)
4992 .Case("oneway", true)
4993 .Case("bycopy", true)
4994 .Case("byref", true)
4995 .Default(false))
4996 Tokens[I].int_data[0] = CXToken_Keyword;
4997 continue;
4998 }
4999
5000 if (Cursors[I].kind == CXCursor_CXXMethod) {
5001 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5002 if (CXXMethodDecl *Method
5003 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
5004 if ((Method->hasAttr<FinalAttr>() ||
5005 Method->hasAttr<OverrideAttr>()) &&
5006 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
5007 llvm::StringSwitch<bool>(II->getName())
5008 .Case("final", true)
5009 .Case("override", true)
5010 .Default(false))
5011 Tokens[I].int_data[0] = CXToken_Keyword;
5012 }
5013 continue;
5014 }
5015
5016 if (Cursors[I].kind == CXCursor_ClassDecl ||
5017 Cursors[I].kind == CXCursor_StructDecl ||
5018 Cursors[I].kind == CXCursor_ClassTemplate) {
5019 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5020 if (II->getName() == "final") {
5021 // We have to be careful with 'final', since it could be the name
5022 // of a member class rather than the context-sensitive keyword.
5023 // So, check whether the cursor associated with this
5024 Decl *D = getCursorDecl(Cursors[I]);
5025 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
5026 if ((Record->hasAttr<FinalAttr>()) &&
5027 Record->getIdentifier() != II)
5028 Tokens[I].int_data[0] = CXToken_Keyword;
5029 } else if (ClassTemplateDecl *ClassTemplate
5030 = dyn_cast_or_null<ClassTemplateDecl>(D)) {
5031 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
5032 if ((Record->hasAttr<FinalAttr>()) &&
5033 Record->getIdentifier() != II)
5034 Tokens[I].int_data[0] = CXToken_Keyword;
5035 }
5036 }
5037 continue;
5038 }
5039 }
5040 }
Ted Kremenekab979612010-11-11 08:05:23 +00005041}
5042
Ted Kremenek6db61092010-05-05 00:55:15 +00005043extern "C" {
5044
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005045void clang_annotateTokens(CXTranslationUnit TU,
5046 CXToken *Tokens, unsigned NumTokens,
5047 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005048
5049 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005050 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005051
Douglas Gregor4419b672010-10-21 06:10:04 +00005052 // Any token we don't specifically annotate will have a NULL cursor.
5053 CXCursor C = clang_getNullCursor();
5054 for (unsigned I = 0; I != NumTokens; ++I)
5055 Cursors[I] = C;
5056
Ted Kremeneka60ed472010-11-16 08:15:36 +00005057 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005058 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005059 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005060
Douglas Gregorbdf60622010-03-05 21:16:25 +00005061 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005062
5063 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005064 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005065 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005066 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005067 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5068 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005069}
Ted Kremenek6628a612011-03-18 22:51:30 +00005070
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005071} // end: extern "C"
5072
5073//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005074// Operations for querying linkage of a cursor.
5075//===----------------------------------------------------------------------===//
5076
5077extern "C" {
5078CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005079 if (!clang_isDeclaration(cursor.kind))
5080 return CXLinkage_Invalid;
5081
Ted Kremenek16b42592010-03-03 06:36:57 +00005082 Decl *D = cxcursor::getCursorDecl(cursor);
5083 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5084 switch (ND->getLinkage()) {
5085 case NoLinkage: return CXLinkage_NoLinkage;
5086 case InternalLinkage: return CXLinkage_Internal;
5087 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5088 case ExternalLinkage: return CXLinkage_External;
5089 };
5090
5091 return CXLinkage_Invalid;
5092}
5093} // end: extern "C"
5094
5095//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005096// Operations for querying language of a cursor.
5097//===----------------------------------------------------------------------===//
5098
5099static CXLanguageKind getDeclLanguage(const Decl *D) {
5100 switch (D->getKind()) {
5101 default:
5102 break;
5103 case Decl::ImplicitParam:
5104 case Decl::ObjCAtDefsField:
5105 case Decl::ObjCCategory:
5106 case Decl::ObjCCategoryImpl:
5107 case Decl::ObjCClass:
5108 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005109 case Decl::ObjCForwardProtocol:
5110 case Decl::ObjCImplementation:
5111 case Decl::ObjCInterface:
5112 case Decl::ObjCIvar:
5113 case Decl::ObjCMethod:
5114 case Decl::ObjCProperty:
5115 case Decl::ObjCPropertyImpl:
5116 case Decl::ObjCProtocol:
5117 return CXLanguage_ObjC;
5118 case Decl::CXXConstructor:
5119 case Decl::CXXConversion:
5120 case Decl::CXXDestructor:
5121 case Decl::CXXMethod:
5122 case Decl::CXXRecord:
5123 case Decl::ClassTemplate:
5124 case Decl::ClassTemplatePartialSpecialization:
5125 case Decl::ClassTemplateSpecialization:
5126 case Decl::Friend:
5127 case Decl::FriendTemplate:
5128 case Decl::FunctionTemplate:
5129 case Decl::LinkageSpec:
5130 case Decl::Namespace:
5131 case Decl::NamespaceAlias:
5132 case Decl::NonTypeTemplateParm:
5133 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005134 case Decl::TemplateTemplateParm:
5135 case Decl::TemplateTypeParm:
5136 case Decl::UnresolvedUsingTypename:
5137 case Decl::UnresolvedUsingValue:
5138 case Decl::Using:
5139 case Decl::UsingDirective:
5140 case Decl::UsingShadow:
5141 return CXLanguage_CPlusPlus;
5142 }
5143
5144 return CXLanguage_C;
5145}
5146
5147extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005148
5149enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5150 if (clang_isDeclaration(cursor.kind))
5151 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005152 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005153 return CXAvailability_Available;
5154
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005155 switch (D->getAvailability()) {
5156 case AR_Available:
5157 case AR_NotYetIntroduced:
5158 return CXAvailability_Available;
5159
5160 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005161 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005162
5163 case AR_Unavailable:
5164 return CXAvailability_NotAvailable;
5165 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005166 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005167
Douglas Gregor58ddb602010-08-23 23:00:57 +00005168 return CXAvailability_Available;
5169}
5170
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005171CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5172 if (clang_isDeclaration(cursor.kind))
5173 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5174
5175 return CXLanguage_Invalid;
5176}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005177
5178 /// \brief If the given cursor is the "templated" declaration
5179 /// descibing a class or function template, return the class or
5180 /// function template.
5181static Decl *maybeGetTemplateCursor(Decl *D) {
5182 if (!D)
5183 return 0;
5184
5185 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5186 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5187 return FunTmpl;
5188
5189 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5190 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5191 return ClassTmpl;
5192
5193 return D;
5194}
5195
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005196CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5197 if (clang_isDeclaration(cursor.kind)) {
5198 if (Decl *D = getCursorDecl(cursor)) {
5199 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005200 if (!DC)
5201 return clang_getNullCursor();
5202
5203 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5204 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005205 }
5206 }
5207
5208 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5209 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005210 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005211 }
5212
5213 return clang_getNullCursor();
5214}
5215
5216CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5217 if (clang_isDeclaration(cursor.kind)) {
5218 if (Decl *D = getCursorDecl(cursor)) {
5219 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005220 if (!DC)
5221 return clang_getNullCursor();
5222
5223 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5224 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005225 }
5226 }
5227
5228 // FIXME: Note that we can't easily compute the lexical context of a
5229 // statement or expression, so we return nothing.
5230 return clang_getNullCursor();
5231}
5232
Douglas Gregor9f592342010-10-01 20:25:15 +00005233static void CollectOverriddenMethods(DeclContext *Ctx,
5234 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005235 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005236 if (!Ctx)
5237 return;
5238
5239 // If we have a class or category implementation, jump straight to the
5240 // interface.
5241 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5242 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5243
5244 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5245 if (!Container)
5246 return;
5247
5248 // Check whether we have a matching method at this level.
5249 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5250 Method->isInstanceMethod()))
5251 if (Method != Overridden) {
5252 // We found an override at this level; there is no need to look
5253 // into other protocols or categories.
5254 Methods.push_back(Overridden);
5255 return;
5256 }
5257
5258 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5259 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5260 PEnd = Protocol->protocol_end();
5261 P != PEnd; ++P)
5262 CollectOverriddenMethods(*P, Method, Methods);
5263 }
5264
5265 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5266 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5267 PEnd = Category->protocol_end();
5268 P != PEnd; ++P)
5269 CollectOverriddenMethods(*P, Method, Methods);
5270 }
5271
5272 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5273 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5274 PEnd = Interface->protocol_end();
5275 P != PEnd; ++P)
5276 CollectOverriddenMethods(*P, Method, Methods);
5277
5278 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5279 Category; Category = Category->getNextClassCategory())
5280 CollectOverriddenMethods(Category, Method, Methods);
5281
5282 // We only look into the superclass if we haven't found anything yet.
5283 if (Methods.empty())
5284 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5285 return CollectOverriddenMethods(Super, Method, Methods);
5286 }
5287}
5288
5289void clang_getOverriddenCursors(CXCursor cursor,
5290 CXCursor **overridden,
5291 unsigned *num_overridden) {
5292 if (overridden)
5293 *overridden = 0;
5294 if (num_overridden)
5295 *num_overridden = 0;
5296 if (!overridden || !num_overridden)
5297 return;
5298
5299 if (!clang_isDeclaration(cursor.kind))
5300 return;
5301
5302 Decl *D = getCursorDecl(cursor);
5303 if (!D)
5304 return;
5305
5306 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005307 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005308 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5309 *num_overridden = CXXMethod->size_overridden_methods();
5310 if (!*num_overridden)
5311 return;
5312
5313 *overridden = new CXCursor [*num_overridden];
5314 unsigned I = 0;
5315 for (CXXMethodDecl::method_iterator
5316 M = CXXMethod->begin_overridden_methods(),
5317 MEnd = CXXMethod->end_overridden_methods();
5318 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005319 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005320 return;
5321 }
5322
5323 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5324 if (!Method)
5325 return;
5326
5327 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005328 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005329 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5330
5331 if (Methods.empty())
5332 return;
5333
5334 *num_overridden = Methods.size();
5335 *overridden = new CXCursor [Methods.size()];
5336 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005337 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005338}
5339
5340void clang_disposeOverriddenCursors(CXCursor *overridden) {
5341 delete [] overridden;
5342}
5343
Douglas Gregorecdcb882010-10-20 22:00:55 +00005344CXFile clang_getIncludedFile(CXCursor cursor) {
5345 if (cursor.kind != CXCursor_InclusionDirective)
5346 return 0;
5347
5348 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5349 return (void *)ID->getFile();
5350}
5351
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005352} // end: extern "C"
5353
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005354
5355//===----------------------------------------------------------------------===//
5356// C++ AST instrospection.
5357//===----------------------------------------------------------------------===//
5358
5359extern "C" {
5360unsigned clang_CXXMethod_isStatic(CXCursor C) {
5361 if (!clang_isDeclaration(C.kind))
5362 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005363
5364 CXXMethodDecl *Method = 0;
5365 Decl *D = cxcursor::getCursorDecl(C);
5366 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5367 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5368 else
5369 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5370 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005371}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005372
Douglas Gregor211924b2011-05-12 15:17:24 +00005373unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5374 if (!clang_isDeclaration(C.kind))
5375 return 0;
5376
5377 CXXMethodDecl *Method = 0;
5378 Decl *D = cxcursor::getCursorDecl(C);
5379 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5380 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5381 else
5382 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5383 return (Method && Method->isVirtual()) ? 1 : 0;
5384}
5385
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005386} // end: extern "C"
5387
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005388//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005389// Attribute introspection.
5390//===----------------------------------------------------------------------===//
5391
5392extern "C" {
5393CXType clang_getIBOutletCollectionType(CXCursor C) {
5394 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005395 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005396
5397 IBOutletCollectionAttr *A =
5398 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5399
Douglas Gregor841b2382011-03-06 18:55:32 +00005400 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005401}
5402} // end: extern "C"
5403
5404//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005405// Inspecting memory usage.
5406//===----------------------------------------------------------------------===//
5407
Ted Kremenekf7870022011-04-20 16:41:07 +00005408typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005409
Ted Kremenekf7870022011-04-20 16:41:07 +00005410static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5411 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005412 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005413 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005414 entries.push_back(entry);
5415}
5416
5417extern "C" {
5418
Ted Kremenekf7870022011-04-20 16:41:07 +00005419const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005420 const char *str = "";
5421 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005422 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005423 str = "ASTContext: expressions, declarations, and types";
5424 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005425 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005426 str = "ASTContext: identifiers";
5427 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005428 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005429 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005430 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005431 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005432 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005433 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005434 case CXTUResourceUsage_SourceManagerContentCache:
5435 str = "SourceManager: content cache allocator";
5436 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005437 case CXTUResourceUsage_AST_SideTables:
5438 str = "ASTContext: side tables";
5439 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005440 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5441 str = "SourceManager: malloc'ed memory buffers";
5442 break;
5443 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5444 str = "SourceManager: mmap'ed memory buffers";
5445 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005446 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5447 str = "ExternalASTSource: malloc'ed memory buffers";
5448 break;
5449 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5450 str = "ExternalASTSource: mmap'ed memory buffers";
5451 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005452 case CXTUResourceUsage_Preprocessor:
5453 str = "Preprocessor: malloc'ed memory";
5454 break;
5455 case CXTUResourceUsage_PreprocessingRecord:
5456 str = "Preprocessor: PreprocessingRecord";
5457 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005458 }
5459 return str;
5460}
5461
Ted Kremenekf7870022011-04-20 16:41:07 +00005462CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005463 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005464 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005465 return usage;
5466 }
5467
5468 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5469 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5470 ASTContext &astContext = astUnit->getASTContext();
5471
5472 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005473 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005474 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005475
5476 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005477 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005478 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5479
5480 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005481 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005482 (unsigned long) astContext.Selectors.getTotalMemory());
5483
Ted Kremenekba29bd22011-04-28 04:53:38 +00005484 // How much memory is used by ASTContext's side tables?
5485 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5486 (unsigned long) astContext.getSideTableAllocatedMemory());
5487
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005488 // How much memory is used for caching global code completion results?
5489 unsigned long completionBytes = 0;
5490 if (GlobalCodeCompletionAllocator *completionAllocator =
5491 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005492 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005493 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005494 createCXTUResourceUsageEntry(*entries,
5495 CXTUResourceUsage_GlobalCompletionResults,
5496 completionBytes);
5497
5498 // How much memory is being used by SourceManager's content cache?
5499 createCXTUResourceUsageEntry(*entries,
5500 CXTUResourceUsage_SourceManagerContentCache,
5501 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005502
5503 // How much memory is being used by the MemoryBuffer's in SourceManager?
5504 const SourceManager::MemoryBufferSizes &srcBufs =
5505 astUnit->getSourceManager().getMemoryBufferSizes();
5506
5507 createCXTUResourceUsageEntry(*entries,
5508 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5509 (unsigned long) srcBufs.malloc_bytes);
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005510 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005511 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5512 (unsigned long) srcBufs.mmap_bytes);
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005513
5514 // How much memory is being used by the ExternalASTSource?
5515 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5516 const ExternalASTSource::MemoryBufferSizes &sizes =
5517 esrc->getMemoryBufferSizes();
5518
5519 createCXTUResourceUsageEntry(*entries,
5520 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5521 (unsigned long) sizes.malloc_bytes);
5522 createCXTUResourceUsageEntry(*entries,
5523 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5524 (unsigned long) sizes.mmap_bytes);
5525 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005526
5527 // How much memory is being used by the Preprocessor?
5528 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005529 createCXTUResourceUsageEntry(*entries,
5530 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005531 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005532
5533 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5534 createCXTUResourceUsageEntry(*entries,
5535 CXTUResourceUsage_PreprocessingRecord,
5536 pRec->getTotalMemory());
5537 }
5538
5539
Ted Kremenekf7870022011-04-20 16:41:07 +00005540 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005541 (unsigned) entries->size(),
5542 entries->size() ? &(*entries)[0] : 0 };
5543 entries.take();
5544 return usage;
5545}
5546
Ted Kremenekf7870022011-04-20 16:41:07 +00005547void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005548 if (usage.data)
5549 delete (MemUsageEntries*) usage.data;
5550}
5551
5552} // end extern "C"
5553
Douglas Gregor6df78732011-05-05 20:27:22 +00005554void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5555 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5556 for (unsigned I = 0; I != Usage.numEntries; ++I)
5557 fprintf(stderr, " %s: %lu\n",
5558 clang_getTUResourceUsageName(Usage.entries[I].kind),
5559 Usage.entries[I].amount);
5560
5561 clang_disposeCXTUResourceUsage(Usage);
5562}
5563
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005564//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005565// Misc. utility functions.
5566//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005567
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005568/// Default to using an 8 MB stack size on "safety" threads.
5569static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005570
5571namespace clang {
5572
5573bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005574 void (*Fn)(void*), void *UserData,
5575 unsigned Size) {
5576 if (!Size)
5577 Size = GetSafetyThreadStackSize();
5578 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005579 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5580 return CRC.RunSafely(Fn, UserData);
5581}
5582
5583unsigned GetSafetyThreadStackSize() {
5584 return SafetyStackThreadSize;
5585}
5586
5587void SetSafetyThreadStackSize(unsigned Value) {
5588 SafetyStackThreadSize = Value;
5589}
5590
5591}
5592
Ted Kremenek04bb7162010-01-22 22:44:15 +00005593extern "C" {
5594
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005595CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005596 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005597}
5598
5599} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005600