blob: c78584a3a72a6b2d13d99e55fe2cd17f76f909d5 [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())
Douglas Gregorffcd9852011-04-20 21:16:21 +0000120 EndLoc = SM.getInstantiationRange(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
164typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
165
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.
206 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
207 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
208
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.
259 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
260 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
270 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
271 getPreprocessedEntities();
272
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000274
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000275 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000276 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000277 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000278 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000279 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000280 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000281 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000282 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
283 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000284 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000285 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000286 bool VisitClassTemplatePartialSpecializationDecl(
287 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000288 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitEnumConstantDecl(EnumConstantDecl *D);
290 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
291 bool VisitFunctionDecl(FunctionDecl *ND);
292 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000293 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000294 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000295 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000296 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000297 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
299 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
300 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
301 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000302 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000303 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
304 bool VisitObjCImplDecl(ObjCImplDecl *D);
305 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
306 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000307 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
308 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
309 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000310 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000311 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000312 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000313 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000314 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000315 bool VisitUsingDecl(UsingDecl *D);
316 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
317 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000318
Douglas Gregor01829d32010-08-31 14:41:23 +0000319 // Name visitor
320 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000321 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000322 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000323
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000324 // Template visitors
325 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000326 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000327 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
328
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000329 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000330 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000332 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000333 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
334 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000335 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000337 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000339 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000340 bool VisitPointerTypeLoc(PointerTypeLoc TL);
341 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
342 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
343 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
344 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000345 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000346 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000347 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000348 // FIXME: Implement visitors here when the unimplemented TypeLocs get
349 // implemented
350 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000351 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000352 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Sean Huntca63c202011-05-24 22:41:36 +0000353 bool VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000354 bool VisitDependentNameTypeLoc(DependentNameTypeLoc TL);
Douglas Gregor94fdffa2011-03-01 20:11:18 +0000355 bool VisitDependentTemplateSpecializationTypeLoc(
356 DependentTemplateSpecializationTypeLoc TL);
Douglas Gregor9e876872011-03-01 18:12:44 +0000357 bool VisitElaboratedTypeLoc(ElaboratedTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000358
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000359 // Data-recursive visitor functions.
360 bool IsInRegionOfInterest(CXCursor C);
361 bool RunVisitorWorkList(VisitorWorkList &WL);
362 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000363 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000364};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000365
Ted Kremenekab188932010-01-05 19:32:54 +0000366} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000367
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000368static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000369static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
370
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000371
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000373 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374}
375
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376/// \brief Visit the given cursor and, if requested by the visitor,
377/// its children.
378///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000379/// \param Cursor the cursor to visit.
380///
381/// \param CheckRegionOfInterest if true, then the caller already checked that
382/// this cursor is within the region of interest.
383///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000384/// \returns true if the visitation should be aborted, false if it
385/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000386bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000387 if (clang_isInvalid(Cursor.kind))
388 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000389
Douglas Gregorb1373d02010-01-20 20:59:29 +0000390 if (clang_isDeclaration(Cursor.kind)) {
391 Decl *D = getCursorDecl(Cursor);
392 assert(D && "Invalid declaration cursor");
393 if (D->getPCHLevel() > MaxPCHLevel)
394 return false;
395
396 if (D->isImplicit())
397 return false;
398 }
399
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000400 // If we have a range of interest, and this cursor doesn't intersect with it,
401 // we're done.
402 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000403 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000404 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000405 return false;
406 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000407
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408 switch (Visitor(Cursor, Parent, ClientData)) {
409 case CXChildVisit_Break:
410 return true;
411
412 case CXChildVisit_Continue:
413 return false;
414
415 case CXChildVisit_Recurse:
416 return VisitChildren(Cursor);
417 }
418
Douglas Gregorfd643772010-01-25 16:45:46 +0000419 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000420}
421
Douglas Gregor788f5a12010-03-20 00:41:21 +0000422std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
423CursorVisitor::getPreprocessedEntities() {
424 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000425 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000426
427 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000428 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
429
430 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
431 // If we would only look at local declarations but we have a region of
432 // interest, check whether that region of interest is in the main file.
433 // If not, we should traverse all declarations.
434 // FIXME: My kingdom for a proper binary search approach to finding
435 // cursors!
436 std::pair<FileID, unsigned> Location
437 = AU->getSourceManager().getDecomposedInstantiationLoc(
438 RegionOfInterest.getBegin());
439 if (Location.first != AU->getSourceManager().getMainFileID())
440 OnlyLocalDecls = false;
441 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000442
Douglas Gregor89d99802010-11-30 06:16:57 +0000443 PreprocessingRecord::iterator StartEntity, EndEntity;
444 if (OnlyLocalDecls) {
445 StartEntity = AU->pp_entity_begin();
446 EndEntity = AU->pp_entity_end();
447 } else {
448 StartEntity = PPRec.begin();
449 EndEntity = PPRec.end();
450 }
451
Douglas Gregor788f5a12010-03-20 00:41:21 +0000452 // There is no region of interest; we have to walk everything.
453 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000454 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000455
456 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000457 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000458 std::pair<FileID, unsigned> Begin
459 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
460 std::pair<FileID, unsigned> End
461 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
462
463 // The region of interest spans files; we have to walk everything.
464 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000465 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000466
467 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000468 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000469 if (ByFileMap.empty()) {
470 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000471 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000472 std::pair<FileID, unsigned> P
473 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000474
Douglas Gregor788f5a12010-03-20 00:41:21 +0000475 ByFileMap[P.first].push_back(*E);
476 }
477 }
478
479 return std::make_pair(ByFileMap[Begin.first].begin(),
480 ByFileMap[Begin.first].end());
481}
482
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000484///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000485/// \returns true if the visitation should be aborted, false if it
486/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000487bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000488 if (clang_isReference(Cursor.kind) &&
489 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000490 // By definition, references have no children.
491 return false;
492 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000493
494 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000496 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000497
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498 if (clang_isDeclaration(Cursor.kind)) {
499 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000500 if (!D)
501 return false;
502
Ted Kremenek539311e2010-02-18 18:47:01 +0000503 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000505
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000506 if (clang_isStatement(Cursor.kind)) {
507 if (Stmt *S = getCursorStmt(Cursor))
508 return Visit(S);
509
510 return false;
511 }
512
513 if (clang_isExpression(Cursor.kind)) {
514 if (Expr *E = getCursorExpr(Cursor))
515 return Visit(E);
516
517 return false;
518 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000519
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000521 CXTranslationUnit tu = getCursorTU(Cursor);
522 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000523
524 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
525 for (unsigned I = 0; I != 2; ++I) {
526 if (VisitOrder[I]) {
527 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
528 RegionOfInterest.isInvalid()) {
529 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
530 TLEnd = CXXUnit->top_level_end();
531 TL != TLEnd; ++TL) {
532 if (Visit(MakeCXCursor(*TL, tu), true))
533 return true;
534 }
535 } else if (VisitDeclContext(
536 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000537 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000538 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000539 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000540
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000541 // Walk the preprocessing record.
542 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
543 // FIXME: Once we have the ability to deserialize a preprocessing record,
544 // do so.
545 PreprocessingRecord::iterator E, EEnd;
546 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000547 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
548 if (Visit(MakeMacroExpansionCursor(ME, tu)))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000549 return true;
550
551 continue;
552 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000553
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000554 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
555 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
556 return true;
557
558 continue;
559 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000560
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000561 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
562 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
563 return true;
564
565 continue;
566 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000567 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000568 }
569 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000570
Douglas Gregor7b691f332010-01-20 21:13:59 +0000571 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000573
Douglas Gregorc314aa42011-03-02 19:17:03 +0000574 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
575 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
576 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
577 return Visit(BaseTSInfo->getTypeLoc());
578 }
579 }
580 }
581
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return false;
584}
585
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000586bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000587 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
588 if (Visit(TSInfo->getTypeLoc()))
589 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000590
Ted Kremenek664cffd2010-07-22 11:30:19 +0000591 if (Stmt *Body = B->getBody())
592 return Visit(MakeCXCursor(Body, StmtParent, TU));
593
594 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000595}
596
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000597llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
598 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000599 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000600 if (Range.isInvalid())
601 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000602
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000603 switch (CompareRegionOfInterest(Range)) {
604 case RangeBefore:
605 // This declaration comes before the region of interest; skip it.
606 return llvm::Optional<bool>();
607
608 case RangeAfter:
609 // This declaration comes after the region of interest; we're done.
610 return false;
611
612 case RangeOverlap:
613 // This declaration overlaps the region of interest; visit it.
614 break;
615 }
616 }
617 return true;
618}
619
620bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
621 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
622
623 // FIXME: Eventually remove. This part of a hack to support proper
624 // iteration over all Decls contained lexically within an ObjC container.
625 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
626 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
627
628 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000629 Decl *D = *I;
630 if (D->getLexicalDeclContext() != DC)
631 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000632 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000633 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
634 if (!V.hasValue())
635 continue;
636 if (!V.getValue())
637 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000638 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000639 return true;
640 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000641 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000642}
643
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000644bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
645 llvm_unreachable("Translation units are visited directly by Visit()");
646 return false;
647}
648
Richard Smith162e1c12011-04-15 14:24:37 +0000649bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
650 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
651 return Visit(TSInfo->getTypeLoc());
652
653 return false;
654}
655
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000656bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
657 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
658 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000659
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000660 return false;
661}
662
663bool CursorVisitor::VisitTagDecl(TagDecl *D) {
664 return VisitDeclContext(D);
665}
666
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000667bool CursorVisitor::VisitClassTemplateSpecializationDecl(
668 ClassTemplateSpecializationDecl *D) {
669 bool ShouldVisitBody = false;
670 switch (D->getSpecializationKind()) {
671 case TSK_Undeclared:
672 case TSK_ImplicitInstantiation:
673 // Nothing to visit
674 return false;
675
676 case TSK_ExplicitInstantiationDeclaration:
677 case TSK_ExplicitInstantiationDefinition:
678 break;
679
680 case TSK_ExplicitSpecialization:
681 ShouldVisitBody = true;
682 break;
683 }
684
685 // Visit the template arguments used in the specialization.
686 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
687 TypeLoc TL = SpecType->getTypeLoc();
688 if (TemplateSpecializationTypeLoc *TSTLoc
689 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
690 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
691 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
692 return true;
693 }
694 }
695
696 if (ShouldVisitBody && VisitCXXRecordDecl(D))
697 return true;
698
699 return false;
700}
701
Douglas Gregor74dbe642010-08-31 19:31:58 +0000702bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
703 ClassTemplatePartialSpecializationDecl *D) {
704 // FIXME: Visit the "outer" template parameter lists on the TagDecl
705 // before visiting these template parameters.
706 if (VisitTemplateParameters(D->getTemplateParameters()))
707 return true;
708
709 // Visit the partial specialization arguments.
710 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
711 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
712 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
713 return true;
714
715 return VisitCXXRecordDecl(D);
716}
717
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000718bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000719 // Visit the default argument.
720 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
721 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
722 if (Visit(DefArg->getTypeLoc()))
723 return true;
724
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000725 return false;
726}
727
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000728bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
729 if (Expr *Init = D->getInitExpr())
730 return Visit(MakeCXCursor(Init, StmtParent, TU));
731 return false;
732}
733
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000734bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
735 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
736 if (Visit(TSInfo->getTypeLoc()))
737 return true;
738
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000739 // Visit the nested-name-specifier, if present.
740 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
741 if (VisitNestedNameSpecifierLoc(QualifierLoc))
742 return true;
743
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000744 return false;
745}
746
Douglas Gregora67e03f2010-09-09 21:42:20 +0000747/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000748static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
749 CXXCtorInitializer const * const *X
750 = static_cast<CXXCtorInitializer const * const *>(Xp);
751 CXXCtorInitializer const * const *Y
752 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000753
754 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
755 return -1;
756 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
757 return 1;
758 else
759 return 0;
760}
761
Douglas Gregorb1373d02010-01-20 20:59:29 +0000762bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000763 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
764 // Visit the function declaration's syntactic components in the order
765 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000766 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000767 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
768
769 // If we have a function declared directly (without the use of a typedef),
770 // visit just the return type. Otherwise, just visit the function's type
771 // now.
772 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
773 (!FTL && Visit(TL)))
774 return true;
775
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000776 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000777 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
778 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000779 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000780
781 // Visit the declaration name.
782 if (VisitDeclarationNameInfo(ND->getNameInfo()))
783 return true;
784
785 // FIXME: Visit explicitly-specified template arguments!
786
787 // Visit the function parameters, if we have a function type.
788 if (FTL && VisitFunctionTypeLoc(*FTL, true))
789 return true;
790
791 // FIXME: Attributes?
792 }
793
Sean Hunt10620eb2011-05-06 20:44:56 +0000794 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000795 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
796 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000797 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000798 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
799 IEnd = Constructor->init_end();
800 I != IEnd; ++I) {
801 if (!(*I)->isWritten())
802 continue;
803
804 WrittenInits.push_back(*I);
805 }
806
807 // Sort the initializers in source order
808 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000809 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000810
811 // Visit the initializers in source order
812 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000813 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000814 if (Init->isAnyMemberInitializer()) {
815 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000816 Init->getMemberLocation(), TU)))
817 return true;
818 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
819 if (Visit(BaseInfo->getTypeLoc()))
820 return true;
821 }
822
823 // Visit the initializer value.
824 if (Expr *Initializer = Init->getInit())
825 if (Visit(MakeCXCursor(Initializer, ND, TU)))
826 return true;
827 }
828 }
829
830 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
831 return true;
832 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833
Douglas Gregorb1373d02010-01-20 20:59:29 +0000834 return false;
835}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000836
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000837bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
838 if (VisitDeclaratorDecl(D))
839 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841 if (Expr *BitWidth = D->getBitWidth())
842 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000843
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000844 return false;
845}
846
847bool CursorVisitor::VisitVarDecl(VarDecl *D) {
848 if (VisitDeclaratorDecl(D))
849 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000851 if (Expr *Init = D->getInit())
852 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 return false;
855}
856
Douglas Gregor84b51d72010-09-01 20:16:53 +0000857bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
858 if (VisitDeclaratorDecl(D))
859 return true;
860
861 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
862 if (Expr *DefArg = D->getDefaultArgument())
863 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
864
865 return false;
866}
867
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000868bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
869 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
870 // before visiting these template parameters.
871 if (VisitTemplateParameters(D->getTemplateParameters()))
872 return true;
873
874 return VisitFunctionDecl(D->getTemplatedDecl());
875}
876
Douglas Gregor39d6f072010-08-31 19:02:00 +0000877bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
878 // FIXME: Visit the "outer" template parameter lists on the TagDecl
879 // before visiting these template parameters.
880 if (VisitTemplateParameters(D->getTemplateParameters()))
881 return true;
882
883 return VisitCXXRecordDecl(D->getTemplatedDecl());
884}
885
Douglas Gregor84b51d72010-09-01 20:16:53 +0000886bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
887 if (VisitTemplateParameters(D->getTemplateParameters()))
888 return true;
889
890 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
891 VisitTemplateArgumentLoc(D->getDefaultArgument()))
892 return true;
893
894 return false;
895}
896
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000897bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000898 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
899 if (Visit(TSInfo->getTypeLoc()))
900 return true;
901
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000903 PEnd = ND->param_end();
904 P != PEnd; ++P) {
905 if (Visit(MakeCXCursor(*P, TU)))
906 return true;
907 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000908
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000909 if (ND->isThisDeclarationADefinition() &&
910 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
911 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000912
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000913 return false;
914}
915
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000916namespace {
917 struct ContainerDeclsSort {
918 SourceManager &SM;
919 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
920 bool operator()(Decl *A, Decl *B) {
921 SourceLocation L_A = A->getLocStart();
922 SourceLocation L_B = B->getLocStart();
923 assert(L_A.isValid() && L_B.isValid());
924 return SM.isBeforeInTranslationUnit(L_A, L_B);
925 }
926 };
927}
928
Douglas Gregora59e3902010-01-21 23:27:09 +0000929bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000930 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
931 // an @implementation can lexically contain Decls that are not properly
932 // nested in the AST. When we identify such cases, we need to retrofit
933 // this nesting here.
934 if (!DI_current)
935 return VisitDeclContext(D);
936
937 // Scan the Decls that immediately come after the container
938 // in the current DeclContext. If any fall within the
939 // container's lexical region, stash them into a vector
940 // for later processing.
941 llvm::SmallVector<Decl *, 24> DeclsInContainer;
942 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000943 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000944 if (EndLoc.isValid()) {
945 DeclContext::decl_iterator next = *DI_current;
946 while (++next != DE_current) {
947 Decl *D_next = *next;
948 if (!D_next)
949 break;
950 SourceLocation L = D_next->getLocStart();
951 if (!L.isValid())
952 break;
953 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
954 *DI_current = next;
955 DeclsInContainer.push_back(D_next);
956 continue;
957 }
958 break;
959 }
960 }
961
962 // The common case.
963 if (DeclsInContainer.empty())
964 return VisitDeclContext(D);
965
966 // Get all the Decls in the DeclContext, and sort them with the
967 // additional ones we've collected. Then visit them.
968 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
969 I!=E; ++I) {
970 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000971 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
972 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000973 continue;
974 DeclsInContainer.push_back(subDecl);
975 }
976
977 // Now sort the Decls so that they appear in lexical order.
978 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
979 ContainerDeclsSort(SM));
980
981 // Now visit the decls.
982 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
983 E = DeclsInContainer.end(); I != E; ++I) {
984 CXCursor Cursor = MakeCXCursor(*I, TU);
985 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
986 if (!V.hasValue())
987 continue;
988 if (!V.getValue())
989 return false;
990 if (Visit(Cursor, true))
991 return true;
992 }
993 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000994}
995
Douglas Gregorb1373d02010-01-20 20:59:29 +0000996bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000997 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
998 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000999 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001000
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001001 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1002 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1003 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001004 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001005 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006
Douglas Gregora59e3902010-01-21 23:27:09 +00001007 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001008}
1009
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001010bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1011 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1012 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1013 E = PID->protocol_end(); I != E; ++I, ++PL)
1014 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001017 return VisitObjCContainerDecl(PID);
1018}
1019
Ted Kremenek23173d72010-05-18 21:09:07 +00001020bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001021 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001022 return true;
1023
Ted Kremenek23173d72010-05-18 21:09:07 +00001024 // FIXME: This implements a workaround with @property declarations also being
1025 // installed in the DeclContext for the @interface. Eventually this code
1026 // should be removed.
1027 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1028 if (!CDecl || !CDecl->IsClassExtension())
1029 return false;
1030
1031 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1032 if (!ID)
1033 return false;
1034
1035 IdentifierInfo *PropertyId = PD->getIdentifier();
1036 ObjCPropertyDecl *prevDecl =
1037 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1038
1039 if (!prevDecl)
1040 return false;
1041
1042 // Visit synthesized methods since they will be skipped when visiting
1043 // the @interface.
1044 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001045 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001046 if (Visit(MakeCXCursor(MD, TU)))
1047 return true;
1048
1049 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001050 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001051 if (Visit(MakeCXCursor(MD, TU)))
1052 return true;
1053
1054 return false;
1055}
1056
Douglas Gregorb1373d02010-01-20 20:59:29 +00001057bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001058 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001059 if (D->getSuperClass() &&
1060 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001062 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001063 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001064
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001065 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1066 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1067 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001068 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001069 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001070
Douglas Gregora59e3902010-01-21 23:27:09 +00001071 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001072}
1073
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001074bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1075 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001076}
1077
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001078bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001079 // 'ID' could be null when dealing with invalid code.
1080 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1081 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1082 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001083
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001084 return VisitObjCImplDecl(D);
1085}
1086
1087bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1088#if 0
1089 // Issue callbacks for super class.
1090 // FIXME: No source location information!
1091 if (D->getSuperClass() &&
1092 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001093 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001094 TU)))
1095 return true;
1096#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001097
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001098 return VisitObjCImplDecl(D);
1099}
1100
1101bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1102 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1103 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1104 E = D->protocol_end();
1105 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001106 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001107 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001108
1109 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001110}
1111
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001112bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1113 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1114 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1115 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001116
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001117 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001118}
1119
Douglas Gregora4ffd852010-11-17 01:03:52 +00001120bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1121 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1122 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1123
1124 return false;
1125}
1126
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001127bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1128 return VisitDeclContext(D);
1129}
1130
Douglas Gregor69319002010-08-31 23:48:11 +00001131bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001132 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001133 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1134 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001135 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001136
1137 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1138 D->getTargetNameLoc(), TU));
1139}
1140
Douglas Gregor7e242562010-09-01 19:52:22 +00001141bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001142 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001143 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1144 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001145 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001146 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001147
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001148 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1149 return true;
1150
Douglas Gregor7e242562010-09-01 19:52:22 +00001151 return VisitDeclarationNameInfo(D->getNameInfo());
1152}
1153
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001154bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001155 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001156 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1157 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001158 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001159
1160 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1161 D->getIdentLocation(), TU));
1162}
1163
Douglas Gregor7e242562010-09-01 19:52:22 +00001164bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001165 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001166 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1167 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001168 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001169 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001170
Douglas Gregor7e242562010-09-01 19:52:22 +00001171 return VisitDeclarationNameInfo(D->getNameInfo());
1172}
1173
1174bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1175 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001176 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001177 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1178 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001179 return true;
1180
Douglas Gregor7e242562010-09-01 19:52:22 +00001181 return false;
1182}
1183
Douglas Gregor01829d32010-08-31 14:41:23 +00001184bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1185 switch (Name.getName().getNameKind()) {
1186 case clang::DeclarationName::Identifier:
1187 case clang::DeclarationName::CXXLiteralOperatorName:
1188 case clang::DeclarationName::CXXOperatorName:
1189 case clang::DeclarationName::CXXUsingDirective:
1190 return false;
1191
1192 case clang::DeclarationName::CXXConstructorName:
1193 case clang::DeclarationName::CXXDestructorName:
1194 case clang::DeclarationName::CXXConversionFunctionName:
1195 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1196 return Visit(TSInfo->getTypeLoc());
1197 return false;
1198
1199 case clang::DeclarationName::ObjCZeroArgSelector:
1200 case clang::DeclarationName::ObjCOneArgSelector:
1201 case clang::DeclarationName::ObjCMultiArgSelector:
1202 // FIXME: Per-identifier location info?
1203 return false;
1204 }
1205
1206 return false;
1207}
1208
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001209bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1210 SourceRange Range) {
1211 // FIXME: This whole routine is a hack to work around the lack of proper
1212 // source information in nested-name-specifiers (PR5791). Since we do have
1213 // a beginning source location, we can visit the first component of the
1214 // nested-name-specifier, if it's a single-token component.
1215 if (!NNS)
1216 return false;
1217
1218 // Get the first component in the nested-name-specifier.
1219 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1220 NNS = Prefix;
1221
1222 switch (NNS->getKind()) {
1223 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001224 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1225 TU));
1226
Douglas Gregor14aba762011-02-24 02:36:08 +00001227 case NestedNameSpecifier::NamespaceAlias:
1228 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1229 Range.getBegin(), TU));
1230
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001231 case NestedNameSpecifier::TypeSpec: {
1232 // If the type has a form where we know that the beginning of the source
1233 // range matches up with a reference cursor. Visit the appropriate reference
1234 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001235 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001236 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1237 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1238 if (const TagType *Tag = dyn_cast<TagType>(T))
1239 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1240 if (const TemplateSpecializationType *TST
1241 = dyn_cast<TemplateSpecializationType>(T))
1242 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1243 break;
1244 }
1245
1246 case NestedNameSpecifier::TypeSpecWithTemplate:
1247 case NestedNameSpecifier::Global:
1248 case NestedNameSpecifier::Identifier:
1249 break;
1250 }
1251
1252 return false;
1253}
1254
Douglas Gregordc355712011-02-25 00:36:19 +00001255bool
1256CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1257 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1258 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1259 Qualifiers.push_back(Qualifier);
1260
1261 while (!Qualifiers.empty()) {
1262 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1263 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1264 switch (NNS->getKind()) {
1265 case NestedNameSpecifier::Namespace:
1266 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001267 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001268 TU)))
1269 return true;
1270
1271 break;
1272
1273 case NestedNameSpecifier::NamespaceAlias:
1274 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001275 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001276 TU)))
1277 return true;
1278
1279 break;
1280
1281 case NestedNameSpecifier::TypeSpec:
1282 case NestedNameSpecifier::TypeSpecWithTemplate:
1283 if (Visit(Q.getTypeLoc()))
1284 return true;
1285
1286 break;
1287
1288 case NestedNameSpecifier::Global:
1289 case NestedNameSpecifier::Identifier:
1290 break;
1291 }
1292 }
1293
1294 return false;
1295}
1296
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001297bool CursorVisitor::VisitTemplateParameters(
1298 const TemplateParameterList *Params) {
1299 if (!Params)
1300 return false;
1301
1302 for (TemplateParameterList::const_iterator P = Params->begin(),
1303 PEnd = Params->end();
1304 P != PEnd; ++P) {
1305 if (Visit(MakeCXCursor(*P, TU)))
1306 return true;
1307 }
1308
1309 return false;
1310}
1311
Douglas Gregor0b36e612010-08-31 20:37:03 +00001312bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1313 switch (Name.getKind()) {
1314 case TemplateName::Template:
1315 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1316
1317 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001318 // Visit the overloaded template set.
1319 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1320 return true;
1321
Douglas Gregor0b36e612010-08-31 20:37:03 +00001322 return false;
1323
1324 case TemplateName::DependentTemplate:
1325 // FIXME: Visit nested-name-specifier.
1326 return false;
1327
1328 case TemplateName::QualifiedTemplate:
1329 // FIXME: Visit nested-name-specifier.
1330 return Visit(MakeCursorTemplateRef(
1331 Name.getAsQualifiedTemplateName()->getDecl(),
1332 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001333
1334 case TemplateName::SubstTemplateTemplateParm:
1335 return Visit(MakeCursorTemplateRef(
1336 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1337 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001338
1339 case TemplateName::SubstTemplateTemplateParmPack:
1340 return Visit(MakeCursorTemplateRef(
1341 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1342 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001343 }
1344
1345 return false;
1346}
1347
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001348bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1349 switch (TAL.getArgument().getKind()) {
1350 case TemplateArgument::Null:
1351 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001352 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001353 return false;
1354
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001355 case TemplateArgument::Type:
1356 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1357 return Visit(TSInfo->getTypeLoc());
1358 return false;
1359
1360 case TemplateArgument::Declaration:
1361 if (Expr *E = TAL.getSourceDeclExpression())
1362 return Visit(MakeCXCursor(E, StmtParent, TU));
1363 return false;
1364
1365 case TemplateArgument::Expression:
1366 if (Expr *E = TAL.getSourceExpression())
1367 return Visit(MakeCXCursor(E, StmtParent, TU));
1368 return false;
1369
1370 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001371 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001372 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1373 return true;
1374
Douglas Gregora7fc9012011-01-05 18:58:31 +00001375 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001376 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001377 }
1378
1379 return false;
1380}
1381
Ted Kremeneka0536d82010-05-07 01:04:29 +00001382bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1383 return VisitDeclContext(D);
1384}
1385
Douglas Gregor01829d32010-08-31 14:41:23 +00001386bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1387 return Visit(TL.getUnqualifiedLoc());
1388}
1389
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001391 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392
1393 // Some builtin types (such as Objective-C's "id", "sel", and
1394 // "Class") have associated declarations. Create cursors for those.
1395 QualType VisitType;
1396 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001397 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001398 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001399 case BuiltinType::Char_U:
1400 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001401 case BuiltinType::Char16:
1402 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001403 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001404 case BuiltinType::UInt:
1405 case BuiltinType::ULong:
1406 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001407 case BuiltinType::UInt128:
1408 case BuiltinType::Char_S:
1409 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001410 case BuiltinType::WChar_U:
1411 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001412 case BuiltinType::Short:
1413 case BuiltinType::Int:
1414 case BuiltinType::Long:
1415 case BuiltinType::LongLong:
1416 case BuiltinType::Int128:
1417 case BuiltinType::Float:
1418 case BuiltinType::Double:
1419 case BuiltinType::LongDouble:
1420 case BuiltinType::NullPtr:
1421 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001422 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001423 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001424 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001425 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001426
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001427 case BuiltinType::ObjCId:
1428 VisitType = Context.getObjCIdType();
1429 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001430
1431 case BuiltinType::ObjCClass:
1432 VisitType = Context.getObjCClassType();
1433 break;
1434
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001435 case BuiltinType::ObjCSel:
1436 VisitType = Context.getObjCSelType();
1437 break;
1438 }
1439
1440 if (!VisitType.isNull()) {
1441 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001442 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001443 TU));
1444 }
1445
1446 return false;
1447}
1448
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001449bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001450 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001451}
1452
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001453bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1454 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1455}
1456
1457bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1458 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1459}
1460
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001461bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001462 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001463}
1464
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001465bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1466 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1467 return true;
1468
John McCallc12c5bb2010-05-15 11:32:37 +00001469 return false;
1470}
1471
1472bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1473 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1474 return true;
1475
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001476 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1477 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1478 TU)))
1479 return true;
1480 }
1481
1482 return false;
1483}
1484
1485bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001486 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001487}
1488
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001489bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1490 return Visit(TL.getInnerLoc());
1491}
1492
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001493bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1494 return Visit(TL.getPointeeLoc());
1495}
1496
1497bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1498 return Visit(TL.getPointeeLoc());
1499}
1500
1501bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1502 return Visit(TL.getPointeeLoc());
1503}
1504
1505bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001506 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001507}
1508
1509bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001510 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001511}
1512
Douglas Gregor01829d32010-08-31 14:41:23 +00001513bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1514 bool SkipResultType) {
1515 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001516 return true;
1517
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001518 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001519 if (Decl *D = TL.getArg(I))
1520 if (Visit(MakeCXCursor(D, TU)))
1521 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001522
1523 return false;
1524}
1525
1526bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1527 if (Visit(TL.getElementLoc()))
1528 return true;
1529
1530 if (Expr *Size = TL.getSizeExpr())
1531 return Visit(MakeCXCursor(Size, StmtParent, TU));
1532
1533 return false;
1534}
1535
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001536bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1537 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001538 // Visit the template name.
1539 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1540 TL.getTemplateNameLoc()))
1541 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001542
1543 // Visit the template arguments.
1544 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1545 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1546 return true;
1547
1548 return false;
1549}
1550
Douglas Gregor2332c112010-01-21 20:48:56 +00001551bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1552 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1553}
1554
1555bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1556 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1557 return Visit(TSInfo->getTypeLoc());
1558
1559 return false;
1560}
1561
Sean Huntca63c202011-05-24 22:41:36 +00001562bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1563 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1564 return Visit(TSInfo->getTypeLoc());
1565
1566 return false;
1567}
1568
Douglas Gregor2494dd02011-03-01 01:34:45 +00001569bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1570 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1571 return true;
1572
1573 return false;
1574}
1575
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001576bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1577 DependentTemplateSpecializationTypeLoc TL) {
1578 // Visit the nested-name-specifier, if there is one.
1579 if (TL.getQualifierLoc() &&
1580 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1581 return true;
1582
1583 // Visit the template arguments.
1584 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1585 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1586 return true;
1587
1588 return false;
1589}
1590
Douglas Gregor9e876872011-03-01 18:12:44 +00001591bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1592 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1593 return true;
1594
1595 return Visit(TL.getNamedTypeLoc());
1596}
1597
Douglas Gregor7536dd52010-12-20 02:24:11 +00001598bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1599 return Visit(TL.getPatternLoc());
1600}
1601
Ted Kremenek3064ef92010-08-27 21:34:58 +00001602bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001603 // Visit the nested-name-specifier, if present.
1604 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1605 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1606 return true;
1607
Ted Kremenek3064ef92010-08-27 21:34:58 +00001608 if (D->isDefinition()) {
1609 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1610 E = D->bases_end(); I != E; ++I) {
1611 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1612 return true;
1613 }
1614 }
1615
1616 return VisitTagDecl(D);
1617}
1618
Ted Kremenek09dfa372010-02-18 05:46:33 +00001619bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001620 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1621 i != e; ++i)
1622 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001623 return true;
1624
1625 return false;
1626}
1627
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001628//===----------------------------------------------------------------------===//
1629// Data-recursive visitor methods.
1630//===----------------------------------------------------------------------===//
1631
Ted Kremenek28a71942010-11-13 00:36:47 +00001632namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001633#define DEF_JOB(NAME, DATA, KIND)\
1634class NAME : public VisitorJob {\
1635public:\
1636 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1637 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001638 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001639};
1640
1641DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1642DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001643DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001644DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001645DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1646 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001647DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001648#undef DEF_JOB
1649
1650class DeclVisit : public VisitorJob {
1651public:
1652 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1653 VisitorJob(parent, VisitorJob::DeclVisitKind,
1654 d, isFirst ? (void*) 1 : (void*) 0) {}
1655 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001656 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001657 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001658 Decl *get() const { return static_cast<Decl*>(data[0]); }
1659 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001660};
Ted Kremenek035dc412010-11-13 00:36:50 +00001661class TypeLocVisit : public VisitorJob {
1662public:
1663 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1664 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1665 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1666
1667 static bool classof(const VisitorJob *VJ) {
1668 return VJ->getKind() == TypeLocVisitKind;
1669 }
1670
Ted Kremenek82f3c502010-11-15 22:23:26 +00001671 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001672 QualType T = QualType::getFromOpaquePtr(data[0]);
1673 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001674 }
1675};
1676
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001677class LabelRefVisit : public VisitorJob {
1678public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001679 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1680 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001681 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001682
1683 static bool classof(const VisitorJob *VJ) {
1684 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1685 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001686 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001687 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001688 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001689};
1690class NestedNameSpecifierVisit : public VisitorJob {
1691public:
1692 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1693 CXCursor parent)
1694 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001695 NS, R.getBegin().getPtrEncoding(),
1696 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001697 static bool classof(const VisitorJob *VJ) {
1698 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1699 }
1700 NestedNameSpecifier *get() const {
1701 return static_cast<NestedNameSpecifier*>(data[0]);
1702 }
1703 SourceRange getSourceRange() const {
1704 SourceLocation A =
1705 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1706 SourceLocation B =
1707 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1708 return SourceRange(A, B);
1709 }
1710};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001711
1712class NestedNameSpecifierLocVisit : public VisitorJob {
1713public:
1714 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1715 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1716 Qualifier.getNestedNameSpecifier(),
1717 Qualifier.getOpaqueData()) { }
1718
1719 static bool classof(const VisitorJob *VJ) {
1720 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1721 }
1722
1723 NestedNameSpecifierLoc get() const {
1724 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1725 data[1]);
1726 }
1727};
1728
Ted Kremenekf64d8032010-11-18 00:02:32 +00001729class DeclarationNameInfoVisit : public VisitorJob {
1730public:
1731 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1732 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1733 static bool classof(const VisitorJob *VJ) {
1734 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1735 }
1736 DeclarationNameInfo get() const {
1737 Stmt *S = static_cast<Stmt*>(data[0]);
1738 switch (S->getStmtClass()) {
1739 default:
1740 llvm_unreachable("Unhandled Stmt");
1741 case Stmt::CXXDependentScopeMemberExprClass:
1742 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1743 case Stmt::DependentScopeDeclRefExprClass:
1744 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1745 }
1746 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001747};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001748class MemberRefVisit : public VisitorJob {
1749public:
1750 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1751 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001752 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001753 static bool classof(const VisitorJob *VJ) {
1754 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1755 }
1756 FieldDecl *get() const {
1757 return static_cast<FieldDecl*>(data[0]);
1758 }
1759 SourceLocation getLoc() const {
1760 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1761 }
1762};
Ted Kremenek28a71942010-11-13 00:36:47 +00001763class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1764 VisitorWorkList &WL;
1765 CXCursor Parent;
1766public:
1767 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1768 : WL(wl), Parent(parent) {}
1769
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001770 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001771 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001772 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001773 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001774 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001775 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001776 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001777 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001778 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001779 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001780 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001781 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001782 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001783 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001784 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001785 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001786 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001787 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001788 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1789 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001790 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001791 void VisitIfStmt(IfStmt *If);
1792 void VisitInitListExpr(InitListExpr *IE);
1793 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001794 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001795 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001796 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1797 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001798 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001799 void VisitStmt(Stmt *S);
1800 void VisitSwitchStmt(SwitchStmt *S);
1801 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001802 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001803 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001804 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001805 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001806 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001807 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001808 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001809
Ted Kremenek28a71942010-11-13 00:36:47 +00001810private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001811 void AddDeclarationNameInfo(Stmt *S);
1812 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001813 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001814 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001815 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001816 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001817 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001818 void AddTypeLoc(TypeSourceInfo *TI);
1819 void EnqueueChildren(Stmt *S);
1820};
1821} // end anonyous namespace
1822
Ted Kremenekf64d8032010-11-18 00:02:32 +00001823void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1824 // 'S' should always be non-null, since it comes from the
1825 // statement we are visiting.
1826 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1827}
1828void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1829 SourceRange R) {
1830 if (N)
1831 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1832}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001833
1834void
1835EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1836 if (Qualifier)
1837 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1838}
1839
Ted Kremenek28a71942010-11-13 00:36:47 +00001840void EnqueueVisitor::AddStmt(Stmt *S) {
1841 if (S)
1842 WL.push_back(StmtVisit(S, Parent));
1843}
Ted Kremenek035dc412010-11-13 00:36:50 +00001844void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001845 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001846 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001847}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001848void EnqueueVisitor::
1849 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1850 if (A)
1851 WL.push_back(ExplicitTemplateArgsVisit(
1852 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1853}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001854void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1855 if (D)
1856 WL.push_back(MemberRefVisit(D, L, Parent));
1857}
Ted Kremenek28a71942010-11-13 00:36:47 +00001858void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1859 if (TI)
1860 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1861 }
1862void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001863 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001864 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001865 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001866 }
1867 if (size == WL.size())
1868 return;
1869 // Now reverse the entries we just added. This will match the DFS
1870 // ordering performed by the worklist.
1871 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1872 std::reverse(I, E);
1873}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001874void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1875 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1876}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001877void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1878 AddDecl(B->getBlockDecl());
1879}
Ted Kremenek28a71942010-11-13 00:36:47 +00001880void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1881 EnqueueChildren(E);
1882 AddTypeLoc(E->getTypeSourceInfo());
1883}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001884void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1885 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1886 E = S->body_rend(); I != E; ++I) {
1887 AddStmt(*I);
1888 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001889}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001890void EnqueueVisitor::
1891VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1892 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1893 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001894 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1895 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001896 if (!E->isImplicitAccess())
1897 AddStmt(E->getBase());
1898}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001899void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1900 // Enqueue the initializer or constructor arguments.
1901 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1902 AddStmt(E->getConstructorArg(I-1));
1903 // Enqueue the array size, if any.
1904 AddStmt(E->getArraySize());
1905 // Enqueue the allocated type.
1906 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1907 // Enqueue the placement arguments.
1908 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1909 AddStmt(E->getPlacementArg(I-1));
1910}
Ted Kremenek28a71942010-11-13 00:36:47 +00001911void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001912 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1913 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001914 AddStmt(CE->getCallee());
1915 AddStmt(CE->getArg(0));
1916}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001917void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1918 // Visit the name of the type being destroyed.
1919 AddTypeLoc(E->getDestroyedTypeInfo());
1920 // Visit the scope type that looks disturbingly like the nested-name-specifier
1921 // but isn't.
1922 AddTypeLoc(E->getScopeTypeInfo());
1923 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001924 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1925 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001926 // Visit base expression.
1927 AddStmt(E->getBase());
1928}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001929void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1930 AddTypeLoc(E->getTypeSourceInfo());
1931}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001932void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1933 EnqueueChildren(E);
1934 AddTypeLoc(E->getTypeSourceInfo());
1935}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001936void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1937 EnqueueChildren(E);
1938 if (E->isTypeOperand())
1939 AddTypeLoc(E->getTypeOperandSourceInfo());
1940}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001941
1942void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1943 *E) {
1944 EnqueueChildren(E);
1945 AddTypeLoc(E->getTypeSourceInfo());
1946}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001947void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1948 EnqueueChildren(E);
1949 if (E->isTypeOperand())
1950 AddTypeLoc(E->getTypeOperandSourceInfo());
1951}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001952void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001953 if (DR->hasExplicitTemplateArgs()) {
1954 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1955 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001956 WL.push_back(DeclRefExprParts(DR, Parent));
1957}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001958void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1959 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1960 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001961 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001962}
Ted Kremenek035dc412010-11-13 00:36:50 +00001963void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1964 unsigned size = WL.size();
1965 bool isFirst = true;
1966 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1967 D != DEnd; ++D) {
1968 AddDecl(*D, isFirst);
1969 isFirst = false;
1970 }
1971 if (size == WL.size())
1972 return;
1973 // Now reverse the entries we just added. This will match the DFS
1974 // ordering performed by the worklist.
1975 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1976 std::reverse(I, E);
1977}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001978void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1979 AddStmt(E->getInit());
1980 typedef DesignatedInitExpr::Designator Designator;
1981 for (DesignatedInitExpr::reverse_designators_iterator
1982 D = E->designators_rbegin(), DEnd = E->designators_rend();
1983 D != DEnd; ++D) {
1984 if (D->isFieldDesignator()) {
1985 if (FieldDecl *Field = D->getField())
1986 AddMemberRef(Field, D->getFieldLoc());
1987 continue;
1988 }
1989 if (D->isArrayDesignator()) {
1990 AddStmt(E->getArrayIndex(*D));
1991 continue;
1992 }
1993 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1994 AddStmt(E->getArrayRangeEnd(*D));
1995 AddStmt(E->getArrayRangeStart(*D));
1996 }
1997}
Ted Kremenek28a71942010-11-13 00:36:47 +00001998void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1999 EnqueueChildren(E);
2000 AddTypeLoc(E->getTypeInfoAsWritten());
2001}
2002void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2003 AddStmt(FS->getBody());
2004 AddStmt(FS->getInc());
2005 AddStmt(FS->getCond());
2006 AddDecl(FS->getConditionVariable());
2007 AddStmt(FS->getInit());
2008}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002009void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2010 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2011}
Ted Kremenek28a71942010-11-13 00:36:47 +00002012void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2013 AddStmt(If->getElse());
2014 AddStmt(If->getThen());
2015 AddStmt(If->getCond());
2016 AddDecl(If->getConditionVariable());
2017}
2018void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2019 // We care about the syntactic form of the initializer list, only.
2020 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2021 IE = Syntactic;
2022 EnqueueChildren(IE);
2023}
2024void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002025 WL.push_back(MemberExprParts(M, Parent));
2026
2027 // If the base of the member access expression is an implicit 'this', don't
2028 // visit it.
2029 // FIXME: If we ever want to show these implicit accesses, this will be
2030 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002031 if (!M->isImplicitAccess())
2032 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002033}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002034void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2035 AddTypeLoc(E->getEncodedTypeSourceInfo());
2036}
Ted Kremenek28a71942010-11-13 00:36:47 +00002037void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2038 EnqueueChildren(M);
2039 AddTypeLoc(M->getClassReceiverTypeInfo());
2040}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002041void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2042 // Visit the components of the offsetof expression.
2043 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2044 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2045 const OffsetOfNode &Node = E->getComponent(I-1);
2046 switch (Node.getKind()) {
2047 case OffsetOfNode::Array:
2048 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2049 break;
2050 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002051 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002052 break;
2053 case OffsetOfNode::Identifier:
2054 case OffsetOfNode::Base:
2055 continue;
2056 }
2057 }
2058 // Visit the type into which we're computing the offset.
2059 AddTypeLoc(E->getTypeSourceInfo());
2060}
Ted Kremenek28a71942010-11-13 00:36:47 +00002061void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002062 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002063 WL.push_back(OverloadExprParts(E, Parent));
2064}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002065void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2066 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002067 EnqueueChildren(E);
2068 if (E->isArgumentType())
2069 AddTypeLoc(E->getArgumentTypeInfo());
2070}
Ted Kremenek28a71942010-11-13 00:36:47 +00002071void EnqueueVisitor::VisitStmt(Stmt *S) {
2072 EnqueueChildren(S);
2073}
2074void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2075 AddStmt(S->getBody());
2076 AddStmt(S->getCond());
2077 AddDecl(S->getConditionVariable());
2078}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002079
Ted Kremenek28a71942010-11-13 00:36:47 +00002080void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2081 AddStmt(W->getBody());
2082 AddStmt(W->getCond());
2083 AddDecl(W->getConditionVariable());
2084}
John Wiegley21ff2e52011-04-28 00:16:57 +00002085
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002086void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2087 AddTypeLoc(E->getQueriedTypeSourceInfo());
2088}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002089
2090void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002091 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002092 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002093}
2094
John Wiegley21ff2e52011-04-28 00:16:57 +00002095void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2096 AddTypeLoc(E->getQueriedTypeSourceInfo());
2097}
2098
John Wiegley55262202011-04-25 06:54:41 +00002099void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2100 EnqueueChildren(E);
2101}
2102
Ted Kremenek28a71942010-11-13 00:36:47 +00002103void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2104 VisitOverloadExpr(U);
2105 if (!U->isImplicitAccess())
2106 AddStmt(U->getBase());
2107}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002108void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2109 AddStmt(E->getSubExpr());
2110 AddTypeLoc(E->getWrittenTypeInfo());
2111}
Douglas Gregor94d96292011-01-19 20:34:17 +00002112void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2113 WL.push_back(SizeOfPackExprParts(E, Parent));
2114}
Ted Kremenek60458782010-11-12 21:34:16 +00002115
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002116void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002117 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002118}
2119
2120bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2121 if (RegionOfInterest.isValid()) {
2122 SourceRange Range = getRawCursorExtent(C);
2123 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2124 return false;
2125 }
2126 return true;
2127}
2128
2129bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2130 while (!WL.empty()) {
2131 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002132 VisitorJob LI = WL.back();
2133 WL.pop_back();
2134
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002135 // Set the Parent field, then back to its old value once we're done.
2136 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2137
2138 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002139 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002140 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002141 if (!D)
2142 continue;
2143
2144 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002145 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002146 return true;
2147
2148 continue;
2149 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002150 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2151 const ExplicitTemplateArgumentList *ArgList =
2152 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2153 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2154 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2155 Arg != ArgEnd; ++Arg) {
2156 if (VisitTemplateArgumentLoc(*Arg))
2157 return true;
2158 }
2159 continue;
2160 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002161 case VisitorJob::TypeLocVisitKind: {
2162 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002163 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002164 return true;
2165 continue;
2166 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002167 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002168 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002169 if (LabelStmt *stmt = LS->getStmt()) {
2170 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2171 TU))) {
2172 return true;
2173 }
2174 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002175 continue;
2176 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002177
Ted Kremenekf64d8032010-11-18 00:02:32 +00002178 case VisitorJob::NestedNameSpecifierVisitKind: {
2179 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2180 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2181 return true;
2182 continue;
2183 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002184
2185 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2186 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2187 if (VisitNestedNameSpecifierLoc(V->get()))
2188 return true;
2189 continue;
2190 }
2191
Ted Kremenekf64d8032010-11-18 00:02:32 +00002192 case VisitorJob::DeclarationNameInfoVisitKind: {
2193 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2194 ->get()))
2195 return true;
2196 continue;
2197 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002198 case VisitorJob::MemberRefVisitKind: {
2199 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2200 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2201 return true;
2202 continue;
2203 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002204 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002205 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002206 if (!S)
2207 continue;
2208
Ted Kremenekf1107452010-11-12 18:26:56 +00002209 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002210 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002211 if (!IsInRegionOfInterest(Cursor))
2212 continue;
2213 switch (Visitor(Cursor, Parent, ClientData)) {
2214 case CXChildVisit_Break: return true;
2215 case CXChildVisit_Continue: break;
2216 case CXChildVisit_Recurse:
2217 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002218 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002219 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002220 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002221 }
2222 case VisitorJob::MemberExprPartsKind: {
2223 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002224 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002225
2226 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002227 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2228 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002229 return true;
2230
2231 // Visit the declaration name.
2232 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2233 return true;
2234
2235 // Visit the explicitly-specified template arguments, if any.
2236 if (M->hasExplicitTemplateArgs()) {
2237 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2238 *ArgEnd = Arg + M->getNumTemplateArgs();
2239 Arg != ArgEnd; ++Arg) {
2240 if (VisitTemplateArgumentLoc(*Arg))
2241 return true;
2242 }
2243 }
2244 continue;
2245 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002246 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002247 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002248 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002249 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2250 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002251 return true;
2252 // Visit declaration name.
2253 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2254 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002255 continue;
2256 }
Ted Kremenek60458782010-11-12 21:34:16 +00002257 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002258 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002259 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002260 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2261 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002262 return true;
2263 // Visit the declaration name.
2264 if (VisitDeclarationNameInfo(O->getNameInfo()))
2265 return true;
2266 // Visit the overloaded declaration reference.
2267 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2268 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002269 continue;
2270 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002271 case VisitorJob::SizeOfPackExprPartsKind: {
2272 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2273 NamedDecl *Pack = E->getPack();
2274 if (isa<TemplateTypeParmDecl>(Pack)) {
2275 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2276 E->getPackLoc(), TU)))
2277 return true;
2278
2279 continue;
2280 }
2281
2282 if (isa<TemplateTemplateParmDecl>(Pack)) {
2283 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2284 E->getPackLoc(), TU)))
2285 return true;
2286
2287 continue;
2288 }
2289
2290 // Non-type template parameter packs and function parameter packs are
2291 // treated like DeclRefExpr cursors.
2292 continue;
2293 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002294 }
2295 }
2296 return false;
2297}
2298
Ted Kremenekcdba6592010-11-18 00:42:18 +00002299bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002300 VisitorWorkList *WL = 0;
2301 if (!WorkListFreeList.empty()) {
2302 WL = WorkListFreeList.back();
2303 WL->clear();
2304 WorkListFreeList.pop_back();
2305 }
2306 else {
2307 WL = new VisitorWorkList();
2308 WorkListCache.push_back(WL);
2309 }
2310 EnqueueWorkList(*WL, S);
2311 bool result = RunVisitorWorkList(*WL);
2312 WorkListFreeList.push_back(WL);
2313 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002314}
2315
2316//===----------------------------------------------------------------------===//
2317// Misc. API hooks.
2318//===----------------------------------------------------------------------===//
2319
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002320static llvm::sys::Mutex EnableMultithreadingMutex;
2321static bool EnabledMultithreading;
2322
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002323extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002324CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2325 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002326 // Disable pretty stack trace functionality, which will otherwise be a very
2327 // poor citizen of the world and set up all sorts of signal handlers.
2328 llvm::DisablePrettyStackTrace = true;
2329
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002330 // We use crash recovery to make some of our APIs more reliable, implicitly
2331 // enable it.
2332 llvm::CrashRecoveryContext::Enable();
2333
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002334 // Enable support for multithreading in LLVM.
2335 {
2336 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2337 if (!EnabledMultithreading) {
2338 llvm::llvm_start_multithreaded();
2339 EnabledMultithreading = true;
2340 }
2341 }
2342
Douglas Gregora030b7c2010-01-22 20:35:53 +00002343 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002344 if (excludeDeclarationsFromPCH)
2345 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002346 if (displayDiagnostics)
2347 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002348 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002349}
2350
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002351void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002352 if (CIdx)
2353 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002354}
2355
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002356void clang_toggleCrashRecovery(unsigned isEnabled) {
2357 if (isEnabled)
2358 llvm::CrashRecoveryContext::Enable();
2359 else
2360 llvm::CrashRecoveryContext::Disable();
2361}
2362
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002363CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002364 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002365 if (!CIdx)
2366 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002367
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002368 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002369 FileSystemOptions FileSystemOpts;
2370 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002371
Douglas Gregor28019772010-04-05 23:52:57 +00002372 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002373 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002374 CXXIdx->getOnlyLocalDecls(),
2375 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002376 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002377}
2378
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002379unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002380 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002381 CXTranslationUnit_CacheCompletionResults |
John McCallf85e1932011-06-15 23:02:42 +00002382 CXTranslationUnit_CXXPrecompiledPreamble |
2383 CXTranslationUnit_CXXChainedPCH;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002384}
2385
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002386CXTranslationUnit
2387clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2388 const char *source_filename,
2389 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002390 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002391 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002392 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002393 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002394 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002395 return clang_parseTranslationUnit(CIdx, source_filename,
2396 command_line_args, num_command_line_args,
2397 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002398 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002399}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002400
2401struct ParseTranslationUnitInfo {
2402 CXIndex CIdx;
2403 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002404 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002405 int num_command_line_args;
2406 struct CXUnsavedFile *unsaved_files;
2407 unsigned num_unsaved_files;
2408 unsigned options;
2409 CXTranslationUnit result;
2410};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002411static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002412 ParseTranslationUnitInfo *PTUI =
2413 static_cast<ParseTranslationUnitInfo*>(UserData);
2414 CXIndex CIdx = PTUI->CIdx;
2415 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002416 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002417 int num_command_line_args = PTUI->num_command_line_args;
2418 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2419 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2420 unsigned options = PTUI->options;
2421 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002422
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002423 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002424 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002426 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2427
Douglas Gregor44c181a2010-07-23 00:33:23 +00002428 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002429 bool CompleteTranslationUnit
2430 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002431 bool CacheCodeCompetionResults
2432 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002433 bool CXXPrecompilePreamble
2434 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2435 bool CXXChainedPCH
2436 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002437
Douglas Gregor5352ac02010-01-28 00:27:43 +00002438 // Configure the diagnostics.
2439 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002440 llvm::IntrusiveRefCntPtr<Diagnostic>
2441 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2442 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002443
Ted Kremenek25a11e12011-03-22 01:15:24 +00002444 // Recover resources if we crash before exiting this function.
2445 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2446 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2447 DiagCleanup(Diags.getPtr());
2448
2449 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2450 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2451
2452 // Recover resources if we crash before exiting this function.
2453 llvm::CrashRecoveryContextCleanupRegistrar<
2454 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2455
Douglas Gregor4db64a42010-01-23 00:14:00 +00002456 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002457 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002458 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002459 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002460 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2461 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002462 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002463
Ted Kremenek25a11e12011-03-22 01:15:24 +00002464 llvm::OwningPtr<std::vector<const char *> >
2465 Args(new std::vector<const char*>());
2466
2467 // Recover resources if we crash before exiting this method.
2468 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2469 ArgsCleanup(Args.get());
2470
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002471 // Since the Clang C library is primarily used by batch tools dealing with
2472 // (often very broken) source code, where spell-checking can have a
2473 // significant negative impact on performance (particularly when
2474 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002475 // Only do this if we haven't found a spell-checking-related argument.
2476 bool FoundSpellCheckingArgument = false;
2477 for (int I = 0; I != num_command_line_args; ++I) {
2478 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2479 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2480 FoundSpellCheckingArgument = true;
2481 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002482 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002483 }
2484 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002485 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002486
Ted Kremenek25a11e12011-03-22 01:15:24 +00002487 Args->insert(Args->end(), command_line_args,
2488 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002489
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002490 // The 'source_filename' argument is optional. If the caller does not
2491 // specify it then it is assumed that the source file is specified
2492 // in the actual argument list.
2493 // Put the source file after command_line_args otherwise if '-x' flag is
2494 // present it will be unused.
2495 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002496 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002497
Douglas Gregor44c181a2010-07-23 00:33:23 +00002498 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002499 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002500 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002501 Args->push_back("-Xclang");
2502 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002503 NestedMacroExpansions
2504 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002505 }
2506
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002507 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002508 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002509 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2510 /* vector::data() not portable */,
2511 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002512 Diags,
2513 CXXIdx->getClangResourcesPath(),
2514 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002515 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002516 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002517 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002518 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002519 PrecompilePreamble,
2520 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002521 CacheCodeCompetionResults,
2522 CXXPrecompilePreamble,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002523 CXXChainedPCH,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002524 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002525
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002526 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002527 // Make sure to check that 'Unit' is non-NULL.
2528 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2529 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2530 DEnd = Unit->stored_diag_end();
2531 D != DEnd; ++D) {
2532 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2533 CXString Msg = clang_formatDiagnostic(&Diag,
2534 clang_defaultDiagnosticDisplayOptions());
2535 fprintf(stderr, "%s\n", clang_getCString(Msg));
2536 clang_disposeString(Msg);
2537 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002538#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002539 // On Windows, force a flush, since there may be multiple copies of
2540 // stderr and stdout in the file system, all with different buffers
2541 // but writing to the same device.
2542 fflush(stderr);
2543#endif
2544 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002545 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002546
Ted Kremeneka60ed472010-11-16 08:15:36 +00002547 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002548}
2549CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2550 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002551 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002552 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002553 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002554 unsigned num_unsaved_files,
2555 unsigned options) {
2556 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002557 num_command_line_args, unsaved_files,
2558 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002559 llvm::CrashRecoveryContext CRC;
2560
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002561 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002562 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2563 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2564 fprintf(stderr, " 'command_line_args' : [");
2565 for (int i = 0; i != num_command_line_args; ++i) {
2566 if (i)
2567 fprintf(stderr, ", ");
2568 fprintf(stderr, "'%s'", command_line_args[i]);
2569 }
2570 fprintf(stderr, "],\n");
2571 fprintf(stderr, " 'unsaved_files' : [");
2572 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2573 if (i)
2574 fprintf(stderr, ", ");
2575 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2576 unsaved_files[i].Length);
2577 }
2578 fprintf(stderr, "],\n");
2579 fprintf(stderr, " 'options' : %d,\n", options);
2580 fprintf(stderr, "}\n");
2581
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002582 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002583 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2584 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002585 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002586
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002587 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002588}
2589
Douglas Gregor19998442010-08-13 15:35:05 +00002590unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2591 return CXSaveTranslationUnit_None;
2592}
2593
2594int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2595 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002596 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002597 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002598
Douglas Gregor39c411f2011-07-06 16:43:36 +00002599 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002600 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2601 PrintLibclangResourceUsage(TU);
2602 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002603}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002604
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002605void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002606 if (CTUnit) {
2607 // If the translation unit has been marked as unsafe to free, just discard
2608 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002609 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002610 return;
2611
Ted Kremeneka60ed472010-11-16 08:15:36 +00002612 delete static_cast<ASTUnit *>(CTUnit->TUData);
2613 disposeCXStringPool(CTUnit->StringPool);
2614 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002615 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002616}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002617
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002618unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2619 return CXReparse_None;
2620}
2621
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002622struct ReparseTranslationUnitInfo {
2623 CXTranslationUnit TU;
2624 unsigned num_unsaved_files;
2625 struct CXUnsavedFile *unsaved_files;
2626 unsigned options;
2627 int result;
2628};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002629
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002630static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002631 ReparseTranslationUnitInfo *RTUI =
2632 static_cast<ReparseTranslationUnitInfo*>(UserData);
2633 CXTranslationUnit TU = RTUI->TU;
2634 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2635 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2636 unsigned options = RTUI->options;
2637 (void) options;
2638 RTUI->result = 1;
2639
Douglas Gregorabc563f2010-07-19 21:46:24 +00002640 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002641 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002642
Ted Kremeneka60ed472010-11-16 08:15:36 +00002643 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002644 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002645
Ted Kremenek25a11e12011-03-22 01:15:24 +00002646 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2647 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2648
2649 // Recover resources if we crash before exiting this function.
2650 llvm::CrashRecoveryContextCleanupRegistrar<
2651 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2652
Douglas Gregorabc563f2010-07-19 21:46:24 +00002653 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2654 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2655 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002656 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002657 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2658 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002659 }
2660
Ted Kremenek4ee99262011-03-22 20:16:19 +00002661 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2662 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002663 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002664}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002665
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002666int clang_reparseTranslationUnit(CXTranslationUnit TU,
2667 unsigned num_unsaved_files,
2668 struct CXUnsavedFile *unsaved_files,
2669 unsigned options) {
2670 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2671 options, 0 };
2672 llvm::CrashRecoveryContext CRC;
2673
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002674 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002675 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002676 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002677 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002678 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2679 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002680
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002681 return RTUI.result;
2682}
2683
Douglas Gregordf95a132010-08-09 20:45:32 +00002684
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002685CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002686 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002687 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002688
Ted Kremeneka60ed472010-11-16 08:15:36 +00002689 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002690 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002691}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002692
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002693CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002694 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002695 return Result;
2696}
2697
Ted Kremenekfb480492010-01-13 21:46:36 +00002698} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002699
Ted Kremenekfb480492010-01-13 21:46:36 +00002700//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002701// CXSourceLocation and CXSourceRange Operations.
2702//===----------------------------------------------------------------------===//
2703
Douglas Gregorb9790342010-01-22 21:44:22 +00002704extern "C" {
2705CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002706 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002707 return Result;
2708}
2709
2710unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002711 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2712 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2713 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002714}
2715
2716CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2717 CXFile file,
2718 unsigned line,
2719 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002720 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002721 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002722
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002723 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002724 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002725 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002726 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002727 = CXXUnit->getSourceManager().getLocation(File, line, column);
2728 if (SLoc.isInvalid()) {
2729 if (Logging)
2730 llvm::errs() << "clang_getLocation(\"" << File->getName()
2731 << "\", " << line << ", " << column << ") = invalid\n";
2732 return clang_getNullLocation();
2733 }
2734
2735 if (Logging)
2736 llvm::errs() << "clang_getLocation(\"" << File->getName()
2737 << "\", " << line << ", " << column << ") = "
2738 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002739
2740 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2741}
2742
2743CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2744 CXFile file,
2745 unsigned offset) {
2746 if (!tu || !file)
2747 return clang_getNullLocation();
2748
Ted Kremeneka60ed472010-11-16 08:15:36 +00002749 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002750 SourceLocation Start
2751 = CXXUnit->getSourceManager().getLocation(
2752 static_cast<const FileEntry *>(file),
2753 1, 1);
2754 if (Start.isInvalid()) return clang_getNullLocation();
2755
2756 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2757
2758 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002759
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002760 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002761}
2762
Douglas Gregor5352ac02010-01-28 00:27:43 +00002763CXSourceRange clang_getNullRange() {
2764 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2765 return Result;
2766}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002767
Douglas Gregor5352ac02010-01-28 00:27:43 +00002768CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2769 if (begin.ptr_data[0] != end.ptr_data[0] ||
2770 begin.ptr_data[1] != end.ptr_data[1])
2771 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002772
2773 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002774 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002775 return Result;
2776}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002777} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002778
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002779static void createNullLocation(CXFile *file, unsigned *line,
2780 unsigned *column, unsigned *offset) {
2781 if (file)
2782 *file = 0;
2783 if (line)
2784 *line = 0;
2785 if (column)
2786 *column = 0;
2787 if (offset)
2788 *offset = 0;
2789 return;
2790}
2791
2792extern "C" {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002793void clang_getInstantiationLocation(CXSourceLocation location,
2794 CXFile *file,
2795 unsigned *line,
2796 unsigned *column,
2797 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002798 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2799
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002800 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002801 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002802 return;
2803 }
2804
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002805 const SourceManager &SM =
2806 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002807 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002808
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002809 // Check that the FileID is invalid on the instantiation location.
2810 // This can manifest in invalid code.
2811 FileID fileID = SM.getFileID(InstLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002812 bool Invalid = false;
2813 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2814 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002815 createNullLocation(file, line, column, offset);
2816 return;
2817 }
2818
Douglas Gregor1db19de2010-01-19 21:36:55 +00002819 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002820 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002821 if (line)
2822 *line = SM.getInstantiationLineNumber(InstLoc);
2823 if (column)
2824 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002825 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002826 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002827}
2828
Douglas Gregora9b06d42010-11-09 06:24:54 +00002829void clang_getSpellingLocation(CXSourceLocation location,
2830 CXFile *file,
2831 unsigned *line,
2832 unsigned *column,
2833 unsigned *offset) {
2834 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2835
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002836 if (!location.ptr_data[0] || Loc.isInvalid())
2837 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002838
2839 const SourceManager &SM =
2840 *static_cast<const SourceManager*>(location.ptr_data[0]);
2841 SourceLocation SpellLoc = Loc;
2842 if (SpellLoc.isMacroID()) {
2843 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2844 if (SimpleSpellingLoc.isFileID() &&
2845 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2846 SpellLoc = SimpleSpellingLoc;
2847 else
2848 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2849 }
2850
2851 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2852 FileID FID = LocInfo.first;
2853 unsigned FileOffset = LocInfo.second;
2854
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002855 if (FID.isInvalid())
2856 return createNullLocation(file, line, column, offset);
2857
Douglas Gregora9b06d42010-11-09 06:24:54 +00002858 if (file)
2859 *file = (void *)SM.getFileEntryForID(FID);
2860 if (line)
2861 *line = SM.getLineNumber(FID, FileOffset);
2862 if (column)
2863 *column = SM.getColumnNumber(FID, FileOffset);
2864 if (offset)
2865 *offset = FileOffset;
2866}
2867
Douglas Gregor1db19de2010-01-19 21:36:55 +00002868CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002869 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002870 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002871 return Result;
2872}
2873
2874CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002875 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002876 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002877 return Result;
2878}
2879
Douglas Gregorb9790342010-01-22 21:44:22 +00002880} // end: extern "C"
2881
Douglas Gregor1db19de2010-01-19 21:36:55 +00002882//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002883// CXFile Operations.
2884//===----------------------------------------------------------------------===//
2885
2886extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002887CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002888 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002889 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002890
Steve Naroff88145032009-10-27 14:35:18 +00002891 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002892 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002893}
2894
2895time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002896 if (!SFile)
2897 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002898
Steve Naroff88145032009-10-27 14:35:18 +00002899 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2900 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002901}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002902
Douglas Gregorb9790342010-01-22 21:44:22 +00002903CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2904 if (!tu)
2905 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002906
Ted Kremeneka60ed472010-11-16 08:15:36 +00002907 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002908
Douglas Gregorb9790342010-01-22 21:44:22 +00002909 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002910 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002911}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002912
Douglas Gregordd3e5542011-05-04 00:14:37 +00002913unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2914 if (!tu || !file)
2915 return 0;
2916
2917 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2918 FileEntry *FEnt = static_cast<FileEntry *>(file);
2919 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2920 .isFileMultipleIncludeGuarded(FEnt);
2921}
2922
Ted Kremenekfb480492010-01-13 21:46:36 +00002923} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002924
Ted Kremenekfb480492010-01-13 21:46:36 +00002925//===----------------------------------------------------------------------===//
2926// CXCursor Operations.
2927//===----------------------------------------------------------------------===//
2928
Ted Kremenekfb480492010-01-13 21:46:36 +00002929static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002930 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2931 return getDeclFromExpr(CE->getSubExpr());
2932
Ted Kremenekfb480492010-01-13 21:46:36 +00002933 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2934 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002935 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2936 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002937 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2938 return ME->getMemberDecl();
2939 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2940 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002941 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002942 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002943
Ted Kremenekfb480492010-01-13 21:46:36 +00002944 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2945 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002946 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2947 if (!CE->isElidable())
2948 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002949 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2950 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002951
Douglas Gregordb1314e2010-10-01 21:11:22 +00002952 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2953 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002954 if (SubstNonTypeTemplateParmPackExpr *NTTP
2955 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2956 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002957 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2958 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2959 isa<ParmVarDecl>(SizeOfPack->getPack()))
2960 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002961
Ted Kremenekfb480492010-01-13 21:46:36 +00002962 return 0;
2963}
2964
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002965static SourceLocation getLocationFromExpr(Expr *E) {
2966 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2967 return /*FIXME:*/Msg->getLeftLoc();
2968 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2969 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002970 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2971 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002972 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2973 return Member->getMemberLoc();
2974 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2975 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002976 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2977 return SizeOfPack->getPackLoc();
2978
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002979 return E->getLocStart();
2980}
2981
Ted Kremenekfb480492010-01-13 21:46:36 +00002982extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002983
2984unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002985 CXCursorVisitor visitor,
2986 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002987 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00002988 getCursorASTUnit(parent)->getMaxPCHLevel(),
2989 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002990 return CursorVis.VisitChildren(parent);
2991}
2992
David Chisnall3387c652010-11-03 14:12:26 +00002993#ifndef __has_feature
2994#define __has_feature(x) 0
2995#endif
2996#if __has_feature(blocks)
2997typedef enum CXChildVisitResult
2998 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2999
3000static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3001 CXClientData client_data) {
3002 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3003 return block(cursor, parent);
3004}
3005#else
3006// If we are compiled with a compiler that doesn't have native blocks support,
3007// define and call the block manually, so the
3008typedef struct _CXChildVisitResult
3009{
3010 void *isa;
3011 int flags;
3012 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003013 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3014 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003015} *CXCursorVisitorBlock;
3016
3017static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3018 CXClientData client_data) {
3019 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3020 return block->invoke(block, cursor, parent);
3021}
3022#endif
3023
3024
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003025unsigned clang_visitChildrenWithBlock(CXCursor parent,
3026 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003027 return clang_visitChildren(parent, visitWithBlock, block);
3028}
3029
Douglas Gregor78205d42010-01-20 21:45:58 +00003030static CXString getDeclSpelling(Decl *D) {
3031 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003032 if (!ND) {
3033 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3034 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3035 return createCXString(Property->getIdentifier()->getName());
3036
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003037 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003038 }
3039
Douglas Gregor78205d42010-01-20 21:45:58 +00003040 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003041 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003042
Douglas Gregor78205d42010-01-20 21:45:58 +00003043 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3044 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3045 // and returns different names. NamedDecl returns the class name and
3046 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003047 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003048
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003049 if (isa<UsingDirectiveDecl>(D))
3050 return createCXString("");
3051
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003052 llvm::SmallString<1024> S;
3053 llvm::raw_svector_ostream os(S);
3054 ND->printName(os);
3055
3056 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003057}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003058
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003059CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003060 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003061 return clang_getTranslationUnitSpelling(
3062 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003063
Steve Narofff334b4e2009-09-02 18:26:48 +00003064 if (clang_isReference(C.kind)) {
3065 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003066 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003067 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003068 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003069 }
3070 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003071 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003072 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003073 }
3074 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003075 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003076 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003077 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003078 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003079 case CXCursor_CXXBaseSpecifier: {
3080 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3081 return createCXString(B->getType().getAsString());
3082 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003083 case CXCursor_TypeRef: {
3084 TypeDecl *Type = getCursorTypeRef(C).first;
3085 assert(Type && "Missing type decl");
3086
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003087 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3088 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003089 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003090 case CXCursor_TemplateRef: {
3091 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003092 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003093
3094 return createCXString(Template->getNameAsString());
3095 }
Douglas Gregor69319002010-08-31 23:48:11 +00003096
3097 case CXCursor_NamespaceRef: {
3098 NamedDecl *NS = getCursorNamespaceRef(C).first;
3099 assert(NS && "Missing namespace decl");
3100
3101 return createCXString(NS->getNameAsString());
3102 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003103
Douglas Gregora67e03f2010-09-09 21:42:20 +00003104 case CXCursor_MemberRef: {
3105 FieldDecl *Field = getCursorMemberRef(C).first;
3106 assert(Field && "Missing member decl");
3107
3108 return createCXString(Field->getNameAsString());
3109 }
3110
Douglas Gregor36897b02010-09-10 00:22:18 +00003111 case CXCursor_LabelRef: {
3112 LabelStmt *Label = getCursorLabelRef(C).first;
3113 assert(Label && "Missing label");
3114
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003115 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003116 }
3117
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003118 case CXCursor_OverloadedDeclRef: {
3119 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3120 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3121 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3122 return createCXString(ND->getNameAsString());
3123 return createCXString("");
3124 }
3125 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3126 return createCXString(E->getName().getAsString());
3127 OverloadedTemplateStorage *Ovl
3128 = Storage.get<OverloadedTemplateStorage*>();
3129 if (Ovl->size() == 0)
3130 return createCXString("");
3131 return createCXString((*Ovl->begin())->getNameAsString());
3132 }
3133
Daniel Dunbaracca7252009-11-30 20:42:49 +00003134 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003135 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003136 }
3137 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003138
3139 if (clang_isExpression(C.kind)) {
3140 Decl *D = getDeclFromExpr(getCursorExpr(C));
3141 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003142 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003143 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003144 }
3145
Douglas Gregor36897b02010-09-10 00:22:18 +00003146 if (clang_isStatement(C.kind)) {
3147 Stmt *S = getCursorStmt(C);
3148 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003149 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003150
3151 return createCXString("");
3152 }
3153
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003154 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003155 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003156 ->getNameStart());
3157
Douglas Gregor572feb22010-03-18 18:04:21 +00003158 if (C.kind == CXCursor_MacroDefinition)
3159 return createCXString(getCursorMacroDefinition(C)->getName()
3160 ->getNameStart());
3161
Douglas Gregorecdcb882010-10-20 22:00:55 +00003162 if (C.kind == CXCursor_InclusionDirective)
3163 return createCXString(getCursorInclusionDirective(C)->getFileName());
3164
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003165 if (clang_isDeclaration(C.kind))
3166 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003167
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003168 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003169}
3170
Douglas Gregor358559d2010-10-02 22:49:11 +00003171CXString clang_getCursorDisplayName(CXCursor C) {
3172 if (!clang_isDeclaration(C.kind))
3173 return clang_getCursorSpelling(C);
3174
3175 Decl *D = getCursorDecl(C);
3176 if (!D)
3177 return createCXString("");
3178
3179 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3180 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3181 D = FunTmpl->getTemplatedDecl();
3182
3183 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3184 llvm::SmallString<64> Str;
3185 llvm::raw_svector_ostream OS(Str);
3186 OS << Function->getNameAsString();
3187 if (Function->getPrimaryTemplate())
3188 OS << "<>";
3189 OS << "(";
3190 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3191 if (I)
3192 OS << ", ";
3193 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3194 }
3195
3196 if (Function->isVariadic()) {
3197 if (Function->getNumParams())
3198 OS << ", ";
3199 OS << "...";
3200 }
3201 OS << ")";
3202 return createCXString(OS.str());
3203 }
3204
3205 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3206 llvm::SmallString<64> Str;
3207 llvm::raw_svector_ostream OS(Str);
3208 OS << ClassTemplate->getNameAsString();
3209 OS << "<";
3210 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3211 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3212 if (I)
3213 OS << ", ";
3214
3215 NamedDecl *Param = Params->getParam(I);
3216 if (Param->getIdentifier()) {
3217 OS << Param->getIdentifier()->getName();
3218 continue;
3219 }
3220
3221 // There is no parameter name, which makes this tricky. Try to come up
3222 // with something useful that isn't too long.
3223 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3224 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3225 else if (NonTypeTemplateParmDecl *NTTP
3226 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3227 OS << NTTP->getType().getAsString(Policy);
3228 else
3229 OS << "template<...> class";
3230 }
3231
3232 OS << ">";
3233 return createCXString(OS.str());
3234 }
3235
3236 if (ClassTemplateSpecializationDecl *ClassSpec
3237 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3238 // If the type was explicitly written, use that.
3239 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3240 return createCXString(TSInfo->getType().getAsString(Policy));
3241
3242 llvm::SmallString<64> Str;
3243 llvm::raw_svector_ostream OS(Str);
3244 OS << ClassSpec->getNameAsString();
3245 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003246 ClassSpec->getTemplateArgs().data(),
3247 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003248 Policy);
3249 return createCXString(OS.str());
3250 }
3251
3252 return clang_getCursorSpelling(C);
3253}
3254
Ted Kremeneke68fff62010-02-17 00:41:32 +00003255CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003256 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003257 case CXCursor_FunctionDecl:
3258 return createCXString("FunctionDecl");
3259 case CXCursor_TypedefDecl:
3260 return createCXString("TypedefDecl");
3261 case CXCursor_EnumDecl:
3262 return createCXString("EnumDecl");
3263 case CXCursor_EnumConstantDecl:
3264 return createCXString("EnumConstantDecl");
3265 case CXCursor_StructDecl:
3266 return createCXString("StructDecl");
3267 case CXCursor_UnionDecl:
3268 return createCXString("UnionDecl");
3269 case CXCursor_ClassDecl:
3270 return createCXString("ClassDecl");
3271 case CXCursor_FieldDecl:
3272 return createCXString("FieldDecl");
3273 case CXCursor_VarDecl:
3274 return createCXString("VarDecl");
3275 case CXCursor_ParmDecl:
3276 return createCXString("ParmDecl");
3277 case CXCursor_ObjCInterfaceDecl:
3278 return createCXString("ObjCInterfaceDecl");
3279 case CXCursor_ObjCCategoryDecl:
3280 return createCXString("ObjCCategoryDecl");
3281 case CXCursor_ObjCProtocolDecl:
3282 return createCXString("ObjCProtocolDecl");
3283 case CXCursor_ObjCPropertyDecl:
3284 return createCXString("ObjCPropertyDecl");
3285 case CXCursor_ObjCIvarDecl:
3286 return createCXString("ObjCIvarDecl");
3287 case CXCursor_ObjCInstanceMethodDecl:
3288 return createCXString("ObjCInstanceMethodDecl");
3289 case CXCursor_ObjCClassMethodDecl:
3290 return createCXString("ObjCClassMethodDecl");
3291 case CXCursor_ObjCImplementationDecl:
3292 return createCXString("ObjCImplementationDecl");
3293 case CXCursor_ObjCCategoryImplDecl:
3294 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003295 case CXCursor_CXXMethod:
3296 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003297 case CXCursor_UnexposedDecl:
3298 return createCXString("UnexposedDecl");
3299 case CXCursor_ObjCSuperClassRef:
3300 return createCXString("ObjCSuperClassRef");
3301 case CXCursor_ObjCProtocolRef:
3302 return createCXString("ObjCProtocolRef");
3303 case CXCursor_ObjCClassRef:
3304 return createCXString("ObjCClassRef");
3305 case CXCursor_TypeRef:
3306 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003307 case CXCursor_TemplateRef:
3308 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003309 case CXCursor_NamespaceRef:
3310 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003311 case CXCursor_MemberRef:
3312 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003313 case CXCursor_LabelRef:
3314 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003315 case CXCursor_OverloadedDeclRef:
3316 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003317 case CXCursor_UnexposedExpr:
3318 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003319 case CXCursor_BlockExpr:
3320 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003321 case CXCursor_DeclRefExpr:
3322 return createCXString("DeclRefExpr");
3323 case CXCursor_MemberRefExpr:
3324 return createCXString("MemberRefExpr");
3325 case CXCursor_CallExpr:
3326 return createCXString("CallExpr");
3327 case CXCursor_ObjCMessageExpr:
3328 return createCXString("ObjCMessageExpr");
3329 case CXCursor_UnexposedStmt:
3330 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003331 case CXCursor_LabelStmt:
3332 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003333 case CXCursor_InvalidFile:
3334 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003335 case CXCursor_InvalidCode:
3336 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003337 case CXCursor_NoDeclFound:
3338 return createCXString("NoDeclFound");
3339 case CXCursor_NotImplemented:
3340 return createCXString("NotImplemented");
3341 case CXCursor_TranslationUnit:
3342 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003343 case CXCursor_UnexposedAttr:
3344 return createCXString("UnexposedAttr");
3345 case CXCursor_IBActionAttr:
3346 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003347 case CXCursor_IBOutletAttr:
3348 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003349 case CXCursor_IBOutletCollectionAttr:
3350 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003351 case CXCursor_PreprocessingDirective:
3352 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003353 case CXCursor_MacroDefinition:
3354 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003355 case CXCursor_MacroExpansion:
3356 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003357 case CXCursor_InclusionDirective:
3358 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003359 case CXCursor_Namespace:
3360 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003361 case CXCursor_LinkageSpec:
3362 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003363 case CXCursor_CXXBaseSpecifier:
3364 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003365 case CXCursor_Constructor:
3366 return createCXString("CXXConstructor");
3367 case CXCursor_Destructor:
3368 return createCXString("CXXDestructor");
3369 case CXCursor_ConversionFunction:
3370 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003371 case CXCursor_TemplateTypeParameter:
3372 return createCXString("TemplateTypeParameter");
3373 case CXCursor_NonTypeTemplateParameter:
3374 return createCXString("NonTypeTemplateParameter");
3375 case CXCursor_TemplateTemplateParameter:
3376 return createCXString("TemplateTemplateParameter");
3377 case CXCursor_FunctionTemplate:
3378 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003379 case CXCursor_ClassTemplate:
3380 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003381 case CXCursor_ClassTemplatePartialSpecialization:
3382 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003383 case CXCursor_NamespaceAlias:
3384 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003385 case CXCursor_UsingDirective:
3386 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003387 case CXCursor_UsingDeclaration:
3388 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003389 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003390 return createCXString("TypeAliasDecl");
3391 case CXCursor_ObjCSynthesizeDecl:
3392 return createCXString("ObjCSynthesizeDecl");
3393 case CXCursor_ObjCDynamicDecl:
3394 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003395 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003396
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003397 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003398 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003399}
Steve Naroff89922f82009-08-31 00:59:03 +00003400
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003401struct GetCursorData {
3402 SourceLocation TokenBeginLoc;
3403 CXCursor &BestCursor;
3404
3405 GetCursorData(SourceLocation tokenBegin, CXCursor &outputCursor)
3406 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { }
3407};
3408
Ted Kremeneke68fff62010-02-17 00:41:32 +00003409enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3410 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003411 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003412 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3413 CXCursor *BestCursor = &Data->BestCursor;
3414
3415 if (clang_isExpression(cursor.kind) &&
3416 clang_isDeclaration(BestCursor->kind)) {
3417 Decl *D = getCursorDecl(*BestCursor);
3418
3419 // Avoid having the cursor of an expression replace the declaration cursor
3420 // when the expression source range overlaps the declaration range.
3421 // This can happen for C++ constructor expressions whose range generally
3422 // include the variable declaration, e.g.:
3423 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3424 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3425 D->getLocation() == Data->TokenBeginLoc)
3426 return CXChildVisit_Break;
3427 }
3428
Douglas Gregor93798e22010-11-05 21:11:19 +00003429 // If our current best cursor is the construction of a temporary object,
3430 // don't replace that cursor with a type reference, because we want
3431 // clang_getCursor() to point at the constructor.
3432 if (clang_isExpression(BestCursor->kind) &&
3433 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3434 cursor.kind == CXCursor_TypeRef)
3435 return CXChildVisit_Recurse;
3436
Douglas Gregor85fe1562010-12-10 07:23:11 +00003437 // Don't override a preprocessing cursor with another preprocessing
3438 // cursor; we want the outermost preprocessing cursor.
3439 if (clang_isPreprocessing(cursor.kind) &&
3440 clang_isPreprocessing(BestCursor->kind))
3441 return CXChildVisit_Recurse;
3442
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003443 *BestCursor = cursor;
3444 return CXChildVisit_Recurse;
3445}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003446
Douglas Gregorb9790342010-01-22 21:44:22 +00003447CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3448 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003449 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003450
Ted Kremeneka60ed472010-11-16 08:15:36 +00003451 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003452 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3453
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003454 // Translate the given source location to make it point at the beginning of
3455 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003456 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003457
3458 // Guard against an invalid SourceLocation, or we may assert in one
3459 // of the following calls.
3460 if (SLoc.isInvalid())
3461 return clang_getNullCursor();
3462
Douglas Gregor40749ee2010-11-03 00:35:38 +00003463 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003464 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3465 CXXUnit->getASTContext().getLangOptions());
3466
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003467 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3468 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003469 // FIXME: Would be great to have a "hint" cursor, then walk from that
3470 // hint cursor upward until we find a cursor whose source range encloses
3471 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003472 GetCursorData ResultData(SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003473 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003474 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003475 Decl::MaxPCHLevel, true, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003476 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003477 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003478
3479 if (Logging) {
3480 CXFile SearchFile;
3481 unsigned SearchLine, SearchColumn;
3482 CXFile ResultFile;
3483 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003484 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3485 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003486 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3487
3488 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3489 0);
3490 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3491 &ResultColumn, 0);
3492 SearchFileName = clang_getFileName(SearchFile);
3493 ResultFileName = clang_getFileName(ResultFile);
3494 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003495 USR = clang_getCursorUSR(Result);
3496 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003497 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3498 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003499 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3500 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003501 clang_disposeString(SearchFileName);
3502 clang_disposeString(ResultFileName);
3503 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003504 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003505
3506 CXCursor Definition = clang_getCursorDefinition(Result);
3507 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3508 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3509 CXString DefinitionKindSpelling
3510 = clang_getCursorKindSpelling(Definition.kind);
3511 CXFile DefinitionFile;
3512 unsigned DefinitionLine, DefinitionColumn;
3513 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3514 &DefinitionLine, &DefinitionColumn, 0);
3515 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3516 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3517 clang_getCString(DefinitionKindSpelling),
3518 clang_getCString(DefinitionFileName),
3519 DefinitionLine, DefinitionColumn);
3520 clang_disposeString(DefinitionFileName);
3521 clang_disposeString(DefinitionKindSpelling);
3522 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003523 }
3524
Ted Kremeneke68fff62010-02-17 00:41:32 +00003525 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003526}
3527
Ted Kremenek73885552009-11-17 19:28:59 +00003528CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003529 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003530}
3531
3532unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003533 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003534}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003535
Douglas Gregor9ce55842010-11-20 00:09:34 +00003536unsigned clang_hashCursor(CXCursor C) {
3537 unsigned Index = 0;
3538 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3539 Index = 1;
3540
3541 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3542 std::make_pair(C.kind, C.data[Index]));
3543}
3544
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003545unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003546 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3547}
3548
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003549unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003550 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3551}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003552
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003553unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003554 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3555}
3556
Douglas Gregor97b98722010-01-19 23:20:36 +00003557unsigned clang_isExpression(enum CXCursorKind K) {
3558 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3559}
3560
3561unsigned clang_isStatement(enum CXCursorKind K) {
3562 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3563}
3564
Douglas Gregor8be80e12011-07-06 03:00:34 +00003565unsigned clang_isAttribute(enum CXCursorKind K) {
3566 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3567}
3568
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003569unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3570 return K == CXCursor_TranslationUnit;
3571}
3572
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003573unsigned clang_isPreprocessing(enum CXCursorKind K) {
3574 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3575}
3576
Ted Kremenekad6eff62010-03-08 21:17:29 +00003577unsigned clang_isUnexposed(enum CXCursorKind K) {
3578 switch (K) {
3579 case CXCursor_UnexposedDecl:
3580 case CXCursor_UnexposedExpr:
3581 case CXCursor_UnexposedStmt:
3582 case CXCursor_UnexposedAttr:
3583 return true;
3584 default:
3585 return false;
3586 }
3587}
3588
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003589CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003590 return C.kind;
3591}
3592
Douglas Gregor98258af2010-01-18 22:46:11 +00003593CXSourceLocation clang_getCursorLocation(CXCursor C) {
3594 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003595 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003596 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003597 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3598 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003599 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003600 }
3601
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003602 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003603 std::pair<ObjCProtocolDecl *, SourceLocation> P
3604 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003605 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003606 }
3607
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003608 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003609 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3610 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003611 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003612 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003613
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003614 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003615 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003616 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003617 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003618
3619 case CXCursor_TemplateRef: {
3620 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3621 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3622 }
3623
Douglas Gregor69319002010-08-31 23:48:11 +00003624 case CXCursor_NamespaceRef: {
3625 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3626 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3627 }
3628
Douglas Gregora67e03f2010-09-09 21:42:20 +00003629 case CXCursor_MemberRef: {
3630 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3631 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3632 }
3633
Ted Kremenek3064ef92010-08-27 21:34:58 +00003634 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003635 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3636 if (!BaseSpec)
3637 return clang_getNullLocation();
3638
3639 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3640 return cxloc::translateSourceLocation(getCursorContext(C),
3641 TSInfo->getTypeLoc().getBeginLoc());
3642
3643 return cxloc::translateSourceLocation(getCursorContext(C),
3644 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003645 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003646
Douglas Gregor36897b02010-09-10 00:22:18 +00003647 case CXCursor_LabelRef: {
3648 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3649 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3650 }
3651
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003652 case CXCursor_OverloadedDeclRef:
3653 return cxloc::translateSourceLocation(getCursorContext(C),
3654 getCursorOverloadedDeclRef(C).second);
3655
Douglas Gregorf46034a2010-01-18 23:41:10 +00003656 default:
3657 // FIXME: Need a way to enumerate all non-reference cases.
3658 llvm_unreachable("Missed a reference kind");
3659 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003660 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003661
3662 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003663 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003664 getLocationFromExpr(getCursorExpr(C)));
3665
Douglas Gregor36897b02010-09-10 00:22:18 +00003666 if (clang_isStatement(C.kind))
3667 return cxloc::translateSourceLocation(getCursorContext(C),
3668 getCursorStmt(C)->getLocStart());
3669
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003670 if (C.kind == CXCursor_PreprocessingDirective) {
3671 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3672 return cxloc::translateSourceLocation(getCursorContext(C), L);
3673 }
Douglas Gregor48072312010-03-18 15:23:44 +00003674
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003675 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003676 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003677 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003678 return cxloc::translateSourceLocation(getCursorContext(C), L);
3679 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003680
3681 if (C.kind == CXCursor_MacroDefinition) {
3682 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3683 return cxloc::translateSourceLocation(getCursorContext(C), L);
3684 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003685
3686 if (C.kind == CXCursor_InclusionDirective) {
3687 SourceLocation L
3688 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3689 return cxloc::translateSourceLocation(getCursorContext(C), L);
3690 }
3691
Ted Kremenek9a700d22010-05-12 06:16:13 +00003692 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003693 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003694
Douglas Gregorf46034a2010-01-18 23:41:10 +00003695 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003696 SourceLocation Loc = D->getLocation();
3697 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3698 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003699 // FIXME: Multiple variables declared in a single declaration
3700 // currently lack the information needed to correctly determine their
3701 // ranges when accounting for the type-specifier. We use context
3702 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3703 // and if so, whether it is the first decl.
3704 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3705 if (!cxcursor::isFirstInDeclGroup(C))
3706 Loc = VD->getLocation();
3707 }
3708
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003709 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003710}
Douglas Gregora7bde202010-01-19 00:34:46 +00003711
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003712} // end extern "C"
3713
3714static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003715 if (clang_isReference(C.kind)) {
3716 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003717 case CXCursor_ObjCSuperClassRef:
3718 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003719
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003720 case CXCursor_ObjCProtocolRef:
3721 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003722
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003723 case CXCursor_ObjCClassRef:
3724 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003725
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003726 case CXCursor_TypeRef:
3727 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003728
3729 case CXCursor_TemplateRef:
3730 return getCursorTemplateRef(C).second;
3731
Douglas Gregor69319002010-08-31 23:48:11 +00003732 case CXCursor_NamespaceRef:
3733 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003734
3735 case CXCursor_MemberRef:
3736 return getCursorMemberRef(C).second;
3737
Ted Kremenek3064ef92010-08-27 21:34:58 +00003738 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003739 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003740
Douglas Gregor36897b02010-09-10 00:22:18 +00003741 case CXCursor_LabelRef:
3742 return getCursorLabelRef(C).second;
3743
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003744 case CXCursor_OverloadedDeclRef:
3745 return getCursorOverloadedDeclRef(C).second;
3746
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003747 default:
3748 // FIXME: Need a way to enumerate all non-reference cases.
3749 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003750 }
3751 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003752
3753 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003754 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003755
3756 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003757 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003758
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003759 if (C.kind == CXCursor_PreprocessingDirective)
3760 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003761
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003762 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003763 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003764
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003765 if (C.kind == CXCursor_MacroDefinition)
3766 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003767
3768 if (C.kind == CXCursor_InclusionDirective)
3769 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3770
Ted Kremenek007a7c92010-11-01 23:26:51 +00003771 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3772 Decl *D = cxcursor::getCursorDecl(C);
3773 SourceRange R = D->getSourceRange();
3774 // FIXME: Multiple variables declared in a single declaration
3775 // currently lack the information needed to correctly determine their
3776 // ranges when accounting for the type-specifier. We use context
3777 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3778 // and if so, whether it is the first decl.
3779 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3780 if (!cxcursor::isFirstInDeclGroup(C))
3781 R.setBegin(VD->getLocation());
3782 }
3783 return R;
3784 }
Douglas Gregor66537982010-11-17 17:14:07 +00003785 return SourceRange();
3786}
3787
3788/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3789/// the decl-specifier-seq for declarations.
3790static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3791 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3792 Decl *D = cxcursor::getCursorDecl(C);
3793 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003794
Douglas Gregor2494dd02011-03-01 01:34:45 +00003795 // Adjust the start of the location for declarations preceded by
3796 // declaration specifiers.
3797 SourceLocation StartLoc;
3798 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3799 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3800 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3801 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3802 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3803 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3804 }
3805
3806 if (StartLoc.isValid() && R.getBegin().isValid() &&
3807 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3808 R.setBegin(StartLoc);
3809
3810 // FIXME: Multiple variables declared in a single declaration
3811 // currently lack the information needed to correctly determine their
3812 // ranges when accounting for the type-specifier. We use context
3813 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3814 // and if so, whether it is the first decl.
3815 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3816 if (!cxcursor::isFirstInDeclGroup(C))
3817 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003818 }
3819
3820 return R;
3821 }
3822
3823 return getRawCursorExtent(C);
3824}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003825
3826extern "C" {
3827
3828CXSourceRange clang_getCursorExtent(CXCursor C) {
3829 SourceRange R = getRawCursorExtent(C);
3830 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003831 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003833 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003834}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003835
3836CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003837 if (clang_isInvalid(C.kind))
3838 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003839
Ted Kremeneka60ed472010-11-16 08:15:36 +00003840 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003841 if (clang_isDeclaration(C.kind)) {
3842 Decl *D = getCursorDecl(C);
3843 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003844 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003845 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003846 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003847 if (ObjCForwardProtocolDecl *Protocols
3848 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003849 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003850 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3851 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3852 return MakeCXCursor(Property, tu);
3853
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003854 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003855 }
3856
Douglas Gregor97b98722010-01-19 23:20:36 +00003857 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003858 Expr *E = getCursorExpr(C);
3859 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003860 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003861 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003862
3863 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003864 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003865
Douglas Gregor97b98722010-01-19 23:20:36 +00003866 return clang_getNullCursor();
3867 }
3868
Douglas Gregor36897b02010-09-10 00:22:18 +00003869 if (clang_isStatement(C.kind)) {
3870 Stmt *S = getCursorStmt(C);
3871 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003872 if (LabelDecl *label = Goto->getLabel())
3873 if (LabelStmt *labelS = label->getStmt())
3874 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003875
3876 return clang_getNullCursor();
3877 }
3878
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003879 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003880 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003881 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003882 }
3883
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003884 if (!clang_isReference(C.kind))
3885 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003886
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003887 switch (C.kind) {
3888 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003889 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003890
3891 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003892 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003893
3894 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003896
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003897 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003898 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003899
3900 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003901 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003902
Douglas Gregor69319002010-08-31 23:48:11 +00003903 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003904 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003905
Douglas Gregora67e03f2010-09-09 21:42:20 +00003906 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003907 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003908
Ted Kremenek3064ef92010-08-27 21:34:58 +00003909 case CXCursor_CXXBaseSpecifier: {
3910 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3911 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003912 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003913 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003914
Douglas Gregor36897b02010-09-10 00:22:18 +00003915 case CXCursor_LabelRef:
3916 // FIXME: We end up faking the "parent" declaration here because we
3917 // don't want to make CXCursor larger.
3918 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003919 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3920 .getTranslationUnitDecl(),
3921 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003922
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003923 case CXCursor_OverloadedDeclRef:
3924 return C;
3925
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003926 default:
3927 // We would prefer to enumerate all non-reference cursor kinds here.
3928 llvm_unreachable("Unhandled reference cursor kind");
3929 break;
3930 }
3931 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003932
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003933 return clang_getNullCursor();
3934}
3935
Douglas Gregorb6998662010-01-19 19:34:47 +00003936CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003937 if (clang_isInvalid(C.kind))
3938 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003939
Ted Kremeneka60ed472010-11-16 08:15:36 +00003940 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003941
Douglas Gregorb6998662010-01-19 19:34:47 +00003942 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003943 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003944 C = clang_getCursorReferenced(C);
3945 WasReference = true;
3946 }
3947
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003948 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003949 return clang_getCursorReferenced(C);
3950
Douglas Gregorb6998662010-01-19 19:34:47 +00003951 if (!clang_isDeclaration(C.kind))
3952 return clang_getNullCursor();
3953
3954 Decl *D = getCursorDecl(C);
3955 if (!D)
3956 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003957
Douglas Gregorb6998662010-01-19 19:34:47 +00003958 switch (D->getKind()) {
3959 // Declaration kinds that don't really separate the notions of
3960 // declaration and definition.
3961 case Decl::Namespace:
3962 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00003963 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003964 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00003965 case Decl::TemplateTypeParm:
3966 case Decl::EnumConstant:
3967 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003968 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003969 case Decl::ObjCIvar:
3970 case Decl::ObjCAtDefsField:
3971 case Decl::ImplicitParam:
3972 case Decl::ParmVar:
3973 case Decl::NonTypeTemplateParm:
3974 case Decl::TemplateTemplateParm:
3975 case Decl::ObjCCategoryImpl:
3976 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003977 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003978 case Decl::LinkageSpec:
3979 case Decl::ObjCPropertyImpl:
3980 case Decl::FileScopeAsm:
3981 case Decl::StaticAssert:
3982 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003983 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003984 return C;
3985
3986 // Declaration kinds that don't make any sense here, but are
3987 // nonetheless harmless.
3988 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003989 break;
3990
3991 // Declaration kinds for which the definition is not resolvable.
3992 case Decl::UnresolvedUsingTypename:
3993 case Decl::UnresolvedUsingValue:
3994 break;
3995
3996 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003997 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003998 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003999
4000 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004001 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004002
4003 case Decl::Enum:
4004 case Decl::Record:
4005 case Decl::CXXRecord:
4006 case Decl::ClassTemplateSpecialization:
4007 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004008 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004009 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004010 return clang_getNullCursor();
4011
4012 case Decl::Function:
4013 case Decl::CXXMethod:
4014 case Decl::CXXConstructor:
4015 case Decl::CXXDestructor:
4016 case Decl::CXXConversion: {
4017 const FunctionDecl *Def = 0;
4018 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004019 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004020 return clang_getNullCursor();
4021 }
4022
4023 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004024 // Ask the variable if it has a definition.
4025 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004026 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004027 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004028 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004029
Douglas Gregorb6998662010-01-19 19:34:47 +00004030 case Decl::FunctionTemplate: {
4031 const FunctionDecl *Def = 0;
4032 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004033 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004034 return clang_getNullCursor();
4035 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004036
Douglas Gregorb6998662010-01-19 19:34:47 +00004037 case Decl::ClassTemplate: {
4038 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004039 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004040 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004041 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004042 return clang_getNullCursor();
4043 }
4044
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004045 case Decl::Using:
4046 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004047 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004048
4049 case Decl::UsingShadow:
4050 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004051 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004052 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004053
4054 case Decl::ObjCMethod: {
4055 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4056 if (Method->isThisDeclarationADefinition())
4057 return C;
4058
4059 // Dig out the method definition in the associated
4060 // @implementation, if we have it.
4061 // FIXME: The ASTs should make finding the definition easier.
4062 if (ObjCInterfaceDecl *Class
4063 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4064 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4065 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4066 Method->isInstanceMethod()))
4067 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004068 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004069
4070 return clang_getNullCursor();
4071 }
4072
4073 case Decl::ObjCCategory:
4074 if (ObjCCategoryImplDecl *Impl
4075 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004076 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004077 return clang_getNullCursor();
4078
4079 case Decl::ObjCProtocol:
4080 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4081 return C;
4082 return clang_getNullCursor();
4083
4084 case Decl::ObjCInterface:
4085 // There are two notions of a "definition" for an Objective-C
4086 // class: the interface and its implementation. When we resolved a
4087 // reference to an Objective-C class, produce the @interface as
4088 // the definition; when we were provided with the interface,
4089 // produce the @implementation as the definition.
4090 if (WasReference) {
4091 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4092 return C;
4093 } else if (ObjCImplementationDecl *Impl
4094 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004095 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004096 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004097
Douglas Gregorb6998662010-01-19 19:34:47 +00004098 case Decl::ObjCProperty:
4099 // FIXME: We don't really know where to find the
4100 // ObjCPropertyImplDecls that implement this property.
4101 return clang_getNullCursor();
4102
4103 case Decl::ObjCCompatibleAlias:
4104 if (ObjCInterfaceDecl *Class
4105 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4106 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004107 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004108
Douglas Gregorb6998662010-01-19 19:34:47 +00004109 return clang_getNullCursor();
4110
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004111 case Decl::ObjCForwardProtocol:
4112 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004113 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004114
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004115 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004116 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004117 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004118
4119 case Decl::Friend:
4120 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004121 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004122 return clang_getNullCursor();
4123
4124 case Decl::FriendTemplate:
4125 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004126 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004127 return clang_getNullCursor();
4128 }
4129
4130 return clang_getNullCursor();
4131}
4132
4133unsigned clang_isCursorDefinition(CXCursor C) {
4134 if (!clang_isDeclaration(C.kind))
4135 return 0;
4136
4137 return clang_getCursorDefinition(C) == C;
4138}
4139
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004140CXCursor clang_getCanonicalCursor(CXCursor C) {
4141 if (!clang_isDeclaration(C.kind))
4142 return C;
4143
4144 if (Decl *D = getCursorDecl(C))
4145 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4146
4147 return C;
4148}
4149
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004150unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004151 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004152 return 0;
4153
4154 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4155 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4156 return E->getNumDecls();
4157
4158 if (OverloadedTemplateStorage *S
4159 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4160 return S->size();
4161
4162 Decl *D = Storage.get<Decl*>();
4163 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004164 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004165 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4166 return Classes->size();
4167 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4168 return Protocols->protocol_size();
4169
4170 return 0;
4171}
4172
4173CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004174 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004175 return clang_getNullCursor();
4176
4177 if (index >= clang_getNumOverloadedDecls(cursor))
4178 return clang_getNullCursor();
4179
Ted Kremeneka60ed472010-11-16 08:15:36 +00004180 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004181 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4182 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004183 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004184
4185 if (OverloadedTemplateStorage *S
4186 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004187 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004188
4189 Decl *D = Storage.get<Decl*>();
4190 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4191 // FIXME: This is, unfortunately, linear time.
4192 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4193 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004194 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004195 }
4196
4197 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004198 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004199
4200 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004201 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004202
4203 return clang_getNullCursor();
4204}
4205
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004206void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004207 const char **startBuf,
4208 const char **endBuf,
4209 unsigned *startLine,
4210 unsigned *startColumn,
4211 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004212 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004213 assert(getCursorDecl(C) && "CXCursor has null decl");
4214 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004215 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4216 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004217
Steve Naroff4ade6d62009-09-23 17:52:52 +00004218 SourceManager &SM = FD->getASTContext().getSourceManager();
4219 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4220 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4221 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4222 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4223 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4224 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4225}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004226
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004227void clang_enableStackTraces(void) {
4228 llvm::sys::PrintStackTraceOnErrorSignal();
4229}
4230
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004231void clang_executeOnThread(void (*fn)(void*), void *user_data,
4232 unsigned stack_size) {
4233 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4234}
4235
Ted Kremenekfb480492010-01-13 21:46:36 +00004236} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004237
Ted Kremenekfb480492010-01-13 21:46:36 +00004238//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004239// Token-based Operations.
4240//===----------------------------------------------------------------------===//
4241
4242/* CXToken layout:
4243 * int_data[0]: a CXTokenKind
4244 * int_data[1]: starting token location
4245 * int_data[2]: token length
4246 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004247 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004248 * otherwise unused.
4249 */
4250extern "C" {
4251
4252CXTokenKind clang_getTokenKind(CXToken CXTok) {
4253 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4254}
4255
4256CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4257 switch (clang_getTokenKind(CXTok)) {
4258 case CXToken_Identifier:
4259 case CXToken_Keyword:
4260 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004261 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4262 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004263
4264 case CXToken_Literal: {
4265 // We have stashed the starting pointer in the ptr_data field. Use it.
4266 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004267 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004268 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004269
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004270 case CXToken_Punctuation:
4271 case CXToken_Comment:
4272 break;
4273 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004274
4275 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004276 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004277 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004278 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004279 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004280
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004281 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4282 std::pair<FileID, unsigned> LocInfo
4283 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004284 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004285 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004286 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4287 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004288 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004289
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004290 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004291}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004292
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004293CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004294 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004295 if (!CXXUnit)
4296 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004297
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004298 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4299 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4300}
4301
4302CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004303 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004304 if (!CXXUnit)
4305 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004306
4307 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004308 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4309}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004310
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004311void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4312 CXToken **Tokens, unsigned *NumTokens) {
4313 if (Tokens)
4314 *Tokens = 0;
4315 if (NumTokens)
4316 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004317
Ted Kremeneka60ed472010-11-16 08:15:36 +00004318 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004319 if (!CXXUnit || !Tokens || !NumTokens)
4320 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004321
Douglas Gregorbdf60622010-03-05 21:16:25 +00004322 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4323
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004324 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004325 if (R.isInvalid())
4326 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004327
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004328 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4329 std::pair<FileID, unsigned> BeginLocInfo
4330 = SourceMgr.getDecomposedLoc(R.getBegin());
4331 std::pair<FileID, unsigned> EndLocInfo
4332 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004333
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004334 // Cannot tokenize across files.
4335 if (BeginLocInfo.first != EndLocInfo.first)
4336 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004337
4338 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004339 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004340 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004341 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004342 if (Invalid)
4343 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004344
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004345 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4346 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004347 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004348 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004349
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004350 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004351 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004352 llvm::SmallVector<CXToken, 32> CXTokens;
4353 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004354 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004355 do {
4356 // Lex the next token
4357 Lex.LexFromRawLexer(Tok);
4358 if (Tok.is(tok::eof))
4359 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004360
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004361 // Initialize the CXToken.
4362 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004363
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004364 // - Common fields
4365 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4366 CXTok.int_data[2] = Tok.getLength();
4367 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004368
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004369 // - Kind-specific fields
4370 if (Tok.isLiteral()) {
4371 CXTok.int_data[0] = CXToken_Literal;
4372 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004373 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004374 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004375 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004376 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004377
David Chisnall096428b2010-10-13 21:44:48 +00004378 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004379 CXTok.int_data[0] = CXToken_Keyword;
4380 }
4381 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004382 CXTok.int_data[0] = Tok.is(tok::identifier)
4383 ? CXToken_Identifier
4384 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004385 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386 CXTok.ptr_data = II;
4387 } else if (Tok.is(tok::comment)) {
4388 CXTok.int_data[0] = CXToken_Comment;
4389 CXTok.ptr_data = 0;
4390 } else {
4391 CXTok.int_data[0] = CXToken_Punctuation;
4392 CXTok.ptr_data = 0;
4393 }
4394 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004395 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004396 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004397
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004398 if (CXTokens.empty())
4399 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004400
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004401 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4402 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4403 *NumTokens = CXTokens.size();
4404}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004405
Ted Kremenek6db61092010-05-05 00:55:15 +00004406void clang_disposeTokens(CXTranslationUnit TU,
4407 CXToken *Tokens, unsigned NumTokens) {
4408 free(Tokens);
4409}
4410
4411} // end: extern "C"
4412
4413//===----------------------------------------------------------------------===//
4414// Token annotation APIs.
4415//===----------------------------------------------------------------------===//
4416
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004417typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004418static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4419 CXCursor parent,
4420 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004421namespace {
4422class AnnotateTokensWorker {
4423 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004424 CXToken *Tokens;
4425 CXCursor *Cursors;
4426 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004427 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004428 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004429 CursorVisitor AnnotateVis;
4430 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004431 bool HasContextSensitiveKeywords;
4432
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004433 bool MoreTokens() const { return TokIdx < NumTokens; }
4434 unsigned NextToken() const { return TokIdx; }
4435 void AdvanceToken() { ++TokIdx; }
4436 SourceLocation GetTokenLoc(unsigned tokI) {
4437 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4438 }
4439
Ted Kremenek6db61092010-05-05 00:55:15 +00004440public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004441 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004442 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004443 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004444 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004445 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004446 AnnotateVis(tu,
4447 AnnotateTokensVisitor, this,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00004448 Decl::MaxPCHLevel, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004449 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4450 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004451
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004452 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004453 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004454 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004455 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004456 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004457 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004458
4459 /// \brief Determine whether the annotator saw any cursors that have
4460 /// context-sensitive keywords.
4461 bool hasContextSensitiveKeywords() const {
4462 return HasContextSensitiveKeywords;
4463 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004464};
4465}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004466
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004467void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4468 // Walk the AST within the region of interest, annotating tokens
4469 // along the way.
4470 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004471
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004472 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4473 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004474 if (Pos != Annotated.end() &&
4475 (clang_isInvalid(Cursors[I].kind) ||
4476 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004477 Cursors[I] = Pos->second;
4478 }
4479
4480 // Finish up annotating any tokens left.
4481 if (!MoreTokens())
4482 return;
4483
4484 const CXCursor &C = clang_getNullCursor();
4485 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4486 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4487 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004488 }
4489}
4490
Ted Kremenek6db61092010-05-05 00:55:15 +00004491enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004492AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004493 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004494 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004495 if (cursorRange.isInvalid())
4496 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004497
4498 if (!HasContextSensitiveKeywords) {
4499 // Objective-C properties can have context-sensitive keywords.
4500 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4501 if (ObjCPropertyDecl *Property
4502 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4503 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4504 }
4505 // Objective-C methods can have context-sensitive keywords.
4506 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4507 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4508 if (ObjCMethodDecl *Method
4509 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4510 if (Method->getObjCDeclQualifier())
4511 HasContextSensitiveKeywords = true;
4512 else {
4513 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4514 PEnd = Method->param_end();
4515 P != PEnd; ++P) {
4516 if ((*P)->getObjCDeclQualifier()) {
4517 HasContextSensitiveKeywords = true;
4518 break;
4519 }
4520 }
4521 }
4522 }
4523 }
4524 // C++ methods can have context-sensitive keywords.
4525 else if (cursor.kind == CXCursor_CXXMethod) {
4526 if (CXXMethodDecl *Method
4527 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4528 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4529 HasContextSensitiveKeywords = true;
4530 }
4531 }
4532 // C++ classes can have context-sensitive keywords.
4533 else if (cursor.kind == CXCursor_StructDecl ||
4534 cursor.kind == CXCursor_ClassDecl ||
4535 cursor.kind == CXCursor_ClassTemplate ||
4536 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4537 if (Decl *D = getCursorDecl(cursor))
4538 if (D->hasAttr<FinalAttr>())
4539 HasContextSensitiveKeywords = true;
4540 }
4541 }
4542
Douglas Gregor4419b672010-10-21 06:10:04 +00004543 if (clang_isPreprocessing(cursor.kind)) {
4544 // For macro instantiations, just note where the beginning of the macro
4545 // instantiation occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004546 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004547 Annotated[Loc.int_data] = cursor;
4548 return CXChildVisit_Recurse;
4549 }
4550
Douglas Gregor4419b672010-10-21 06:10:04 +00004551 // Items in the preprocessing record are kept separate from items in
4552 // declarations, so we keep a separate token index.
4553 unsigned SavedTokIdx = TokIdx;
4554 TokIdx = PreprocessingTokIdx;
4555
4556 // Skip tokens up until we catch up to the beginning of the preprocessing
4557 // entry.
4558 while (MoreTokens()) {
4559 const unsigned I = NextToken();
4560 SourceLocation TokLoc = GetTokenLoc(I);
4561 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4562 case RangeBefore:
4563 AdvanceToken();
4564 continue;
4565 case RangeAfter:
4566 case RangeOverlap:
4567 break;
4568 }
4569 break;
4570 }
4571
4572 // Look at all of the tokens within this range.
4573 while (MoreTokens()) {
4574 const unsigned I = NextToken();
4575 SourceLocation TokLoc = GetTokenLoc(I);
4576 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4577 case RangeBefore:
4578 assert(0 && "Infeasible");
4579 case RangeAfter:
4580 break;
4581 case RangeOverlap:
4582 Cursors[I] = cursor;
4583 AdvanceToken();
4584 continue;
4585 }
4586 break;
4587 }
4588
4589 // Save the preprocessing token index; restore the non-preprocessing
4590 // token index.
4591 PreprocessingTokIdx = TokIdx;
4592 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004593 return CXChildVisit_Recurse;
4594 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004595
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004596 if (cursorRange.isInvalid())
4597 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004598
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004599 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4600
Ted Kremeneka333c662010-05-12 05:29:33 +00004601 // Adjust the annotated range based specific declarations.
4602 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4603 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004604 Decl *D = cxcursor::getCursorDecl(cursor);
4605 // Don't visit synthesized ObjC methods, since they have no syntatic
4606 // representation in the source.
4607 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4608 if (MD->isSynthesized())
4609 return CXChildVisit_Continue;
4610 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004611
4612 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004613 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004614 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4615 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4616 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4617 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4618 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004619 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004620
4621 if (StartLoc.isValid() && L.isValid() &&
4622 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4623 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004624 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004625
Ted Kremenek3f404602010-08-14 01:14:06 +00004626 // If the location of the cursor occurs within a macro instantiation, record
4627 // the spelling location of the cursor in our annotation map. We can then
4628 // paper over the token labelings during a post-processing step to try and
4629 // get cursor mappings for tokens that are the *arguments* of a macro
4630 // instantiation.
4631 if (L.isMacroID()) {
4632 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4633 // Only invalidate the old annotation if it isn't part of a preprocessing
4634 // directive. Here we assume that the default construction of CXCursor
4635 // results in CXCursor.kind being an initialized value (i.e., 0). If
4636 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004637
Ted Kremenek3f404602010-08-14 01:14:06 +00004638 CXCursor &oldC = Annotated[rawEncoding];
4639 if (!clang_isPreprocessing(oldC.kind))
4640 oldC = cursor;
4641 }
4642
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004643 const enum CXCursorKind K = clang_getCursorKind(parent);
4644 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004645 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4646 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004647
4648 while (MoreTokens()) {
4649 const unsigned I = NextToken();
4650 SourceLocation TokLoc = GetTokenLoc(I);
4651 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4652 case RangeBefore:
4653 Cursors[I] = updateC;
4654 AdvanceToken();
4655 continue;
4656 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004657 case RangeOverlap:
4658 break;
4659 }
4660 break;
4661 }
4662
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004663 // Avoid having the cursor of an expression "overwrite" the annotation of the
4664 // variable declaration that it belongs to.
4665 // This can happen for C++ constructor expressions whose range generally
4666 // include the variable declaration, e.g.:
4667 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4668 if (clang_isExpression(cursorK)) {
4669 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004670 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004671 const unsigned I = NextToken();
4672 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4673 E->getLocStart() == D->getLocation() &&
4674 E->getLocStart() == GetTokenLoc(I)) {
4675 Cursors[I] = updateC;
4676 AdvanceToken();
4677 }
4678 }
4679 }
4680
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004681 // Visit children to get their cursor information.
4682 const unsigned BeforeChildren = NextToken();
4683 VisitChildren(cursor);
4684 const unsigned AfterChildren = NextToken();
4685
4686 // Adjust 'Last' to the last token within the extent of the cursor.
4687 while (MoreTokens()) {
4688 const unsigned I = NextToken();
4689 SourceLocation TokLoc = GetTokenLoc(I);
4690 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4691 case RangeBefore:
4692 assert(0 && "Infeasible");
4693 case RangeAfter:
4694 break;
4695 case RangeOverlap:
4696 Cursors[I] = updateC;
4697 AdvanceToken();
4698 continue;
4699 }
4700 break;
4701 }
4702 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004703
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004704 // Scan the tokens that are at the beginning of the cursor, but are not
4705 // capture by the child cursors.
4706
4707 // For AST elements within macros, rely on a post-annotate pass to
4708 // to correctly annotate the tokens with cursors. Otherwise we can
4709 // get confusing results of having tokens that map to cursors that really
4710 // are expanded by an instantiation.
4711 if (L.isMacroID())
4712 cursor = clang_getNullCursor();
4713
4714 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4715 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4716 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004717
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004718 Cursors[I] = cursor;
4719 }
4720 // Scan the tokens that are at the end of the cursor, but are not captured
4721 // but the child cursors.
4722 for (unsigned I = AfterChildren; I != Last; ++I)
4723 Cursors[I] = cursor;
4724
4725 TokIdx = Last;
4726 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004727}
4728
Ted Kremenek6db61092010-05-05 00:55:15 +00004729static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4730 CXCursor parent,
4731 CXClientData client_data) {
4732 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4733}
4734
Ted Kremenek6628a612011-03-18 22:51:30 +00004735namespace {
4736 struct clang_annotateTokens_Data {
4737 CXTranslationUnit TU;
4738 ASTUnit *CXXUnit;
4739 CXToken *Tokens;
4740 unsigned NumTokens;
4741 CXCursor *Cursors;
4742 };
4743}
4744
Ted Kremenekab979612010-11-11 08:05:23 +00004745// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004746static void clang_annotateTokensImpl(void *UserData) {
4747 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4748 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4749 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4750 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4751 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4752
4753 // Determine the region of interest, which contains all of the tokens.
4754 SourceRange RegionOfInterest;
4755 RegionOfInterest.setBegin(
4756 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4757 RegionOfInterest.setEnd(
4758 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4759 Tokens[NumTokens-1])));
4760
4761 // A mapping from the source locations found when re-lexing or traversing the
4762 // region of interest to the corresponding cursors.
4763 AnnotateTokensData Annotated;
4764
4765 // Relex the tokens within the source range to look for preprocessing
4766 // directives.
4767 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4768 std::pair<FileID, unsigned> BeginLocInfo
4769 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4770 std::pair<FileID, unsigned> EndLocInfo
4771 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4772
4773 llvm::StringRef Buffer;
4774 bool Invalid = false;
4775 if (BeginLocInfo.first == EndLocInfo.first &&
4776 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4777 !Invalid) {
4778 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4779 CXXUnit->getASTContext().getLangOptions(),
4780 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4781 Buffer.end());
4782 Lex.SetCommentRetentionState(true);
4783
4784 // Lex tokens in raw mode until we hit the end of the range, to avoid
4785 // entering #includes or expanding macros.
4786 while (true) {
4787 Token Tok;
4788 Lex.LexFromRawLexer(Tok);
4789
4790 reprocess:
4791 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4792 // We have found a preprocessing directive. Gobble it up so that we
4793 // don't see it while preprocessing these tokens later, but keep track
4794 // of all of the token locations inside this preprocessing directive so
4795 // that we can annotate them appropriately.
4796 //
4797 // FIXME: Some simple tests here could identify macro definitions and
4798 // #undefs, to provide specific cursor kinds for those.
4799 llvm::SmallVector<SourceLocation, 32> Locations;
4800 do {
4801 Locations.push_back(Tok.getLocation());
4802 Lex.LexFromRawLexer(Tok);
4803 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4804
4805 using namespace cxcursor;
4806 CXCursor Cursor
4807 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4808 Locations.back()),
4809 TU);
4810 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4811 Annotated[Locations[I].getRawEncoding()] = Cursor;
4812 }
4813
4814 if (Tok.isAtStartOfLine())
4815 goto reprocess;
4816
4817 continue;
4818 }
4819
4820 if (Tok.is(tok::eof))
4821 break;
4822 }
4823 }
4824
4825 // Annotate all of the source locations in the region of interest that map to
4826 // a specific cursor.
4827 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4828 TU, RegionOfInterest);
4829
4830 // FIXME: We use a ridiculous stack size here because the data-recursion
4831 // algorithm uses a large stack frame than the non-data recursive version,
4832 // and AnnotationTokensWorker currently transforms the data-recursion
4833 // algorithm back into a traditional recursion by explicitly calling
4834 // VisitChildren(). We will need to remove this explicit recursive call.
4835 W.AnnotateTokens();
4836
4837 // If we ran into any entities that involve context-sensitive keywords,
4838 // take another pass through the tokens to mark them as such.
4839 if (W.hasContextSensitiveKeywords()) {
4840 for (unsigned I = 0; I != NumTokens; ++I) {
4841 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4842 continue;
4843
4844 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4845 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4846 if (ObjCPropertyDecl *Property
4847 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4848 if (Property->getPropertyAttributesAsWritten() != 0 &&
4849 llvm::StringSwitch<bool>(II->getName())
4850 .Case("readonly", true)
4851 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00004852 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004853 .Case("readwrite", true)
4854 .Case("retain", true)
4855 .Case("copy", true)
4856 .Case("nonatomic", true)
4857 .Case("atomic", true)
4858 .Case("getter", true)
4859 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00004860 .Case("strong", true)
4861 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00004862 .Default(false))
4863 Tokens[I].int_data[0] = CXToken_Keyword;
4864 }
4865 continue;
4866 }
4867
4868 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
4869 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
4870 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4871 if (llvm::StringSwitch<bool>(II->getName())
4872 .Case("in", true)
4873 .Case("out", true)
4874 .Case("inout", true)
4875 .Case("oneway", true)
4876 .Case("bycopy", true)
4877 .Case("byref", true)
4878 .Default(false))
4879 Tokens[I].int_data[0] = CXToken_Keyword;
4880 continue;
4881 }
4882
4883 if (Cursors[I].kind == CXCursor_CXXMethod) {
4884 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4885 if (CXXMethodDecl *Method
4886 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
4887 if ((Method->hasAttr<FinalAttr>() ||
4888 Method->hasAttr<OverrideAttr>()) &&
4889 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
4890 llvm::StringSwitch<bool>(II->getName())
4891 .Case("final", true)
4892 .Case("override", true)
4893 .Default(false))
4894 Tokens[I].int_data[0] = CXToken_Keyword;
4895 }
4896 continue;
4897 }
4898
4899 if (Cursors[I].kind == CXCursor_ClassDecl ||
4900 Cursors[I].kind == CXCursor_StructDecl ||
4901 Cursors[I].kind == CXCursor_ClassTemplate) {
4902 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4903 if (II->getName() == "final") {
4904 // We have to be careful with 'final', since it could be the name
4905 // of a member class rather than the context-sensitive keyword.
4906 // So, check whether the cursor associated with this
4907 Decl *D = getCursorDecl(Cursors[I]);
4908 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
4909 if ((Record->hasAttr<FinalAttr>()) &&
4910 Record->getIdentifier() != II)
4911 Tokens[I].int_data[0] = CXToken_Keyword;
4912 } else if (ClassTemplateDecl *ClassTemplate
4913 = dyn_cast_or_null<ClassTemplateDecl>(D)) {
4914 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
4915 if ((Record->hasAttr<FinalAttr>()) &&
4916 Record->getIdentifier() != II)
4917 Tokens[I].int_data[0] = CXToken_Keyword;
4918 }
4919 }
4920 continue;
4921 }
4922 }
4923 }
Ted Kremenekab979612010-11-11 08:05:23 +00004924}
4925
Ted Kremenek6db61092010-05-05 00:55:15 +00004926extern "C" {
4927
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004928void clang_annotateTokens(CXTranslationUnit TU,
4929 CXToken *Tokens, unsigned NumTokens,
4930 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004931
4932 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004933 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004934
Douglas Gregor4419b672010-10-21 06:10:04 +00004935 // Any token we don't specifically annotate will have a NULL cursor.
4936 CXCursor C = clang_getNullCursor();
4937 for (unsigned I = 0; I != NumTokens; ++I)
4938 Cursors[I] = C;
4939
Ted Kremeneka60ed472010-11-16 08:15:36 +00004940 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004941 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004942 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004943
Douglas Gregorbdf60622010-03-05 21:16:25 +00004944 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00004945
4946 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00004947 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00004948 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004949 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004950 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4951 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004952}
Ted Kremenek6628a612011-03-18 22:51:30 +00004953
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004954} // end: extern "C"
4955
4956//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004957// Operations for querying linkage of a cursor.
4958//===----------------------------------------------------------------------===//
4959
4960extern "C" {
4961CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004962 if (!clang_isDeclaration(cursor.kind))
4963 return CXLinkage_Invalid;
4964
Ted Kremenek16b42592010-03-03 06:36:57 +00004965 Decl *D = cxcursor::getCursorDecl(cursor);
4966 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4967 switch (ND->getLinkage()) {
4968 case NoLinkage: return CXLinkage_NoLinkage;
4969 case InternalLinkage: return CXLinkage_Internal;
4970 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4971 case ExternalLinkage: return CXLinkage_External;
4972 };
4973
4974 return CXLinkage_Invalid;
4975}
4976} // end: extern "C"
4977
4978//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004979// Operations for querying language of a cursor.
4980//===----------------------------------------------------------------------===//
4981
4982static CXLanguageKind getDeclLanguage(const Decl *D) {
4983 switch (D->getKind()) {
4984 default:
4985 break;
4986 case Decl::ImplicitParam:
4987 case Decl::ObjCAtDefsField:
4988 case Decl::ObjCCategory:
4989 case Decl::ObjCCategoryImpl:
4990 case Decl::ObjCClass:
4991 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004992 case Decl::ObjCForwardProtocol:
4993 case Decl::ObjCImplementation:
4994 case Decl::ObjCInterface:
4995 case Decl::ObjCIvar:
4996 case Decl::ObjCMethod:
4997 case Decl::ObjCProperty:
4998 case Decl::ObjCPropertyImpl:
4999 case Decl::ObjCProtocol:
5000 return CXLanguage_ObjC;
5001 case Decl::CXXConstructor:
5002 case Decl::CXXConversion:
5003 case Decl::CXXDestructor:
5004 case Decl::CXXMethod:
5005 case Decl::CXXRecord:
5006 case Decl::ClassTemplate:
5007 case Decl::ClassTemplatePartialSpecialization:
5008 case Decl::ClassTemplateSpecialization:
5009 case Decl::Friend:
5010 case Decl::FriendTemplate:
5011 case Decl::FunctionTemplate:
5012 case Decl::LinkageSpec:
5013 case Decl::Namespace:
5014 case Decl::NamespaceAlias:
5015 case Decl::NonTypeTemplateParm:
5016 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005017 case Decl::TemplateTemplateParm:
5018 case Decl::TemplateTypeParm:
5019 case Decl::UnresolvedUsingTypename:
5020 case Decl::UnresolvedUsingValue:
5021 case Decl::Using:
5022 case Decl::UsingDirective:
5023 case Decl::UsingShadow:
5024 return CXLanguage_CPlusPlus;
5025 }
5026
5027 return CXLanguage_C;
5028}
5029
5030extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005031
5032enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5033 if (clang_isDeclaration(cursor.kind))
5034 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005035 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005036 return CXAvailability_Available;
5037
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005038 switch (D->getAvailability()) {
5039 case AR_Available:
5040 case AR_NotYetIntroduced:
5041 return CXAvailability_Available;
5042
5043 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005044 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005045
5046 case AR_Unavailable:
5047 return CXAvailability_NotAvailable;
5048 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005049 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005050
Douglas Gregor58ddb602010-08-23 23:00:57 +00005051 return CXAvailability_Available;
5052}
5053
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005054CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5055 if (clang_isDeclaration(cursor.kind))
5056 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5057
5058 return CXLanguage_Invalid;
5059}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005060
5061 /// \brief If the given cursor is the "templated" declaration
5062 /// descibing a class or function template, return the class or
5063 /// function template.
5064static Decl *maybeGetTemplateCursor(Decl *D) {
5065 if (!D)
5066 return 0;
5067
5068 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5069 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5070 return FunTmpl;
5071
5072 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5073 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5074 return ClassTmpl;
5075
5076 return D;
5077}
5078
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005079CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5080 if (clang_isDeclaration(cursor.kind)) {
5081 if (Decl *D = getCursorDecl(cursor)) {
5082 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005083 if (!DC)
5084 return clang_getNullCursor();
5085
5086 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5087 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005088 }
5089 }
5090
5091 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5092 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005093 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005094 }
5095
5096 return clang_getNullCursor();
5097}
5098
5099CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5100 if (clang_isDeclaration(cursor.kind)) {
5101 if (Decl *D = getCursorDecl(cursor)) {
5102 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005103 if (!DC)
5104 return clang_getNullCursor();
5105
5106 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5107 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005108 }
5109 }
5110
5111 // FIXME: Note that we can't easily compute the lexical context of a
5112 // statement or expression, so we return nothing.
5113 return clang_getNullCursor();
5114}
5115
Douglas Gregor9f592342010-10-01 20:25:15 +00005116static void CollectOverriddenMethods(DeclContext *Ctx,
5117 ObjCMethodDecl *Method,
5118 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5119 if (!Ctx)
5120 return;
5121
5122 // If we have a class or category implementation, jump straight to the
5123 // interface.
5124 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5125 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5126
5127 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5128 if (!Container)
5129 return;
5130
5131 // Check whether we have a matching method at this level.
5132 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5133 Method->isInstanceMethod()))
5134 if (Method != Overridden) {
5135 // We found an override at this level; there is no need to look
5136 // into other protocols or categories.
5137 Methods.push_back(Overridden);
5138 return;
5139 }
5140
5141 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5142 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5143 PEnd = Protocol->protocol_end();
5144 P != PEnd; ++P)
5145 CollectOverriddenMethods(*P, Method, Methods);
5146 }
5147
5148 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5149 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5150 PEnd = Category->protocol_end();
5151 P != PEnd; ++P)
5152 CollectOverriddenMethods(*P, Method, Methods);
5153 }
5154
5155 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5156 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5157 PEnd = Interface->protocol_end();
5158 P != PEnd; ++P)
5159 CollectOverriddenMethods(*P, Method, Methods);
5160
5161 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5162 Category; Category = Category->getNextClassCategory())
5163 CollectOverriddenMethods(Category, Method, Methods);
5164
5165 // We only look into the superclass if we haven't found anything yet.
5166 if (Methods.empty())
5167 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5168 return CollectOverriddenMethods(Super, Method, Methods);
5169 }
5170}
5171
5172void clang_getOverriddenCursors(CXCursor cursor,
5173 CXCursor **overridden,
5174 unsigned *num_overridden) {
5175 if (overridden)
5176 *overridden = 0;
5177 if (num_overridden)
5178 *num_overridden = 0;
5179 if (!overridden || !num_overridden)
5180 return;
5181
5182 if (!clang_isDeclaration(cursor.kind))
5183 return;
5184
5185 Decl *D = getCursorDecl(cursor);
5186 if (!D)
5187 return;
5188
5189 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005190 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005191 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5192 *num_overridden = CXXMethod->size_overridden_methods();
5193 if (!*num_overridden)
5194 return;
5195
5196 *overridden = new CXCursor [*num_overridden];
5197 unsigned I = 0;
5198 for (CXXMethodDecl::method_iterator
5199 M = CXXMethod->begin_overridden_methods(),
5200 MEnd = CXXMethod->end_overridden_methods();
5201 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005202 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005203 return;
5204 }
5205
5206 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5207 if (!Method)
5208 return;
5209
5210 // Handle Objective-C methods.
5211 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
5212 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5213
5214 if (Methods.empty())
5215 return;
5216
5217 *num_overridden = Methods.size();
5218 *overridden = new CXCursor [Methods.size()];
5219 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005220 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005221}
5222
5223void clang_disposeOverriddenCursors(CXCursor *overridden) {
5224 delete [] overridden;
5225}
5226
Douglas Gregorecdcb882010-10-20 22:00:55 +00005227CXFile clang_getIncludedFile(CXCursor cursor) {
5228 if (cursor.kind != CXCursor_InclusionDirective)
5229 return 0;
5230
5231 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5232 return (void *)ID->getFile();
5233}
5234
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005235} // end: extern "C"
5236
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005237
5238//===----------------------------------------------------------------------===//
5239// C++ AST instrospection.
5240//===----------------------------------------------------------------------===//
5241
5242extern "C" {
5243unsigned clang_CXXMethod_isStatic(CXCursor C) {
5244 if (!clang_isDeclaration(C.kind))
5245 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005246
5247 CXXMethodDecl *Method = 0;
5248 Decl *D = cxcursor::getCursorDecl(C);
5249 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5250 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5251 else
5252 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5253 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005254}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005255
Douglas Gregor211924b2011-05-12 15:17:24 +00005256unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5257 if (!clang_isDeclaration(C.kind))
5258 return 0;
5259
5260 CXXMethodDecl *Method = 0;
5261 Decl *D = cxcursor::getCursorDecl(C);
5262 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5263 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5264 else
5265 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5266 return (Method && Method->isVirtual()) ? 1 : 0;
5267}
5268
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005269} // end: extern "C"
5270
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005271//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005272// Attribute introspection.
5273//===----------------------------------------------------------------------===//
5274
5275extern "C" {
5276CXType clang_getIBOutletCollectionType(CXCursor C) {
5277 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005278 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005279
5280 IBOutletCollectionAttr *A =
5281 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5282
Douglas Gregor841b2382011-03-06 18:55:32 +00005283 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005284}
5285} // end: extern "C"
5286
5287//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005288// Inspecting memory usage.
5289//===----------------------------------------------------------------------===//
5290
Ted Kremenekf7870022011-04-20 16:41:07 +00005291typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005292
Ted Kremenekf7870022011-04-20 16:41:07 +00005293static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5294 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005295 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005296 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005297 entries.push_back(entry);
5298}
5299
5300extern "C" {
5301
Ted Kremenekf7870022011-04-20 16:41:07 +00005302const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005303 const char *str = "";
5304 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005305 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005306 str = "ASTContext: expressions, declarations, and types";
5307 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005308 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005309 str = "ASTContext: identifiers";
5310 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005311 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005312 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005313 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005314 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005315 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005316 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005317 case CXTUResourceUsage_SourceManagerContentCache:
5318 str = "SourceManager: content cache allocator";
5319 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005320 case CXTUResourceUsage_AST_SideTables:
5321 str = "ASTContext: side tables";
5322 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005323 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5324 str = "SourceManager: malloc'ed memory buffers";
5325 break;
5326 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5327 str = "SourceManager: mmap'ed memory buffers";
5328 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005329 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5330 str = "ExternalASTSource: malloc'ed memory buffers";
5331 break;
5332 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5333 str = "ExternalASTSource: mmap'ed memory buffers";
5334 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005335 case CXTUResourceUsage_Preprocessor:
5336 str = "Preprocessor: malloc'ed memory";
5337 break;
5338 case CXTUResourceUsage_PreprocessingRecord:
5339 str = "Preprocessor: PreprocessingRecord";
5340 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005341 }
5342 return str;
5343}
5344
Ted Kremenekf7870022011-04-20 16:41:07 +00005345CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005346 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005347 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005348 return usage;
5349 }
5350
5351 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5352 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5353 ASTContext &astContext = astUnit->getASTContext();
5354
5355 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005356 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005357 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005358
5359 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005360 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005361 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5362
5363 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005364 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005365 (unsigned long) astContext.Selectors.getTotalMemory());
5366
Ted Kremenekba29bd22011-04-28 04:53:38 +00005367 // How much memory is used by ASTContext's side tables?
5368 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5369 (unsigned long) astContext.getSideTableAllocatedMemory());
5370
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005371 // How much memory is used for caching global code completion results?
5372 unsigned long completionBytes = 0;
5373 if (GlobalCodeCompletionAllocator *completionAllocator =
5374 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005375 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005376 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005377 createCXTUResourceUsageEntry(*entries,
5378 CXTUResourceUsage_GlobalCompletionResults,
5379 completionBytes);
5380
5381 // How much memory is being used by SourceManager's content cache?
5382 createCXTUResourceUsageEntry(*entries,
5383 CXTUResourceUsage_SourceManagerContentCache,
5384 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005385
5386 // How much memory is being used by the MemoryBuffer's in SourceManager?
5387 const SourceManager::MemoryBufferSizes &srcBufs =
5388 astUnit->getSourceManager().getMemoryBufferSizes();
5389
5390 createCXTUResourceUsageEntry(*entries,
5391 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5392 (unsigned long) srcBufs.malloc_bytes);
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005393 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005394 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5395 (unsigned long) srcBufs.mmap_bytes);
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005396
5397 // How much memory is being used by the ExternalASTSource?
5398 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5399 const ExternalASTSource::MemoryBufferSizes &sizes =
5400 esrc->getMemoryBufferSizes();
5401
5402 createCXTUResourceUsageEntry(*entries,
5403 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5404 (unsigned long) sizes.malloc_bytes);
5405 createCXTUResourceUsageEntry(*entries,
5406 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5407 (unsigned long) sizes.mmap_bytes);
5408 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005409
5410 // How much memory is being used by the Preprocessor?
5411 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005412 createCXTUResourceUsageEntry(*entries,
5413 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005414 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005415
5416 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5417 createCXTUResourceUsageEntry(*entries,
5418 CXTUResourceUsage_PreprocessingRecord,
5419 pRec->getTotalMemory());
5420 }
5421
5422
Ted Kremenekf7870022011-04-20 16:41:07 +00005423 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005424 (unsigned) entries->size(),
5425 entries->size() ? &(*entries)[0] : 0 };
5426 entries.take();
5427 return usage;
5428}
5429
Ted Kremenekf7870022011-04-20 16:41:07 +00005430void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005431 if (usage.data)
5432 delete (MemUsageEntries*) usage.data;
5433}
5434
5435} // end extern "C"
5436
Douglas Gregor6df78732011-05-05 20:27:22 +00005437void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5438 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5439 for (unsigned I = 0; I != Usage.numEntries; ++I)
5440 fprintf(stderr, " %s: %lu\n",
5441 clang_getTUResourceUsageName(Usage.entries[I].kind),
5442 Usage.entries[I].amount);
5443
5444 clang_disposeCXTUResourceUsage(Usage);
5445}
5446
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005447//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005448// Misc. utility functions.
5449//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005450
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005451/// Default to using an 8 MB stack size on "safety" threads.
5452static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005453
5454namespace clang {
5455
5456bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005457 void (*Fn)(void*), void *UserData,
5458 unsigned Size) {
5459 if (!Size)
5460 Size = GetSafetyThreadStackSize();
5461 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005462 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5463 return CRC.RunSafely(Fn, UserData);
5464}
5465
5466unsigned GetSafetyThreadStackSize() {
5467 return SafetyStackThreadSize;
5468}
5469
5470void SetSafetyThreadStackSize(unsigned Value) {
5471 SafetyStackThreadSize = Value;
5472}
5473
5474}
5475
Ted Kremenek04bb7162010-01-22 22:44:15 +00005476extern "C" {
5477
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005478CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005479 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005480}
5481
5482} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005483