blob: 2f8db5dfcef05fc5b372503f7df537c52b649c9f [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000033#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000034#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000035#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000036#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000037#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000038#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000039#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000040#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000041#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000042#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000043#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000044#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000045#include "llvm/Support/Mutex.h"
46#include "llvm/Support/Program.h"
47#include "llvm/Support/Signals.h"
48#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000049#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000050
Steve Naroff50398192009-08-28 15:28:48 +000051using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000052using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000053using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000054
Ted Kremeneka60ed472010-11-16 08:15:36 +000055static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
56 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
61 return D;
62}
63
Douglas Gregor33e9abd2010-01-22 19:49:59 +000064/// \brief The result of comparing two source ranges.
65enum RangeComparisonResult {
66 /// \brief Either the ranges overlap or one of the ranges is invalid.
67 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000068
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 /// \brief The first range ends before the second range starts.
70 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000071
Douglas Gregor33e9abd2010-01-22 19:49:59 +000072 /// \brief The first range starts after the second range ends.
73 RangeAfter
74};
75
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000078static RangeComparisonResult RangeCompare(SourceManager &SM,
79 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000080 SourceRange R2) {
81 assert(R1.isValid() && "First range is invalid?");
82 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000083 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000084 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000085 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000086 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000087 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000088 return RangeAfter;
89 return RangeOverlap;
90}
91
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000092/// \brief Determine if a source location falls within, before, or after a
93/// a given source range.
94static RangeComparisonResult LocationCompare(SourceManager &SM,
95 SourceLocation L, SourceRange R) {
96 assert(R.isValid() && "First range is invalid?");
97 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000098 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000099 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000100 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
101 return RangeBefore;
102 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
103 return RangeAfter;
104 return RangeOverlap;
105}
106
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107/// \brief Translate a Clang source range into a CIndex source range.
108///
109/// Clang internally represents ranges where the end location points to the
110/// start of the token at the end. However, for external clients it is more
111/// useful to have a CXSourceRange be a proper half-open interval. This routine
112/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000113CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000117 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000119 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000120 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000121 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000122 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000123 EndLoc = EndLoc.getFileLocWithOffset(Length);
124 }
125
126 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
127 R.getBegin().getRawEncoding(),
128 EndLoc.getRawEncoding() };
129 return Result;
130}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000131
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000133// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000134//===----------------------------------------------------------------------===//
135
Steve Naroff89922f82009-08-31 00:59:03 +0000136namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000137
138class VisitorJob {
139public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000140 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000141 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000142 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000143 ExplicitTemplateArgsVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000144 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000145 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000146 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000148 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000149 CXCursor parent;
150 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000151 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
152 : parent(C), K(k) {
153 data[0] = d1;
154 data[1] = d2;
155 data[2] = d3;
156 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000157public:
158 Kind getKind() const { return K; }
159 const CXCursor &getParent() const { return parent; }
160 static bool classof(VisitorJob *VJ) { return true; }
161};
162
Chris Lattner5f9e2722011-07-23 10:55:15 +0000163typedef SmallVector<VisitorJob, 10> VisitorWorkList;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000164
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000167 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000168{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000169 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000170 CXTranslationUnit TU;
171 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176 /// \brief The declaration that serves at the parent of any statement or
177 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000178 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000183 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000186 /// \brief Whether we should visit the preprocessing record entries last,
187 /// after visiting other declarations.
188 bool VisitPreprocessorLast;
189
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 /// \brief When valid, a source range to which the cursor should restrict
191 /// its search.
192 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000194 // FIXME: Eventually remove. This part of a hack to support proper
195 // iteration over all Decls contained lexically within an ObjC container.
196 DeclContext::decl_iterator *DI_current;
197 DeclContext::decl_iterator DE_current;
198
Ted Kremenekd1ded662010-11-15 23:31:32 +0000199 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000200 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
201 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
206 /// \brief Determine whether this particular source range comes before, comes
207 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000209 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
211
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000212 class SetParentRAII {
213 CXCursor &Parent;
214 Decl *&StmtParent;
215 CXCursor OldParent;
216
217 public:
218 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
219 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
220 {
221 Parent = NewParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225
226 ~SetParentRAII() {
227 Parent = OldParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231 };
232
Steve Naroff89922f82009-08-31 00:59:03 +0000233public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000234 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
235 CXClientData ClientData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000236 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000238 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
239 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor08e0bc12011-09-10 00:09:20 +0000240 VisitPreprocessorLast(VisitPreprocessorLast),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000241 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 {
243 Parent.kind = CXCursor_NoDeclFound;
244 Parent.data[0] = 0;
245 Parent.data[1] = 0;
246 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000249
Ted Kremenekd1ded662010-11-15 23:31:32 +0000250 ~CursorVisitor() {
251 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000252 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000253 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
254 delete *I;
255 }
256 }
257
Ted Kremeneka60ed472010-11-16 08:15:36 +0000258 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
259 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000260
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000261 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000262
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000263 bool visitPreprocessedEntitiesInRegion();
264
265 template<typename InputIterator>
266 bool visitPreprocessedEntitiesInRegion(InputIterator First,
267 InputIterator Last);
268
269 template<typename InputIterator>
270 bool visitPreprocessedEntities(InputIterator First, InputIterator Last);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000271
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000273
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000274 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000275 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000276 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000277 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000278 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000279 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000280 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000281 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
282 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000283 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000284 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000285 bool VisitClassTemplatePartialSpecializationDecl(
286 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000287 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitEnumConstantDecl(EnumConstantDecl *D);
289 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
290 bool VisitFunctionDecl(FunctionDecl *ND);
291 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000292 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000293 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000294 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000295 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000296 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
298 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
299 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
300 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000301 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000302 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
303 bool VisitObjCImplDecl(ObjCImplDecl *D);
304 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
305 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000306 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
307 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
308 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000309 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000310 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000311 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000312 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000313 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000314 bool VisitUsingDecl(UsingDecl *D);
315 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
316 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000317
Douglas Gregor01829d32010-08-31 14:41:23 +0000318 // Name visitor
319 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000320 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000321 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000322
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000323 // Template visitors
324 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000325 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000326 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
327
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000328 // Type visitors
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000329#define ABSTRACT_TYPELOC(CLASS, PARENT)
330#define TYPELOC(CLASS, PARENT) \
331 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
332#include "clang/AST/TypeLocNodes.def"
333
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000334 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000335 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000336 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
337
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000338 // Data-recursive visitor functions.
339 bool IsInRegionOfInterest(CXCursor C);
340 bool RunVisitorWorkList(VisitorWorkList &WL);
341 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000342 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000343};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Ted Kremenekab188932010-01-05 19:32:54 +0000345} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000346
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000347static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000348static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
349
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000350
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000351RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000352 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000353}
354
Douglas Gregorb1373d02010-01-20 20:59:29 +0000355/// \brief Visit the given cursor and, if requested by the visitor,
356/// its children.
357///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000358/// \param Cursor the cursor to visit.
359///
360/// \param CheckRegionOfInterest if true, then the caller already checked that
361/// this cursor is within the region of interest.
362///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \returns true if the visitation should be aborted, false if it
364/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000366 if (clang_isInvalid(Cursor.kind))
367 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000368
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369 if (clang_isDeclaration(Cursor.kind)) {
370 Decl *D = getCursorDecl(Cursor);
371 assert(D && "Invalid declaration cursor");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 if (D->isImplicit())
373 return false;
374 }
375
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000376 // If we have a range of interest, and this cursor doesn't intersect with it,
377 // we're done.
378 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000379 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000380 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381 return false;
382 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000383
Douglas Gregorb1373d02010-01-20 20:59:29 +0000384 switch (Visitor(Cursor, Parent, ClientData)) {
385 case CXChildVisit_Break:
386 return true;
387
388 case CXChildVisit_Continue:
389 return false;
390
391 case CXChildVisit_Recurse:
392 return VisitChildren(Cursor);
393 }
394
Douglas Gregorfd643772010-01-25 16:45:46 +0000395 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396}
397
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000398bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000399 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000400 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000401
402 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000403 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
404
405 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
406 // If we would only look at local declarations but we have a region of
407 // interest, check whether that region of interest is in the main file.
408 // If not, we should traverse all declarations.
409 // FIXME: My kingdom for a proper binary search approach to finding
410 // cursors!
411 std::pair<FileID, unsigned> Location
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000412 = AU->getSourceManager().getDecomposedExpansionLoc(
Douglas Gregor32038bb2010-12-21 19:07:48 +0000413 RegionOfInterest.getBegin());
414 if (Location.first != AU->getSourceManager().getMainFileID())
415 OnlyLocalDecls = false;
416 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000417
Douglas Gregor89d99802010-11-30 06:16:57 +0000418 PreprocessingRecord::iterator StartEntity, EndEntity;
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000419 if (OnlyLocalDecls && AU->pp_entity_begin() != AU->pp_entity_end())
420 return visitPreprocessedEntitiesInRegion(AU->pp_entity_begin(),
421 AU->pp_entity_end());
422 else
423 return visitPreprocessedEntitiesInRegion(PPRec.begin(), PPRec.end());
424}
425
426template<typename InputIterator>
427bool CursorVisitor::visitPreprocessedEntitiesInRegion(InputIterator First,
428 InputIterator Last) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429 // There is no region of interest; we have to walk everything.
430 if (RegionOfInterest.isInvalid())
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000431 return visitPreprocessedEntities(First, Last);
432
Douglas Gregor788f5a12010-03-20 00:41:21 +0000433 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000434 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000435 std::pair<FileID, unsigned> Begin
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000436 = SM.getDecomposedExpansionLoc(RegionOfInterest.getBegin());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000437 std::pair<FileID, unsigned> End
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000438 = SM.getDecomposedExpansionLoc(RegionOfInterest.getEnd());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000439
440 // The region of interest spans files; we have to walk everything.
441 if (Begin.first != End.first)
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000442 return visitPreprocessedEntities(First, Last);
443
Douglas Gregor788f5a12010-03-20 00:41:21 +0000444 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000445 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000446 if (ByFileMap.empty()) {
447 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000448 for (; First != Last; ++First) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000449 std::pair<FileID, unsigned> P
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000450 = SM.getDecomposedExpansionLoc((*First)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000451
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000452 ByFileMap[P.first].push_back(*First);
453 }
454 }
455
456 return visitPreprocessedEntities(ByFileMap[Begin.first].begin(),
457 ByFileMap[Begin.first].end());
458}
459
460template<typename InputIterator>
461bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
462 InputIterator Last) {
463 for (; First != Last; ++First) {
464 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
465 if (Visit(MakeMacroExpansionCursor(ME, TU)))
466 return true;
467
468 continue;
469 }
470
471 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
472 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
473 return true;
474
475 continue;
476 }
477
478 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
479 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
480 return true;
481
482 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000483 }
484 }
485
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000486 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000487}
488
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000490///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000491/// \returns true if the visitation should be aborted, false if it
492/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000493bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000494 if (clang_isReference(Cursor.kind) &&
495 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000496 // By definition, references have no children.
497 return false;
498 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000499
500 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000502 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504 if (clang_isDeclaration(Cursor.kind)) {
505 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000506 if (!D)
507 return false;
508
Ted Kremenek539311e2010-02-18 18:47:01 +0000509 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000510 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000512 if (clang_isStatement(Cursor.kind)) {
513 if (Stmt *S = getCursorStmt(Cursor))
514 return Visit(S);
515
516 return false;
517 }
518
519 if (clang_isExpression(Cursor.kind)) {
520 if (Expr *E = getCursorExpr(Cursor))
521 return Visit(E);
522
523 return false;
524 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000525
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000527 CXTranslationUnit tu = getCursorTU(Cursor);
528 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000529
530 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
531 for (unsigned I = 0; I != 2; ++I) {
532 if (VisitOrder[I]) {
533 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
534 RegionOfInterest.isInvalid()) {
535 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
536 TLEnd = CXXUnit->top_level_end();
537 TL != TLEnd; ++TL) {
538 if (Visit(MakeCXCursor(*TL, tu), true))
539 return true;
540 }
541 } else if (VisitDeclContext(
542 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000543 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000544 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000545 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000546
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000547 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000548 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
549 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000550 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000551
Douglas Gregor7b691f332010-01-20 21:13:59 +0000552 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000554
Douglas Gregorc314aa42011-03-02 19:17:03 +0000555 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
556 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
557 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
558 return Visit(BaseTSInfo->getTypeLoc());
559 }
560 }
561 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000562
563 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
564 IBOutletCollectionAttr *A =
565 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
566 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
567 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
568 A->getInterfaceLoc(), TU));
569 }
570
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 return false;
573}
574
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000575bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000576 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
577 if (Visit(TSInfo->getTypeLoc()))
578 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000579
Ted Kremenek664cffd2010-07-22 11:30:19 +0000580 if (Stmt *Body = B->getBody())
581 return Visit(MakeCXCursor(Body, StmtParent, TU));
582
583 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000584}
585
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000586llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
587 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000588 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000589 if (Range.isInvalid())
590 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000591
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000592 switch (CompareRegionOfInterest(Range)) {
593 case RangeBefore:
594 // This declaration comes before the region of interest; skip it.
595 return llvm::Optional<bool>();
596
597 case RangeAfter:
598 // This declaration comes after the region of interest; we're done.
599 return false;
600
601 case RangeOverlap:
602 // This declaration overlaps the region of interest; visit it.
603 break;
604 }
605 }
606 return true;
607}
608
609bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
610 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
611
612 // FIXME: Eventually remove. This part of a hack to support proper
613 // iteration over all Decls contained lexically within an ObjC container.
614 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
615 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
616
617 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000618 Decl *D = *I;
619 if (D->getLexicalDeclContext() != DC)
620 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000621 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000622 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
623 if (!V.hasValue())
624 continue;
625 if (!V.getValue())
626 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000627 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000628 return true;
629 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000630 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000631}
632
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
634 llvm_unreachable("Translation units are visited directly by Visit()");
635 return false;
636}
637
Richard Smith162e1c12011-04-15 14:24:37 +0000638bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
639 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
640 return Visit(TSInfo->getTypeLoc());
641
642 return false;
643}
644
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000645bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
646 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
647 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000648
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000649 return false;
650}
651
652bool CursorVisitor::VisitTagDecl(TagDecl *D) {
653 return VisitDeclContext(D);
654}
655
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000656bool CursorVisitor::VisitClassTemplateSpecializationDecl(
657 ClassTemplateSpecializationDecl *D) {
658 bool ShouldVisitBody = false;
659 switch (D->getSpecializationKind()) {
660 case TSK_Undeclared:
661 case TSK_ImplicitInstantiation:
662 // Nothing to visit
663 return false;
664
665 case TSK_ExplicitInstantiationDeclaration:
666 case TSK_ExplicitInstantiationDefinition:
667 break;
668
669 case TSK_ExplicitSpecialization:
670 ShouldVisitBody = true;
671 break;
672 }
673
674 // Visit the template arguments used in the specialization.
675 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
676 TypeLoc TL = SpecType->getTypeLoc();
677 if (TemplateSpecializationTypeLoc *TSTLoc
678 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
679 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
680 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
681 return true;
682 }
683 }
684
685 if (ShouldVisitBody && VisitCXXRecordDecl(D))
686 return true;
687
688 return false;
689}
690
Douglas Gregor74dbe642010-08-31 19:31:58 +0000691bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
692 ClassTemplatePartialSpecializationDecl *D) {
693 // FIXME: Visit the "outer" template parameter lists on the TagDecl
694 // before visiting these template parameters.
695 if (VisitTemplateParameters(D->getTemplateParameters()))
696 return true;
697
698 // Visit the partial specialization arguments.
699 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
700 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
701 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
702 return true;
703
704 return VisitCXXRecordDecl(D);
705}
706
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000707bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000708 // Visit the default argument.
709 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
710 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
711 if (Visit(DefArg->getTypeLoc()))
712 return true;
713
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000714 return false;
715}
716
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000717bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
718 if (Expr *Init = D->getInitExpr())
719 return Visit(MakeCXCursor(Init, StmtParent, TU));
720 return false;
721}
722
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000723bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
724 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
725 if (Visit(TSInfo->getTypeLoc()))
726 return true;
727
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000728 // Visit the nested-name-specifier, if present.
729 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
730 if (VisitNestedNameSpecifierLoc(QualifierLoc))
731 return true;
732
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000733 return false;
734}
735
Douglas Gregora67e03f2010-09-09 21:42:20 +0000736/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000737static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
738 CXXCtorInitializer const * const *X
739 = static_cast<CXXCtorInitializer const * const *>(Xp);
740 CXXCtorInitializer const * const *Y
741 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000742
743 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
744 return -1;
745 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
746 return 1;
747 else
748 return 0;
749}
750
Douglas Gregorb1373d02010-01-20 20:59:29 +0000751bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000752 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
753 // Visit the function declaration's syntactic components in the order
754 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000755 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000756 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
757
758 // If we have a function declared directly (without the use of a typedef),
759 // visit just the return type. Otherwise, just visit the function's type
760 // now.
761 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
762 (!FTL && Visit(TL)))
763 return true;
764
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000765 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000766 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
767 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000768 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000769
770 // Visit the declaration name.
771 if (VisitDeclarationNameInfo(ND->getNameInfo()))
772 return true;
773
774 // FIXME: Visit explicitly-specified template arguments!
775
776 // Visit the function parameters, if we have a function type.
777 if (FTL && VisitFunctionTypeLoc(*FTL, true))
778 return true;
779
780 // FIXME: Attributes?
781 }
782
Sean Hunt10620eb2011-05-06 20:44:56 +0000783 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000784 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
785 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000786 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000787 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
788 IEnd = Constructor->init_end();
789 I != IEnd; ++I) {
790 if (!(*I)->isWritten())
791 continue;
792
793 WrittenInits.push_back(*I);
794 }
795
796 // Sort the initializers in source order
797 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000798 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000799
800 // Visit the initializers in source order
801 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000802 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000803 if (Init->isAnyMemberInitializer()) {
804 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000805 Init->getMemberLocation(), TU)))
806 return true;
807 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
808 if (Visit(BaseInfo->getTypeLoc()))
809 return true;
810 }
811
812 // Visit the initializer value.
813 if (Expr *Initializer = Init->getInit())
814 if (Visit(MakeCXCursor(Initializer, ND, TU)))
815 return true;
816 }
817 }
818
819 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
820 return true;
821 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000822
Douglas Gregorb1373d02010-01-20 20:59:29 +0000823 return false;
824}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000825
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000826bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
827 if (VisitDeclaratorDecl(D))
828 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000829
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000830 if (Expr *BitWidth = D->getBitWidth())
831 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000833 return false;
834}
835
836bool CursorVisitor::VisitVarDecl(VarDecl *D) {
837 if (VisitDeclaratorDecl(D))
838 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 if (Expr *Init = D->getInit())
841 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 return false;
844}
845
Douglas Gregor84b51d72010-09-01 20:16:53 +0000846bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
847 if (VisitDeclaratorDecl(D))
848 return true;
849
850 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
851 if (Expr *DefArg = D->getDefaultArgument())
852 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
853
854 return false;
855}
856
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000857bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
858 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
859 // before visiting these template parameters.
860 if (VisitTemplateParameters(D->getTemplateParameters()))
861 return true;
862
863 return VisitFunctionDecl(D->getTemplatedDecl());
864}
865
Douglas Gregor39d6f072010-08-31 19:02:00 +0000866bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
867 // FIXME: Visit the "outer" template parameter lists on the TagDecl
868 // before visiting these template parameters.
869 if (VisitTemplateParameters(D->getTemplateParameters()))
870 return true;
871
872 return VisitCXXRecordDecl(D->getTemplatedDecl());
873}
874
Douglas Gregor84b51d72010-09-01 20:16:53 +0000875bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
876 if (VisitTemplateParameters(D->getTemplateParameters()))
877 return true;
878
879 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
880 VisitTemplateArgumentLoc(D->getDefaultArgument()))
881 return true;
882
883 return false;
884}
885
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000886bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000887 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
888 if (Visit(TSInfo->getTypeLoc()))
889 return true;
890
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000891 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000892 PEnd = ND->param_end();
893 P != PEnd; ++P) {
894 if (Visit(MakeCXCursor(*P, TU)))
895 return true;
896 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000897
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000898 if (ND->isThisDeclarationADefinition() &&
899 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
900 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000901
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000902 return false;
903}
904
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000905namespace {
906 struct ContainerDeclsSort {
907 SourceManager &SM;
908 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
909 bool operator()(Decl *A, Decl *B) {
910 SourceLocation L_A = A->getLocStart();
911 SourceLocation L_B = B->getLocStart();
912 assert(L_A.isValid() && L_B.isValid());
913 return SM.isBeforeInTranslationUnit(L_A, L_B);
914 }
915 };
916}
917
Douglas Gregora59e3902010-01-21 23:27:09 +0000918bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000919 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
920 // an @implementation can lexically contain Decls that are not properly
921 // nested in the AST. When we identify such cases, we need to retrofit
922 // this nesting here.
923 if (!DI_current)
924 return VisitDeclContext(D);
925
926 // Scan the Decls that immediately come after the container
927 // in the current DeclContext. If any fall within the
928 // container's lexical region, stash them into a vector
929 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000930 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000931 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000932 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000933 if (EndLoc.isValid()) {
934 DeclContext::decl_iterator next = *DI_current;
935 while (++next != DE_current) {
936 Decl *D_next = *next;
937 if (!D_next)
938 break;
939 SourceLocation L = D_next->getLocStart();
940 if (!L.isValid())
941 break;
942 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
943 *DI_current = next;
944 DeclsInContainer.push_back(D_next);
945 continue;
946 }
947 break;
948 }
949 }
950
951 // The common case.
952 if (DeclsInContainer.empty())
953 return VisitDeclContext(D);
954
955 // Get all the Decls in the DeclContext, and sort them with the
956 // additional ones we've collected. Then visit them.
957 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
958 I!=E; ++I) {
959 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000960 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
961 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000962 continue;
963 DeclsInContainer.push_back(subDecl);
964 }
965
966 // Now sort the Decls so that they appear in lexical order.
967 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
968 ContainerDeclsSort(SM));
969
970 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000971 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000972 E = DeclsInContainer.end(); I != E; ++I) {
973 CXCursor Cursor = MakeCXCursor(*I, TU);
974 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
975 if (!V.hasValue())
976 continue;
977 if (!V.getValue())
978 return false;
979 if (Visit(Cursor, true))
980 return true;
981 }
982 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000983}
984
Douglas Gregorb1373d02010-01-20 20:59:29 +0000985bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000986 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
987 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000990 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
991 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
992 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000993 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000994 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995
Douglas Gregora59e3902010-01-21 23:27:09 +0000996 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000997}
998
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000999bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1000 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1001 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1002 E = PID->protocol_end(); I != E; ++I, ++PL)
1003 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1004 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001005
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001006 return VisitObjCContainerDecl(PID);
1007}
1008
Ted Kremenek23173d72010-05-18 21:09:07 +00001009bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001010 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001011 return true;
1012
Ted Kremenek23173d72010-05-18 21:09:07 +00001013 // FIXME: This implements a workaround with @property declarations also being
1014 // installed in the DeclContext for the @interface. Eventually this code
1015 // should be removed.
1016 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1017 if (!CDecl || !CDecl->IsClassExtension())
1018 return false;
1019
1020 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1021 if (!ID)
1022 return false;
1023
1024 IdentifierInfo *PropertyId = PD->getIdentifier();
1025 ObjCPropertyDecl *prevDecl =
1026 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1027
1028 if (!prevDecl)
1029 return false;
1030
1031 // Visit synthesized methods since they will be skipped when visiting
1032 // the @interface.
1033 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001034 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001035 if (Visit(MakeCXCursor(MD, TU)))
1036 return true;
1037
1038 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001039 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001040 if (Visit(MakeCXCursor(MD, TU)))
1041 return true;
1042
1043 return false;
1044}
1045
Douglas Gregorb1373d02010-01-20 20:59:29 +00001046bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001047 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001048 if (D->getSuperClass() &&
1049 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001050 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001051 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001052 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001053
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001054 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1055 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1056 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001057 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001058 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001059
Douglas Gregora59e3902010-01-21 23:27:09 +00001060 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001061}
1062
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1064 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001065}
1066
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001067bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001068 // 'ID' could be null when dealing with invalid code.
1069 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1070 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1071 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001072
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001073 return VisitObjCImplDecl(D);
1074}
1075
1076bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1077#if 0
1078 // Issue callbacks for super class.
1079 // FIXME: No source location information!
1080 if (D->getSuperClass() &&
1081 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001082 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001083 TU)))
1084 return true;
1085#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001086
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001087 return VisitObjCImplDecl(D);
1088}
1089
1090bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1091 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1092 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1093 E = D->protocol_end();
1094 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001095 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001096 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001097
1098 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001099}
1100
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001101bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001102 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1103 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001104 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001105 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001106}
1107
Douglas Gregora4ffd852010-11-17 01:03:52 +00001108bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1109 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1110 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1111
1112 return false;
1113}
1114
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001115bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1116 return VisitDeclContext(D);
1117}
1118
Douglas Gregor69319002010-08-31 23:48:11 +00001119bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001121 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1122 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001123 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001124
1125 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1126 D->getTargetNameLoc(), TU));
1127}
1128
Douglas Gregor7e242562010-09-01 19:52:22 +00001129bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001130 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001131 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1132 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001134 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001135
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001136 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1137 return true;
1138
Douglas Gregor7e242562010-09-01 19:52:22 +00001139 return VisitDeclarationNameInfo(D->getNameInfo());
1140}
1141
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001142bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001143 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001144 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1145 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001146 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001147
1148 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1149 D->getIdentLocation(), TU));
1150}
1151
Douglas Gregor7e242562010-09-01 19:52:22 +00001152bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001153 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001154 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1155 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001156 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001157 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001158
Douglas Gregor7e242562010-09-01 19:52:22 +00001159 return VisitDeclarationNameInfo(D->getNameInfo());
1160}
1161
1162bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1163 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001164 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001165 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1166 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001167 return true;
1168
Douglas Gregor7e242562010-09-01 19:52:22 +00001169 return false;
1170}
1171
Douglas Gregor01829d32010-08-31 14:41:23 +00001172bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1173 switch (Name.getName().getNameKind()) {
1174 case clang::DeclarationName::Identifier:
1175 case clang::DeclarationName::CXXLiteralOperatorName:
1176 case clang::DeclarationName::CXXOperatorName:
1177 case clang::DeclarationName::CXXUsingDirective:
1178 return false;
1179
1180 case clang::DeclarationName::CXXConstructorName:
1181 case clang::DeclarationName::CXXDestructorName:
1182 case clang::DeclarationName::CXXConversionFunctionName:
1183 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1184 return Visit(TSInfo->getTypeLoc());
1185 return false;
1186
1187 case clang::DeclarationName::ObjCZeroArgSelector:
1188 case clang::DeclarationName::ObjCOneArgSelector:
1189 case clang::DeclarationName::ObjCMultiArgSelector:
1190 // FIXME: Per-identifier location info?
1191 return false;
1192 }
1193
1194 return false;
1195}
1196
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001197bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1198 SourceRange Range) {
1199 // FIXME: This whole routine is a hack to work around the lack of proper
1200 // source information in nested-name-specifiers (PR5791). Since we do have
1201 // a beginning source location, we can visit the first component of the
1202 // nested-name-specifier, if it's a single-token component.
1203 if (!NNS)
1204 return false;
1205
1206 // Get the first component in the nested-name-specifier.
1207 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1208 NNS = Prefix;
1209
1210 switch (NNS->getKind()) {
1211 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001212 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1213 TU));
1214
Douglas Gregor14aba762011-02-24 02:36:08 +00001215 case NestedNameSpecifier::NamespaceAlias:
1216 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1217 Range.getBegin(), TU));
1218
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001219 case NestedNameSpecifier::TypeSpec: {
1220 // If the type has a form where we know that the beginning of the source
1221 // range matches up with a reference cursor. Visit the appropriate reference
1222 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001223 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001224 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1225 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1226 if (const TagType *Tag = dyn_cast<TagType>(T))
1227 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1228 if (const TemplateSpecializationType *TST
1229 = dyn_cast<TemplateSpecializationType>(T))
1230 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1231 break;
1232 }
1233
1234 case NestedNameSpecifier::TypeSpecWithTemplate:
1235 case NestedNameSpecifier::Global:
1236 case NestedNameSpecifier::Identifier:
1237 break;
1238 }
1239
1240 return false;
1241}
1242
Douglas Gregordc355712011-02-25 00:36:19 +00001243bool
1244CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001245 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001246 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1247 Qualifiers.push_back(Qualifier);
1248
1249 while (!Qualifiers.empty()) {
1250 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1251 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1252 switch (NNS->getKind()) {
1253 case NestedNameSpecifier::Namespace:
1254 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001255 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001256 TU)))
1257 return true;
1258
1259 break;
1260
1261 case NestedNameSpecifier::NamespaceAlias:
1262 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001263 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001264 TU)))
1265 return true;
1266
1267 break;
1268
1269 case NestedNameSpecifier::TypeSpec:
1270 case NestedNameSpecifier::TypeSpecWithTemplate:
1271 if (Visit(Q.getTypeLoc()))
1272 return true;
1273
1274 break;
1275
1276 case NestedNameSpecifier::Global:
1277 case NestedNameSpecifier::Identifier:
1278 break;
1279 }
1280 }
1281
1282 return false;
1283}
1284
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001285bool CursorVisitor::VisitTemplateParameters(
1286 const TemplateParameterList *Params) {
1287 if (!Params)
1288 return false;
1289
1290 for (TemplateParameterList::const_iterator P = Params->begin(),
1291 PEnd = Params->end();
1292 P != PEnd; ++P) {
1293 if (Visit(MakeCXCursor(*P, TU)))
1294 return true;
1295 }
1296
1297 return false;
1298}
1299
Douglas Gregor0b36e612010-08-31 20:37:03 +00001300bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1301 switch (Name.getKind()) {
1302 case TemplateName::Template:
1303 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1304
1305 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001306 // Visit the overloaded template set.
1307 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1308 return true;
1309
Douglas Gregor0b36e612010-08-31 20:37:03 +00001310 return false;
1311
1312 case TemplateName::DependentTemplate:
1313 // FIXME: Visit nested-name-specifier.
1314 return false;
1315
1316 case TemplateName::QualifiedTemplate:
1317 // FIXME: Visit nested-name-specifier.
1318 return Visit(MakeCursorTemplateRef(
1319 Name.getAsQualifiedTemplateName()->getDecl(),
1320 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001321
1322 case TemplateName::SubstTemplateTemplateParm:
1323 return Visit(MakeCursorTemplateRef(
1324 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1325 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001326
1327 case TemplateName::SubstTemplateTemplateParmPack:
1328 return Visit(MakeCursorTemplateRef(
1329 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1330 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001331 }
1332
1333 return false;
1334}
1335
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001336bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1337 switch (TAL.getArgument().getKind()) {
1338 case TemplateArgument::Null:
1339 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001340 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001341 return false;
1342
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001343 case TemplateArgument::Type:
1344 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1345 return Visit(TSInfo->getTypeLoc());
1346 return false;
1347
1348 case TemplateArgument::Declaration:
1349 if (Expr *E = TAL.getSourceDeclExpression())
1350 return Visit(MakeCXCursor(E, StmtParent, TU));
1351 return false;
1352
1353 case TemplateArgument::Expression:
1354 if (Expr *E = TAL.getSourceExpression())
1355 return Visit(MakeCXCursor(E, StmtParent, TU));
1356 return false;
1357
1358 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001359 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001360 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1361 return true;
1362
Douglas Gregora7fc9012011-01-05 18:58:31 +00001363 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001364 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001365 }
1366
1367 return false;
1368}
1369
Ted Kremeneka0536d82010-05-07 01:04:29 +00001370bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1371 return VisitDeclContext(D);
1372}
1373
Douglas Gregor01829d32010-08-31 14:41:23 +00001374bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1375 return Visit(TL.getUnqualifiedLoc());
1376}
1377
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001379 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380
1381 // Some builtin types (such as Objective-C's "id", "sel", and
1382 // "Class") have associated declarations. Create cursors for those.
1383 QualType VisitType;
1384 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001385 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001387 case BuiltinType::Char_U:
1388 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001389 case BuiltinType::Char16:
1390 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001391 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392 case BuiltinType::UInt:
1393 case BuiltinType::ULong:
1394 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001395 case BuiltinType::UInt128:
1396 case BuiltinType::Char_S:
1397 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001398 case BuiltinType::WChar_U:
1399 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001400 case BuiltinType::Short:
1401 case BuiltinType::Int:
1402 case BuiltinType::Long:
1403 case BuiltinType::LongLong:
1404 case BuiltinType::Int128:
1405 case BuiltinType::Float:
1406 case BuiltinType::Double:
1407 case BuiltinType::LongDouble:
1408 case BuiltinType::NullPtr:
1409 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001410 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001411 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001412 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001413 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001414
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001415 case BuiltinType::ObjCId:
1416 VisitType = Context.getObjCIdType();
1417 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001418
1419 case BuiltinType::ObjCClass:
1420 VisitType = Context.getObjCClassType();
1421 break;
1422
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423 case BuiltinType::ObjCSel:
1424 VisitType = Context.getObjCSelType();
1425 break;
1426 }
1427
1428 if (!VisitType.isNull()) {
1429 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001430 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001431 TU));
1432 }
1433
1434 return false;
1435}
1436
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001437bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001438 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001439}
1440
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001441bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1442 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1443}
1444
1445bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001446 if (TL.isDefinition())
1447 return Visit(MakeCXCursor(TL.getDecl(), TU));
1448
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001449 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1450}
1451
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001452bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001453 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001454}
1455
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001456bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1457 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1458 return true;
1459
John McCallc12c5bb2010-05-15 11:32:37 +00001460 return false;
1461}
1462
1463bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1464 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1465 return true;
1466
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001467 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1468 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1469 TU)))
1470 return true;
1471 }
1472
1473 return false;
1474}
1475
1476bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001477 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001478}
1479
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001480bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1481 return Visit(TL.getInnerLoc());
1482}
1483
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001484bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1485 return Visit(TL.getPointeeLoc());
1486}
1487
1488bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1489 return Visit(TL.getPointeeLoc());
1490}
1491
1492bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1493 return Visit(TL.getPointeeLoc());
1494}
1495
1496bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001497 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001498}
1499
1500bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001501 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001502}
1503
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001504bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1505 return Visit(TL.getModifiedLoc());
1506}
1507
Douglas Gregor01829d32010-08-31 14:41:23 +00001508bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1509 bool SkipResultType) {
1510 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001511 return true;
1512
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001513 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001514 if (Decl *D = TL.getArg(I))
1515 if (Visit(MakeCXCursor(D, TU)))
1516 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001517
1518 return false;
1519}
1520
1521bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1522 if (Visit(TL.getElementLoc()))
1523 return true;
1524
1525 if (Expr *Size = TL.getSizeExpr())
1526 return Visit(MakeCXCursor(Size, StmtParent, TU));
1527
1528 return false;
1529}
1530
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001531bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1532 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001533 // Visit the template name.
1534 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1535 TL.getTemplateNameLoc()))
1536 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001537
1538 // Visit the template arguments.
1539 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1540 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1541 return true;
1542
1543 return false;
1544}
1545
Douglas Gregor2332c112010-01-21 20:48:56 +00001546bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1547 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1548}
1549
1550bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1551 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1552 return Visit(TSInfo->getTypeLoc());
1553
1554 return false;
1555}
1556
Sean Huntca63c202011-05-24 22:41:36 +00001557bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1558 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1559 return Visit(TSInfo->getTypeLoc());
1560
1561 return false;
1562}
1563
Douglas Gregor2494dd02011-03-01 01:34:45 +00001564bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1565 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1566 return true;
1567
1568 return false;
1569}
1570
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001571bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1572 DependentTemplateSpecializationTypeLoc TL) {
1573 // Visit the nested-name-specifier, if there is one.
1574 if (TL.getQualifierLoc() &&
1575 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1576 return true;
1577
1578 // Visit the template arguments.
1579 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1580 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1581 return true;
1582
1583 return false;
1584}
1585
Douglas Gregor9e876872011-03-01 18:12:44 +00001586bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1587 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1588 return true;
1589
1590 return Visit(TL.getNamedTypeLoc());
1591}
1592
Douglas Gregor7536dd52010-12-20 02:24:11 +00001593bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1594 return Visit(TL.getPatternLoc());
1595}
1596
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001597bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1598 if (Expr *E = TL.getUnderlyingExpr())
1599 return Visit(MakeCXCursor(E, StmtParent, TU));
1600
1601 return false;
1602}
1603
1604bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1605 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1606}
1607
1608#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1609bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1610 return Visit##PARENT##Loc(TL); \
1611}
1612
1613DEFAULT_TYPELOC_IMPL(Complex, Type)
1614DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1615DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1616DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1617DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1618DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1619DEFAULT_TYPELOC_IMPL(Vector, Type)
1620DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1621DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1622DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1623DEFAULT_TYPELOC_IMPL(Record, TagType)
1624DEFAULT_TYPELOC_IMPL(Enum, TagType)
1625DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1626DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1627DEFAULT_TYPELOC_IMPL(Auto, Type)
1628
Ted Kremenek3064ef92010-08-27 21:34:58 +00001629bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001630 // Visit the nested-name-specifier, if present.
1631 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1632 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1633 return true;
1634
Ted Kremenek3064ef92010-08-27 21:34:58 +00001635 if (D->isDefinition()) {
1636 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1637 E = D->bases_end(); I != E; ++I) {
1638 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1639 return true;
1640 }
1641 }
1642
1643 return VisitTagDecl(D);
1644}
1645
Ted Kremenek09dfa372010-02-18 05:46:33 +00001646bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001647 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1648 i != e; ++i)
1649 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001650 return true;
1651
1652 return false;
1653}
1654
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001655//===----------------------------------------------------------------------===//
1656// Data-recursive visitor methods.
1657//===----------------------------------------------------------------------===//
1658
Ted Kremenek28a71942010-11-13 00:36:47 +00001659namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001660#define DEF_JOB(NAME, DATA, KIND)\
1661class NAME : public VisitorJob {\
1662public:\
1663 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1664 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001665 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001666};
1667
1668DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1669DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001670DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001671DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001672DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1673 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001674DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001675#undef DEF_JOB
1676
1677class DeclVisit : public VisitorJob {
1678public:
1679 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1680 VisitorJob(parent, VisitorJob::DeclVisitKind,
1681 d, isFirst ? (void*) 1 : (void*) 0) {}
1682 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001683 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001684 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001685 Decl *get() const { return static_cast<Decl*>(data[0]); }
1686 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001687};
Ted Kremenek035dc412010-11-13 00:36:50 +00001688class TypeLocVisit : public VisitorJob {
1689public:
1690 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1691 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1692 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1693
1694 static bool classof(const VisitorJob *VJ) {
1695 return VJ->getKind() == TypeLocVisitKind;
1696 }
1697
Ted Kremenek82f3c502010-11-15 22:23:26 +00001698 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001699 QualType T = QualType::getFromOpaquePtr(data[0]);
1700 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001701 }
1702};
1703
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001704class LabelRefVisit : public VisitorJob {
1705public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001706 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1707 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001708 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001709
1710 static bool classof(const VisitorJob *VJ) {
1711 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1712 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001713 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001714 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001715 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001716};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001717
1718class NestedNameSpecifierLocVisit : public VisitorJob {
1719public:
1720 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1721 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1722 Qualifier.getNestedNameSpecifier(),
1723 Qualifier.getOpaqueData()) { }
1724
1725 static bool classof(const VisitorJob *VJ) {
1726 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1727 }
1728
1729 NestedNameSpecifierLoc get() const {
1730 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1731 data[1]);
1732 }
1733};
1734
Ted Kremenekf64d8032010-11-18 00:02:32 +00001735class DeclarationNameInfoVisit : public VisitorJob {
1736public:
1737 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1738 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1739 static bool classof(const VisitorJob *VJ) {
1740 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1741 }
1742 DeclarationNameInfo get() const {
1743 Stmt *S = static_cast<Stmt*>(data[0]);
1744 switch (S->getStmtClass()) {
1745 default:
1746 llvm_unreachable("Unhandled Stmt");
1747 case Stmt::CXXDependentScopeMemberExprClass:
1748 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1749 case Stmt::DependentScopeDeclRefExprClass:
1750 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1751 }
1752 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001753};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001754class MemberRefVisit : public VisitorJob {
1755public:
1756 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1757 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001758 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001759 static bool classof(const VisitorJob *VJ) {
1760 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1761 }
1762 FieldDecl *get() const {
1763 return static_cast<FieldDecl*>(data[0]);
1764 }
1765 SourceLocation getLoc() const {
1766 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1767 }
1768};
Ted Kremenek28a71942010-11-13 00:36:47 +00001769class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1770 VisitorWorkList &WL;
1771 CXCursor Parent;
1772public:
1773 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1774 : WL(wl), Parent(parent) {}
1775
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001776 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001777 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001778 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001779 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001780 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001781 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001782 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001783 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001784 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001785 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001786 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001787 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001788 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001789 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001790 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001791 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001792 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001793 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001794 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1795 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001796 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001797 void VisitIfStmt(IfStmt *If);
1798 void VisitInitListExpr(InitListExpr *IE);
1799 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001800 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001801 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001802 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1803 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001804 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001805 void VisitStmt(Stmt *S);
1806 void VisitSwitchStmt(SwitchStmt *S);
1807 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001808 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001809 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001810 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001811 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001812 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001813 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001814 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001815
Ted Kremenek28a71942010-11-13 00:36:47 +00001816private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001817 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001818 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001819 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001820 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001821 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001822 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001823 void AddTypeLoc(TypeSourceInfo *TI);
1824 void EnqueueChildren(Stmt *S);
1825};
1826} // end anonyous namespace
1827
Ted Kremenekf64d8032010-11-18 00:02:32 +00001828void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1829 // 'S' should always be non-null, since it comes from the
1830 // statement we are visiting.
1831 WL.push_back(DeclarationNameInfoVisit(S, 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 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002177
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002178 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2179 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2180 if (VisitNestedNameSpecifierLoc(V->get()))
2181 return true;
2182 continue;
2183 }
2184
Ted Kremenekf64d8032010-11-18 00:02:32 +00002185 case VisitorJob::DeclarationNameInfoVisitKind: {
2186 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2187 ->get()))
2188 return true;
2189 continue;
2190 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002191 case VisitorJob::MemberRefVisitKind: {
2192 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2193 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2194 return true;
2195 continue;
2196 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002197 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002198 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002199 if (!S)
2200 continue;
2201
Ted Kremenekf1107452010-11-12 18:26:56 +00002202 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002203 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002204 if (!IsInRegionOfInterest(Cursor))
2205 continue;
2206 switch (Visitor(Cursor, Parent, ClientData)) {
2207 case CXChildVisit_Break: return true;
2208 case CXChildVisit_Continue: break;
2209 case CXChildVisit_Recurse:
2210 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002211 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002212 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002213 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002214 }
2215 case VisitorJob::MemberExprPartsKind: {
2216 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002217 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002218
2219 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002220 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2221 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002222 return true;
2223
2224 // Visit the declaration name.
2225 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2226 return true;
2227
2228 // Visit the explicitly-specified template arguments, if any.
2229 if (M->hasExplicitTemplateArgs()) {
2230 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2231 *ArgEnd = Arg + M->getNumTemplateArgs();
2232 Arg != ArgEnd; ++Arg) {
2233 if (VisitTemplateArgumentLoc(*Arg))
2234 return true;
2235 }
2236 }
2237 continue;
2238 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002239 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002240 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002241 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002242 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2243 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002244 return true;
2245 // Visit declaration name.
2246 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2247 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002248 continue;
2249 }
Ted Kremenek60458782010-11-12 21:34:16 +00002250 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002251 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002252 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002253 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2254 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002255 return true;
2256 // Visit the declaration name.
2257 if (VisitDeclarationNameInfo(O->getNameInfo()))
2258 return true;
2259 // Visit the overloaded declaration reference.
2260 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2261 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002262 continue;
2263 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002264 case VisitorJob::SizeOfPackExprPartsKind: {
2265 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2266 NamedDecl *Pack = E->getPack();
2267 if (isa<TemplateTypeParmDecl>(Pack)) {
2268 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2269 E->getPackLoc(), TU)))
2270 return true;
2271
2272 continue;
2273 }
2274
2275 if (isa<TemplateTemplateParmDecl>(Pack)) {
2276 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2277 E->getPackLoc(), TU)))
2278 return true;
2279
2280 continue;
2281 }
2282
2283 // Non-type template parameter packs and function parameter packs are
2284 // treated like DeclRefExpr cursors.
2285 continue;
2286 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002287 }
2288 }
2289 return false;
2290}
2291
Ted Kremenekcdba6592010-11-18 00:42:18 +00002292bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002293 VisitorWorkList *WL = 0;
2294 if (!WorkListFreeList.empty()) {
2295 WL = WorkListFreeList.back();
2296 WL->clear();
2297 WorkListFreeList.pop_back();
2298 }
2299 else {
2300 WL = new VisitorWorkList();
2301 WorkListCache.push_back(WL);
2302 }
2303 EnqueueWorkList(*WL, S);
2304 bool result = RunVisitorWorkList(*WL);
2305 WorkListFreeList.push_back(WL);
2306 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002307}
2308
Francois Pichet48a8d142011-07-25 22:00:44 +00002309namespace {
2310typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2311RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2312 const DeclarationNameInfo &NI,
2313 const SourceRange &QLoc,
2314 const ExplicitTemplateArgumentList *TemplateArgs = 0){
2315 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2316 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2317 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2318
2319 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2320
2321 RefNamePieces Pieces;
2322
2323 if (WantQualifier && QLoc.isValid())
2324 Pieces.push_back(QLoc);
2325
2326 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2327 Pieces.push_back(NI.getLoc());
2328
2329 if (WantTemplateArgs && TemplateArgs)
2330 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2331 TemplateArgs->RAngleLoc));
2332
2333 if (Kind == DeclarationName::CXXOperatorName) {
2334 Pieces.push_back(SourceLocation::getFromRawEncoding(
2335 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2336 Pieces.push_back(SourceLocation::getFromRawEncoding(
2337 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2338 }
2339
2340 if (WantSinglePiece) {
2341 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2342 Pieces.clear();
2343 Pieces.push_back(R);
2344 }
2345
2346 return Pieces;
2347}
2348}
2349
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002350//===----------------------------------------------------------------------===//
2351// Misc. API hooks.
2352//===----------------------------------------------------------------------===//
2353
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002354static llvm::sys::Mutex EnableMultithreadingMutex;
2355static bool EnabledMultithreading;
2356
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002357extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002358CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2359 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002360 // Disable pretty stack trace functionality, which will otherwise be a very
2361 // poor citizen of the world and set up all sorts of signal handlers.
2362 llvm::DisablePrettyStackTrace = true;
2363
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002364 // We use crash recovery to make some of our APIs more reliable, implicitly
2365 // enable it.
2366 llvm::CrashRecoveryContext::Enable();
2367
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002368 // Enable support for multithreading in LLVM.
2369 {
2370 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2371 if (!EnabledMultithreading) {
2372 llvm::llvm_start_multithreaded();
2373 EnabledMultithreading = true;
2374 }
2375 }
2376
Douglas Gregora030b7c2010-01-22 20:35:53 +00002377 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002378 if (excludeDeclarationsFromPCH)
2379 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002380 if (displayDiagnostics)
2381 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002382 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002383}
2384
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002385void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002386 if (CIdx)
2387 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002388}
2389
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002390void clang_toggleCrashRecovery(unsigned isEnabled) {
2391 if (isEnabled)
2392 llvm::CrashRecoveryContext::Enable();
2393 else
2394 llvm::CrashRecoveryContext::Disable();
2395}
2396
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002397CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002398 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002399 if (!CIdx)
2400 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002401
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002402 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002403 FileSystemOptions FileSystemOpts;
2404 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002405
Douglas Gregor28019772010-04-05 23:52:57 +00002406 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002407 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002408 CXXIdx->getOnlyLocalDecls(),
2409 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002410 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002411}
2412
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002413unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002414 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002415 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002416}
2417
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002418CXTranslationUnit
2419clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2420 const char *source_filename,
2421 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002422 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002423 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002424 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002425 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002426 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002427 return clang_parseTranslationUnit(CIdx, source_filename,
2428 command_line_args, num_command_line_args,
2429 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002430 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002431}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002432
2433struct ParseTranslationUnitInfo {
2434 CXIndex CIdx;
2435 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002436 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002437 int num_command_line_args;
2438 struct CXUnsavedFile *unsaved_files;
2439 unsigned num_unsaved_files;
2440 unsigned options;
2441 CXTranslationUnit result;
2442};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002443static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002444 ParseTranslationUnitInfo *PTUI =
2445 static_cast<ParseTranslationUnitInfo*>(UserData);
2446 CXIndex CIdx = PTUI->CIdx;
2447 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002448 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002449 int num_command_line_args = PTUI->num_command_line_args;
2450 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2451 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2452 unsigned options = PTUI->options;
2453 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002454
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002455 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002456 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002458 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2459
Douglas Gregor44c181a2010-07-23 00:33:23 +00002460 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002461 // FIXME: Add a flag for modules.
2462 TranslationUnitKind TUKind
2463 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002464 bool CacheCodeCompetionResults
2465 = options & CXTranslationUnit_CacheCompletionResults;
2466
Douglas Gregor5352ac02010-01-28 00:27:43 +00002467 // Configure the diagnostics.
2468 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002469 llvm::IntrusiveRefCntPtr<Diagnostic>
2470 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2471 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002472
Ted Kremenek25a11e12011-03-22 01:15:24 +00002473 // Recover resources if we crash before exiting this function.
2474 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2475 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2476 DiagCleanup(Diags.getPtr());
2477
2478 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2479 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2480
2481 // Recover resources if we crash before exiting this function.
2482 llvm::CrashRecoveryContextCleanupRegistrar<
2483 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2484
Douglas Gregor4db64a42010-01-23 00:14:00 +00002485 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002486 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002487 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002488 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002489 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2490 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002491 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002492
Ted Kremenek25a11e12011-03-22 01:15:24 +00002493 llvm::OwningPtr<std::vector<const char *> >
2494 Args(new std::vector<const char*>());
2495
2496 // Recover resources if we crash before exiting this method.
2497 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2498 ArgsCleanup(Args.get());
2499
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002500 // Since the Clang C library is primarily used by batch tools dealing with
2501 // (often very broken) source code, where spell-checking can have a
2502 // significant negative impact on performance (particularly when
2503 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002504 // Only do this if we haven't found a spell-checking-related argument.
2505 bool FoundSpellCheckingArgument = false;
2506 for (int I = 0; I != num_command_line_args; ++I) {
2507 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2508 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2509 FoundSpellCheckingArgument = true;
2510 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002511 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002512 }
2513 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002514 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002515
Ted Kremenek25a11e12011-03-22 01:15:24 +00002516 Args->insert(Args->end(), command_line_args,
2517 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002518
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002519 // The 'source_filename' argument is optional. If the caller does not
2520 // specify it then it is assumed that the source file is specified
2521 // in the actual argument list.
2522 // Put the source file after command_line_args otherwise if '-x' flag is
2523 // present it will be unused.
2524 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002525 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002526
Douglas Gregor44c181a2010-07-23 00:33:23 +00002527 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002528 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002529 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002530 Args->push_back("-Xclang");
2531 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002532 NestedMacroExpansions
2533 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002534 }
2535
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002536 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002537 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002538 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2539 /* vector::data() not portable */,
2540 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002541 Diags,
2542 CXXIdx->getClangResourcesPath(),
2543 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002544 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002545 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002546 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002547 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002548 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002549 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002550 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002551 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002552
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002553 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002554 // Make sure to check that 'Unit' is non-NULL.
2555 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2556 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2557 DEnd = Unit->stored_diag_end();
2558 D != DEnd; ++D) {
2559 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2560 CXString Msg = clang_formatDiagnostic(&Diag,
2561 clang_defaultDiagnosticDisplayOptions());
2562 fprintf(stderr, "%s\n", clang_getCString(Msg));
2563 clang_disposeString(Msg);
2564 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002565#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002566 // On Windows, force a flush, since there may be multiple copies of
2567 // stderr and stdout in the file system, all with different buffers
2568 // but writing to the same device.
2569 fflush(stderr);
2570#endif
2571 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002572 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002573
Ted Kremeneka60ed472010-11-16 08:15:36 +00002574 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002575}
2576CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2577 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002578 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002579 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002580 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002581 unsigned num_unsaved_files,
2582 unsigned options) {
2583 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002584 num_command_line_args, unsaved_files,
2585 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002586 llvm::CrashRecoveryContext CRC;
2587
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002588 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002589 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2590 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2591 fprintf(stderr, " 'command_line_args' : [");
2592 for (int i = 0; i != num_command_line_args; ++i) {
2593 if (i)
2594 fprintf(stderr, ", ");
2595 fprintf(stderr, "'%s'", command_line_args[i]);
2596 }
2597 fprintf(stderr, "],\n");
2598 fprintf(stderr, " 'unsaved_files' : [");
2599 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2600 if (i)
2601 fprintf(stderr, ", ");
2602 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2603 unsaved_files[i].Length);
2604 }
2605 fprintf(stderr, "],\n");
2606 fprintf(stderr, " 'options' : %d,\n", options);
2607 fprintf(stderr, "}\n");
2608
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002609 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002610 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2611 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002612 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002613
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002614 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002615}
2616
Douglas Gregor19998442010-08-13 15:35:05 +00002617unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2618 return CXSaveTranslationUnit_None;
2619}
2620
2621int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2622 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002623 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002624 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002625
Douglas Gregor39c411f2011-07-06 16:43:36 +00002626 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002627 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2628 PrintLibclangResourceUsage(TU);
2629 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002630}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002631
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002632void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002633 if (CTUnit) {
2634 // If the translation unit has been marked as unsafe to free, just discard
2635 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002636 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002637 return;
2638
Ted Kremeneka60ed472010-11-16 08:15:36 +00002639 delete static_cast<ASTUnit *>(CTUnit->TUData);
2640 disposeCXStringPool(CTUnit->StringPool);
2641 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002642 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002643}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002644
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002645unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2646 return CXReparse_None;
2647}
2648
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002649struct ReparseTranslationUnitInfo {
2650 CXTranslationUnit TU;
2651 unsigned num_unsaved_files;
2652 struct CXUnsavedFile *unsaved_files;
2653 unsigned options;
2654 int result;
2655};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002656
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002657static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002658 ReparseTranslationUnitInfo *RTUI =
2659 static_cast<ReparseTranslationUnitInfo*>(UserData);
2660 CXTranslationUnit TU = RTUI->TU;
2661 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2662 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2663 unsigned options = RTUI->options;
2664 (void) options;
2665 RTUI->result = 1;
2666
Douglas Gregorabc563f2010-07-19 21:46:24 +00002667 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002668 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002669
Ted Kremeneka60ed472010-11-16 08:15:36 +00002670 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002671 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002672
Ted Kremenek25a11e12011-03-22 01:15:24 +00002673 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2674 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2675
2676 // Recover resources if we crash before exiting this function.
2677 llvm::CrashRecoveryContextCleanupRegistrar<
2678 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2679
Douglas Gregorabc563f2010-07-19 21:46:24 +00002680 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002681 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002682 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002683 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002684 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2685 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002686 }
2687
Ted Kremenek4ee99262011-03-22 20:16:19 +00002688 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2689 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002690 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002691}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002692
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002693int clang_reparseTranslationUnit(CXTranslationUnit TU,
2694 unsigned num_unsaved_files,
2695 struct CXUnsavedFile *unsaved_files,
2696 unsigned options) {
2697 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2698 options, 0 };
2699 llvm::CrashRecoveryContext CRC;
2700
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002701 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002702 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002703 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002704 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002705 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2706 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002707
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002708 return RTUI.result;
2709}
2710
Douglas Gregordf95a132010-08-09 20:45:32 +00002711
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002712CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002713 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002714 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715
Ted Kremeneka60ed472010-11-16 08:15:36 +00002716 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002717 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002718}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002719
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002720CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002721 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002722 return Result;
2723}
2724
Ted Kremenekfb480492010-01-13 21:46:36 +00002725} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002726
Ted Kremenekfb480492010-01-13 21:46:36 +00002727//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002728// CXSourceLocation and CXSourceRange Operations.
2729//===----------------------------------------------------------------------===//
2730
Douglas Gregorb9790342010-01-22 21:44:22 +00002731extern "C" {
2732CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002733 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002734 return Result;
2735}
2736
2737unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002738 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2739 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2740 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002741}
2742
2743CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2744 CXFile file,
2745 unsigned line,
2746 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002747 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002748 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002749
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002750 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002751 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002752 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002753 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002754 = CXXUnit->getSourceManager().getLocation(File, line, column);
2755 if (SLoc.isInvalid()) {
2756 if (Logging)
2757 llvm::errs() << "clang_getLocation(\"" << File->getName()
2758 << "\", " << line << ", " << column << ") = invalid\n";
2759 return clang_getNullLocation();
2760 }
2761
2762 if (Logging)
2763 llvm::errs() << "clang_getLocation(\"" << File->getName()
2764 << "\", " << line << ", " << column << ") = "
2765 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002766
2767 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2768}
2769
2770CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2771 CXFile file,
2772 unsigned offset) {
2773 if (!tu || !file)
2774 return clang_getNullLocation();
2775
Ted Kremeneka60ed472010-11-16 08:15:36 +00002776 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002777 SourceLocation Start
2778 = CXXUnit->getSourceManager().getLocation(
2779 static_cast<const FileEntry *>(file),
2780 1, 1);
2781 if (Start.isInvalid()) return clang_getNullLocation();
2782
2783 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2784
2785 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002786
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002787 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002788}
2789
Douglas Gregor5352ac02010-01-28 00:27:43 +00002790CXSourceRange clang_getNullRange() {
2791 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2792 return Result;
2793}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002794
Douglas Gregor5352ac02010-01-28 00:27:43 +00002795CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2796 if (begin.ptr_data[0] != end.ptr_data[0] ||
2797 begin.ptr_data[1] != end.ptr_data[1])
2798 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002799
2800 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002801 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002802 return Result;
2803}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002804
2805unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2806{
2807 return range1.ptr_data[0] == range2.ptr_data[0]
2808 && range1.ptr_data[1] == range2.ptr_data[1]
2809 && range1.begin_int_data == range2.begin_int_data
2810 && range1.end_int_data == range2.end_int_data;
2811}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002812} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002813
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002814static void createNullLocation(CXFile *file, unsigned *line,
2815 unsigned *column, unsigned *offset) {
2816 if (file)
2817 *file = 0;
2818 if (line)
2819 *line = 0;
2820 if (column)
2821 *column = 0;
2822 if (offset)
2823 *offset = 0;
2824 return;
2825}
2826
2827extern "C" {
Chandler Carruth20174222011-08-31 16:53:37 +00002828void clang_getExpansionLocation(CXSourceLocation location,
2829 CXFile *file,
2830 unsigned *line,
2831 unsigned *column,
2832 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002833 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2834
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002835 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002836 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002837 return;
2838 }
2839
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002840 const SourceManager &SM =
2841 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth20174222011-08-31 16:53:37 +00002842 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002843
Chandler Carruthcea731a2011-07-14 16:07:57 +00002844 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002845 // This can manifest in invalid code.
Chandler Carruth20174222011-08-31 16:53:37 +00002846 FileID fileID = SM.getFileID(ExpansionLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002847 bool Invalid = false;
2848 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2849 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002850 createNullLocation(file, line, column, offset);
2851 return;
2852 }
2853
Douglas Gregor1db19de2010-01-19 21:36:55 +00002854 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002855 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002856 if (line)
Chandler Carruth20174222011-08-31 16:53:37 +00002857 *line = SM.getExpansionLineNumber(ExpansionLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002858 if (column)
Chandler Carruth20174222011-08-31 16:53:37 +00002859 *column = SM.getExpansionColumnNumber(ExpansionLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002860 if (offset)
Chandler Carruth20174222011-08-31 16:53:37 +00002861 *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2862}
2863
2864void clang_getInstantiationLocation(CXSourceLocation location,
2865 CXFile *file,
2866 unsigned *line,
2867 unsigned *column,
2868 unsigned *offset) {
2869 // Redirect to new API.
2870 clang_getExpansionLocation(location, file, line, column, offset);
Douglas Gregore69517c2010-01-26 03:07:15 +00002871}
2872
Douglas Gregora9b06d42010-11-09 06:24:54 +00002873void clang_getSpellingLocation(CXSourceLocation location,
2874 CXFile *file,
2875 unsigned *line,
2876 unsigned *column,
2877 unsigned *offset) {
2878 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2879
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002880 if (!location.ptr_data[0] || Loc.isInvalid())
2881 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002882
2883 const SourceManager &SM =
2884 *static_cast<const SourceManager*>(location.ptr_data[0]);
2885 SourceLocation SpellLoc = Loc;
2886 if (SpellLoc.isMacroID()) {
2887 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2888 if (SimpleSpellingLoc.isFileID() &&
2889 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2890 SpellLoc = SimpleSpellingLoc;
2891 else
Chandler Carruth40278532011-07-25 16:49:02 +00002892 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002893 }
2894
2895 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2896 FileID FID = LocInfo.first;
2897 unsigned FileOffset = LocInfo.second;
2898
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002899 if (FID.isInvalid())
2900 return createNullLocation(file, line, column, offset);
2901
Douglas Gregora9b06d42010-11-09 06:24:54 +00002902 if (file)
2903 *file = (void *)SM.getFileEntryForID(FID);
2904 if (line)
2905 *line = SM.getLineNumber(FID, FileOffset);
2906 if (column)
2907 *column = SM.getColumnNumber(FID, FileOffset);
2908 if (offset)
2909 *offset = FileOffset;
2910}
2911
Douglas Gregor1db19de2010-01-19 21:36:55 +00002912CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002913 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002914 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002915 return Result;
2916}
2917
2918CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002919 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002920 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002921 return Result;
2922}
2923
Douglas Gregorb9790342010-01-22 21:44:22 +00002924} // end: extern "C"
2925
Douglas Gregor1db19de2010-01-19 21:36:55 +00002926//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002927// CXFile Operations.
2928//===----------------------------------------------------------------------===//
2929
2930extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002931CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002932 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002933 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002934
Steve Naroff88145032009-10-27 14:35:18 +00002935 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002936 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002937}
2938
2939time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002940 if (!SFile)
2941 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002942
Steve Naroff88145032009-10-27 14:35:18 +00002943 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2944 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002945}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002946
Douglas Gregorb9790342010-01-22 21:44:22 +00002947CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2948 if (!tu)
2949 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002950
Ted Kremeneka60ed472010-11-16 08:15:36 +00002951 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002952
Douglas Gregorb9790342010-01-22 21:44:22 +00002953 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002954 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002955}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002956
Douglas Gregordd3e5542011-05-04 00:14:37 +00002957unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2958 if (!tu || !file)
2959 return 0;
2960
2961 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2962 FileEntry *FEnt = static_cast<FileEntry *>(file);
2963 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2964 .isFileMultipleIncludeGuarded(FEnt);
2965}
2966
Ted Kremenekfb480492010-01-13 21:46:36 +00002967} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002968
Ted Kremenekfb480492010-01-13 21:46:36 +00002969//===----------------------------------------------------------------------===//
2970// CXCursor Operations.
2971//===----------------------------------------------------------------------===//
2972
Ted Kremenekfb480492010-01-13 21:46:36 +00002973static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002974 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002975 return getDeclFromExpr(CE->getSubExpr());
2976
Ted Kremenekfb480492010-01-13 21:46:36 +00002977 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2978 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002979 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2980 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002981 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2982 return ME->getMemberDecl();
2983 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2984 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002985 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002986 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002987
Ted Kremenekfb480492010-01-13 21:46:36 +00002988 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2989 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002990 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002991 if (!CE->isElidable())
2992 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002993 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2994 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002995
Douglas Gregordb1314e2010-10-01 21:11:22 +00002996 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2997 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002998 if (SubstNonTypeTemplateParmPackExpr *NTTP
2999 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3000 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00003001 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3002 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3003 isa<ParmVarDecl>(SizeOfPack->getPack()))
3004 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00003005
Ted Kremenekfb480492010-01-13 21:46:36 +00003006 return 0;
3007}
3008
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003009static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00003010 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3011 return getLocationFromExpr(CE->getSubExpr());
3012
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003013 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3014 return /*FIXME:*/Msg->getLeftLoc();
3015 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3016 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003017 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3018 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003019 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3020 return Member->getMemberLoc();
3021 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3022 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003023 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3024 return SizeOfPack->getPackLoc();
3025
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003026 return E->getLocStart();
3027}
3028
Ted Kremenekfb480492010-01-13 21:46:36 +00003029extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003030
3031unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003032 CXCursorVisitor visitor,
3033 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003034 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003035 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003036 return CursorVis.VisitChildren(parent);
3037}
3038
David Chisnall3387c652010-11-03 14:12:26 +00003039#ifndef __has_feature
3040#define __has_feature(x) 0
3041#endif
3042#if __has_feature(blocks)
3043typedef enum CXChildVisitResult
3044 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3045
3046static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3047 CXClientData client_data) {
3048 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3049 return block(cursor, parent);
3050}
3051#else
3052// If we are compiled with a compiler that doesn't have native blocks support,
3053// define and call the block manually, so the
3054typedef struct _CXChildVisitResult
3055{
3056 void *isa;
3057 int flags;
3058 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003059 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3060 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003061} *CXCursorVisitorBlock;
3062
3063static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3064 CXClientData client_data) {
3065 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3066 return block->invoke(block, cursor, parent);
3067}
3068#endif
3069
3070
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003071unsigned clang_visitChildrenWithBlock(CXCursor parent,
3072 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003073 return clang_visitChildren(parent, visitWithBlock, block);
3074}
3075
Douglas Gregor78205d42010-01-20 21:45:58 +00003076static CXString getDeclSpelling(Decl *D) {
3077 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003078 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003079 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003080 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3081 return createCXString(Property->getIdentifier()->getName());
3082
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003083 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003084 }
3085
Douglas Gregor78205d42010-01-20 21:45:58 +00003086 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003087 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003088
Douglas Gregor78205d42010-01-20 21:45:58 +00003089 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3090 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3091 // and returns different names. NamedDecl returns the class name and
3092 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003093 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003094
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003095 if (isa<UsingDirectiveDecl>(D))
3096 return createCXString("");
3097
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003098 llvm::SmallString<1024> S;
3099 llvm::raw_svector_ostream os(S);
3100 ND->printName(os);
3101
3102 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003103}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003104
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003105CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003106 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003107 return clang_getTranslationUnitSpelling(
3108 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003109
Steve Narofff334b4e2009-09-02 18:26:48 +00003110 if (clang_isReference(C.kind)) {
3111 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003112 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003113 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003114 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003115 }
3116 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003117 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003118 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003119 }
3120 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003121 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003122 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003123 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003124 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003125 case CXCursor_CXXBaseSpecifier: {
3126 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3127 return createCXString(B->getType().getAsString());
3128 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003129 case CXCursor_TypeRef: {
3130 TypeDecl *Type = getCursorTypeRef(C).first;
3131 assert(Type && "Missing type decl");
3132
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003133 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3134 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003135 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003136 case CXCursor_TemplateRef: {
3137 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003138 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003139
3140 return createCXString(Template->getNameAsString());
3141 }
Douglas Gregor69319002010-08-31 23:48:11 +00003142
3143 case CXCursor_NamespaceRef: {
3144 NamedDecl *NS = getCursorNamespaceRef(C).first;
3145 assert(NS && "Missing namespace decl");
3146
3147 return createCXString(NS->getNameAsString());
3148 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003149
Douglas Gregora67e03f2010-09-09 21:42:20 +00003150 case CXCursor_MemberRef: {
3151 FieldDecl *Field = getCursorMemberRef(C).first;
3152 assert(Field && "Missing member decl");
3153
3154 return createCXString(Field->getNameAsString());
3155 }
3156
Douglas Gregor36897b02010-09-10 00:22:18 +00003157 case CXCursor_LabelRef: {
3158 LabelStmt *Label = getCursorLabelRef(C).first;
3159 assert(Label && "Missing label");
3160
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003161 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003162 }
3163
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003164 case CXCursor_OverloadedDeclRef: {
3165 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3166 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3167 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3168 return createCXString(ND->getNameAsString());
3169 return createCXString("");
3170 }
3171 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3172 return createCXString(E->getName().getAsString());
3173 OverloadedTemplateStorage *Ovl
3174 = Storage.get<OverloadedTemplateStorage*>();
3175 if (Ovl->size() == 0)
3176 return createCXString("");
3177 return createCXString((*Ovl->begin())->getNameAsString());
3178 }
3179
Daniel Dunbaracca7252009-11-30 20:42:49 +00003180 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003181 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003182 }
3183 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003184
3185 if (clang_isExpression(C.kind)) {
3186 Decl *D = getDeclFromExpr(getCursorExpr(C));
3187 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003188 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003189 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003190 }
3191
Douglas Gregor36897b02010-09-10 00:22:18 +00003192 if (clang_isStatement(C.kind)) {
3193 Stmt *S = getCursorStmt(C);
3194 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003195 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003196
3197 return createCXString("");
3198 }
3199
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003200 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003201 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003202 ->getNameStart());
3203
Douglas Gregor572feb22010-03-18 18:04:21 +00003204 if (C.kind == CXCursor_MacroDefinition)
3205 return createCXString(getCursorMacroDefinition(C)->getName()
3206 ->getNameStart());
3207
Douglas Gregorecdcb882010-10-20 22:00:55 +00003208 if (C.kind == CXCursor_InclusionDirective)
3209 return createCXString(getCursorInclusionDirective(C)->getFileName());
3210
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003211 if (clang_isDeclaration(C.kind))
3212 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003213
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003214 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003215}
3216
Douglas Gregor358559d2010-10-02 22:49:11 +00003217CXString clang_getCursorDisplayName(CXCursor C) {
3218 if (!clang_isDeclaration(C.kind))
3219 return clang_getCursorSpelling(C);
3220
3221 Decl *D = getCursorDecl(C);
3222 if (!D)
3223 return createCXString("");
3224
3225 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3226 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3227 D = FunTmpl->getTemplatedDecl();
3228
3229 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3230 llvm::SmallString<64> Str;
3231 llvm::raw_svector_ostream OS(Str);
3232 OS << Function->getNameAsString();
3233 if (Function->getPrimaryTemplate())
3234 OS << "<>";
3235 OS << "(";
3236 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3237 if (I)
3238 OS << ", ";
3239 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3240 }
3241
3242 if (Function->isVariadic()) {
3243 if (Function->getNumParams())
3244 OS << ", ";
3245 OS << "...";
3246 }
3247 OS << ")";
3248 return createCXString(OS.str());
3249 }
3250
3251 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3252 llvm::SmallString<64> Str;
3253 llvm::raw_svector_ostream OS(Str);
3254 OS << ClassTemplate->getNameAsString();
3255 OS << "<";
3256 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3257 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3258 if (I)
3259 OS << ", ";
3260
3261 NamedDecl *Param = Params->getParam(I);
3262 if (Param->getIdentifier()) {
3263 OS << Param->getIdentifier()->getName();
3264 continue;
3265 }
3266
3267 // There is no parameter name, which makes this tricky. Try to come up
3268 // with something useful that isn't too long.
3269 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3270 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3271 else if (NonTypeTemplateParmDecl *NTTP
3272 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3273 OS << NTTP->getType().getAsString(Policy);
3274 else
3275 OS << "template<...> class";
3276 }
3277
3278 OS << ">";
3279 return createCXString(OS.str());
3280 }
3281
3282 if (ClassTemplateSpecializationDecl *ClassSpec
3283 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3284 // If the type was explicitly written, use that.
3285 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3286 return createCXString(TSInfo->getType().getAsString(Policy));
3287
3288 llvm::SmallString<64> Str;
3289 llvm::raw_svector_ostream OS(Str);
3290 OS << ClassSpec->getNameAsString();
3291 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003292 ClassSpec->getTemplateArgs().data(),
3293 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003294 Policy);
3295 return createCXString(OS.str());
3296 }
3297
3298 return clang_getCursorSpelling(C);
3299}
3300
Ted Kremeneke68fff62010-02-17 00:41:32 +00003301CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003302 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003303 case CXCursor_FunctionDecl:
3304 return createCXString("FunctionDecl");
3305 case CXCursor_TypedefDecl:
3306 return createCXString("TypedefDecl");
3307 case CXCursor_EnumDecl:
3308 return createCXString("EnumDecl");
3309 case CXCursor_EnumConstantDecl:
3310 return createCXString("EnumConstantDecl");
3311 case CXCursor_StructDecl:
3312 return createCXString("StructDecl");
3313 case CXCursor_UnionDecl:
3314 return createCXString("UnionDecl");
3315 case CXCursor_ClassDecl:
3316 return createCXString("ClassDecl");
3317 case CXCursor_FieldDecl:
3318 return createCXString("FieldDecl");
3319 case CXCursor_VarDecl:
3320 return createCXString("VarDecl");
3321 case CXCursor_ParmDecl:
3322 return createCXString("ParmDecl");
3323 case CXCursor_ObjCInterfaceDecl:
3324 return createCXString("ObjCInterfaceDecl");
3325 case CXCursor_ObjCCategoryDecl:
3326 return createCXString("ObjCCategoryDecl");
3327 case CXCursor_ObjCProtocolDecl:
3328 return createCXString("ObjCProtocolDecl");
3329 case CXCursor_ObjCPropertyDecl:
3330 return createCXString("ObjCPropertyDecl");
3331 case CXCursor_ObjCIvarDecl:
3332 return createCXString("ObjCIvarDecl");
3333 case CXCursor_ObjCInstanceMethodDecl:
3334 return createCXString("ObjCInstanceMethodDecl");
3335 case CXCursor_ObjCClassMethodDecl:
3336 return createCXString("ObjCClassMethodDecl");
3337 case CXCursor_ObjCImplementationDecl:
3338 return createCXString("ObjCImplementationDecl");
3339 case CXCursor_ObjCCategoryImplDecl:
3340 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003341 case CXCursor_CXXMethod:
3342 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003343 case CXCursor_UnexposedDecl:
3344 return createCXString("UnexposedDecl");
3345 case CXCursor_ObjCSuperClassRef:
3346 return createCXString("ObjCSuperClassRef");
3347 case CXCursor_ObjCProtocolRef:
3348 return createCXString("ObjCProtocolRef");
3349 case CXCursor_ObjCClassRef:
3350 return createCXString("ObjCClassRef");
3351 case CXCursor_TypeRef:
3352 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003353 case CXCursor_TemplateRef:
3354 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003355 case CXCursor_NamespaceRef:
3356 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003357 case CXCursor_MemberRef:
3358 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003359 case CXCursor_LabelRef:
3360 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003361 case CXCursor_OverloadedDeclRef:
3362 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003363 case CXCursor_UnexposedExpr:
3364 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003365 case CXCursor_BlockExpr:
3366 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003367 case CXCursor_DeclRefExpr:
3368 return createCXString("DeclRefExpr");
3369 case CXCursor_MemberRefExpr:
3370 return createCXString("MemberRefExpr");
3371 case CXCursor_CallExpr:
3372 return createCXString("CallExpr");
3373 case CXCursor_ObjCMessageExpr:
3374 return createCXString("ObjCMessageExpr");
3375 case CXCursor_UnexposedStmt:
3376 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003377 case CXCursor_LabelStmt:
3378 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003379 case CXCursor_InvalidFile:
3380 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003381 case CXCursor_InvalidCode:
3382 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003383 case CXCursor_NoDeclFound:
3384 return createCXString("NoDeclFound");
3385 case CXCursor_NotImplemented:
3386 return createCXString("NotImplemented");
3387 case CXCursor_TranslationUnit:
3388 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003389 case CXCursor_UnexposedAttr:
3390 return createCXString("UnexposedAttr");
3391 case CXCursor_IBActionAttr:
3392 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003393 case CXCursor_IBOutletAttr:
3394 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003395 case CXCursor_IBOutletCollectionAttr:
3396 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003397 case CXCursor_CXXFinalAttr:
3398 return createCXString("attribute(final)");
3399 case CXCursor_CXXOverrideAttr:
3400 return createCXString("attribute(override)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003401 case CXCursor_PreprocessingDirective:
3402 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003403 case CXCursor_MacroDefinition:
3404 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003405 case CXCursor_MacroExpansion:
3406 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003407 case CXCursor_InclusionDirective:
3408 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003409 case CXCursor_Namespace:
3410 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003411 case CXCursor_LinkageSpec:
3412 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003413 case CXCursor_CXXBaseSpecifier:
3414 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003415 case CXCursor_Constructor:
3416 return createCXString("CXXConstructor");
3417 case CXCursor_Destructor:
3418 return createCXString("CXXDestructor");
3419 case CXCursor_ConversionFunction:
3420 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003421 case CXCursor_TemplateTypeParameter:
3422 return createCXString("TemplateTypeParameter");
3423 case CXCursor_NonTypeTemplateParameter:
3424 return createCXString("NonTypeTemplateParameter");
3425 case CXCursor_TemplateTemplateParameter:
3426 return createCXString("TemplateTemplateParameter");
3427 case CXCursor_FunctionTemplate:
3428 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003429 case CXCursor_ClassTemplate:
3430 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003431 case CXCursor_ClassTemplatePartialSpecialization:
3432 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003433 case CXCursor_NamespaceAlias:
3434 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003435 case CXCursor_UsingDirective:
3436 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003437 case CXCursor_UsingDeclaration:
3438 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003439 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003440 return createCXString("TypeAliasDecl");
3441 case CXCursor_ObjCSynthesizeDecl:
3442 return createCXString("ObjCSynthesizeDecl");
3443 case CXCursor_ObjCDynamicDecl:
3444 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003445 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003446
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003447 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003448 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003449}
Steve Naroff89922f82009-08-31 00:59:03 +00003450
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003451struct GetCursorData {
3452 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003453 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003454 CXCursor &BestCursor;
3455
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003456 GetCursorData(SourceManager &SM,
3457 SourceLocation tokenBegin, CXCursor &outputCursor)
3458 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3459 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3460 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003461};
3462
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003463static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3464 CXCursor parent,
3465 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003466 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3467 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003468
3469 // If we point inside a macro argument we should provide info of what the
3470 // token is so use the actual cursor, don't replace it with a macro expansion
3471 // cursor.
3472 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3473 return CXChildVisit_Recurse;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003474
3475 if (clang_isExpression(cursor.kind) &&
3476 clang_isDeclaration(BestCursor->kind)) {
3477 Decl *D = getCursorDecl(*BestCursor);
3478
3479 // Avoid having the cursor of an expression replace the declaration cursor
3480 // when the expression source range overlaps the declaration range.
3481 // This can happen for C++ constructor expressions whose range generally
3482 // include the variable declaration, e.g.:
3483 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3484 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3485 D->getLocation() == Data->TokenBeginLoc)
3486 return CXChildVisit_Break;
3487 }
3488
Douglas Gregor93798e22010-11-05 21:11:19 +00003489 // If our current best cursor is the construction of a temporary object,
3490 // don't replace that cursor with a type reference, because we want
3491 // clang_getCursor() to point at the constructor.
3492 if (clang_isExpression(BestCursor->kind) &&
3493 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3494 cursor.kind == CXCursor_TypeRef)
3495 return CXChildVisit_Recurse;
3496
Douglas Gregor85fe1562010-12-10 07:23:11 +00003497 // Don't override a preprocessing cursor with another preprocessing
3498 // cursor; we want the outermost preprocessing cursor.
3499 if (clang_isPreprocessing(cursor.kind) &&
3500 clang_isPreprocessing(BestCursor->kind))
3501 return CXChildVisit_Recurse;
3502
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003503 *BestCursor = cursor;
3504 return CXChildVisit_Recurse;
3505}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003506
Douglas Gregorb9790342010-01-22 21:44:22 +00003507CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3508 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003509 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003510
Ted Kremeneka60ed472010-11-16 08:15:36 +00003511 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003512 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3513
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003514 // Translate the given source location to make it point at the beginning of
3515 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003516 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003517
3518 // Guard against an invalid SourceLocation, or we may assert in one
3519 // of the following calls.
3520 if (SLoc.isInvalid())
3521 return clang_getNullCursor();
3522
Douglas Gregor40749ee2010-11-03 00:35:38 +00003523 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003524 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3525 CXXUnit->getASTContext().getLangOptions());
3526
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003527 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3528 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003529 // FIXME: Would be great to have a "hint" cursor, then walk from that
3530 // hint cursor upward until we find a cursor whose source range encloses
3531 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003532 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003533 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003534 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00003535 /*VisitPreprocessorLast=*/true,
3536 SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003537 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003538 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003539
3540 if (Logging) {
3541 CXFile SearchFile;
3542 unsigned SearchLine, SearchColumn;
3543 CXFile ResultFile;
3544 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003545 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3546 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003547 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3548
Chandler Carruth20174222011-08-31 16:53:37 +00003549 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3550 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3551 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003552 SearchFileName = clang_getFileName(SearchFile);
3553 ResultFileName = clang_getFileName(ResultFile);
3554 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003555 USR = clang_getCursorUSR(Result);
3556 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003557 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3558 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003559 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3560 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003561 clang_disposeString(SearchFileName);
3562 clang_disposeString(ResultFileName);
3563 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003564 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003565
3566 CXCursor Definition = clang_getCursorDefinition(Result);
3567 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3568 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3569 CXString DefinitionKindSpelling
3570 = clang_getCursorKindSpelling(Definition.kind);
3571 CXFile DefinitionFile;
3572 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003573 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3574 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003575 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3576 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3577 clang_getCString(DefinitionKindSpelling),
3578 clang_getCString(DefinitionFileName),
3579 DefinitionLine, DefinitionColumn);
3580 clang_disposeString(DefinitionFileName);
3581 clang_disposeString(DefinitionKindSpelling);
3582 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003583 }
3584
Ted Kremeneke68fff62010-02-17 00:41:32 +00003585 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003586}
3587
Ted Kremenek73885552009-11-17 19:28:59 +00003588CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003589 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003590}
3591
3592unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003593 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003594}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003595
Douglas Gregor9ce55842010-11-20 00:09:34 +00003596unsigned clang_hashCursor(CXCursor C) {
3597 unsigned Index = 0;
3598 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3599 Index = 1;
3600
3601 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3602 std::make_pair(C.kind, C.data[Index]));
3603}
3604
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003605unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003606 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3607}
3608
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003609unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003610 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3611}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003612
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003613unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003614 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3615}
3616
Douglas Gregor97b98722010-01-19 23:20:36 +00003617unsigned clang_isExpression(enum CXCursorKind K) {
3618 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3619}
3620
3621unsigned clang_isStatement(enum CXCursorKind K) {
3622 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3623}
3624
Douglas Gregor8be80e12011-07-06 03:00:34 +00003625unsigned clang_isAttribute(enum CXCursorKind K) {
3626 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3627}
3628
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003629unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3630 return K == CXCursor_TranslationUnit;
3631}
3632
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003633unsigned clang_isPreprocessing(enum CXCursorKind K) {
3634 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3635}
3636
Ted Kremenekad6eff62010-03-08 21:17:29 +00003637unsigned clang_isUnexposed(enum CXCursorKind K) {
3638 switch (K) {
3639 case CXCursor_UnexposedDecl:
3640 case CXCursor_UnexposedExpr:
3641 case CXCursor_UnexposedStmt:
3642 case CXCursor_UnexposedAttr:
3643 return true;
3644 default:
3645 return false;
3646 }
3647}
3648
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003649CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003650 return C.kind;
3651}
3652
Douglas Gregor98258af2010-01-18 22:46:11 +00003653CXSourceLocation clang_getCursorLocation(CXCursor C) {
3654 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003655 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003656 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003657 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3658 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003659 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003660 }
3661
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003662 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003663 std::pair<ObjCProtocolDecl *, SourceLocation> P
3664 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003665 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003666 }
3667
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003668 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003669 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3670 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003671 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003672 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003673
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003674 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003675 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003676 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003677 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003678
3679 case CXCursor_TemplateRef: {
3680 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3681 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3682 }
3683
Douglas Gregor69319002010-08-31 23:48:11 +00003684 case CXCursor_NamespaceRef: {
3685 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3686 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3687 }
3688
Douglas Gregora67e03f2010-09-09 21:42:20 +00003689 case CXCursor_MemberRef: {
3690 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3691 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3692 }
3693
Ted Kremenek3064ef92010-08-27 21:34:58 +00003694 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003695 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3696 if (!BaseSpec)
3697 return clang_getNullLocation();
3698
3699 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3700 return cxloc::translateSourceLocation(getCursorContext(C),
3701 TSInfo->getTypeLoc().getBeginLoc());
3702
3703 return cxloc::translateSourceLocation(getCursorContext(C),
3704 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003705 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003706
Douglas Gregor36897b02010-09-10 00:22:18 +00003707 case CXCursor_LabelRef: {
3708 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3709 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3710 }
3711
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003712 case CXCursor_OverloadedDeclRef:
3713 return cxloc::translateSourceLocation(getCursorContext(C),
3714 getCursorOverloadedDeclRef(C).second);
3715
Douglas Gregorf46034a2010-01-18 23:41:10 +00003716 default:
3717 // FIXME: Need a way to enumerate all non-reference cases.
3718 llvm_unreachable("Missed a reference kind");
3719 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003720 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003721
3722 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003723 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003724 getLocationFromExpr(getCursorExpr(C)));
3725
Douglas Gregor36897b02010-09-10 00:22:18 +00003726 if (clang_isStatement(C.kind))
3727 return cxloc::translateSourceLocation(getCursorContext(C),
3728 getCursorStmt(C)->getLocStart());
3729
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003730 if (C.kind == CXCursor_PreprocessingDirective) {
3731 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3732 return cxloc::translateSourceLocation(getCursorContext(C), L);
3733 }
Douglas Gregor48072312010-03-18 15:23:44 +00003734
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003735 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003736 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003737 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003738 return cxloc::translateSourceLocation(getCursorContext(C), L);
3739 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003740
3741 if (C.kind == CXCursor_MacroDefinition) {
3742 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3743 return cxloc::translateSourceLocation(getCursorContext(C), L);
3744 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003745
3746 if (C.kind == CXCursor_InclusionDirective) {
3747 SourceLocation L
3748 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3749 return cxloc::translateSourceLocation(getCursorContext(C), L);
3750 }
3751
Ted Kremenek9a700d22010-05-12 06:16:13 +00003752 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003753 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003754
Douglas Gregorf46034a2010-01-18 23:41:10 +00003755 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003756 SourceLocation Loc = D->getLocation();
3757 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3758 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003759 // FIXME: Multiple variables declared in a single declaration
3760 // currently lack the information needed to correctly determine their
3761 // ranges when accounting for the type-specifier. We use context
3762 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3763 // and if so, whether it is the first decl.
3764 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3765 if (!cxcursor::isFirstInDeclGroup(C))
3766 Loc = VD->getLocation();
3767 }
3768
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003769 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003770}
Douglas Gregora7bde202010-01-19 00:34:46 +00003771
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003772} // end extern "C"
3773
3774static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003775 if (clang_isReference(C.kind)) {
3776 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003777 case CXCursor_ObjCSuperClassRef:
3778 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003779
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003780 case CXCursor_ObjCProtocolRef:
3781 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003782
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003783 case CXCursor_ObjCClassRef:
3784 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003785
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003786 case CXCursor_TypeRef:
3787 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003788
3789 case CXCursor_TemplateRef:
3790 return getCursorTemplateRef(C).second;
3791
Douglas Gregor69319002010-08-31 23:48:11 +00003792 case CXCursor_NamespaceRef:
3793 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003794
3795 case CXCursor_MemberRef:
3796 return getCursorMemberRef(C).second;
3797
Ted Kremenek3064ef92010-08-27 21:34:58 +00003798 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003799 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003800
Douglas Gregor36897b02010-09-10 00:22:18 +00003801 case CXCursor_LabelRef:
3802 return getCursorLabelRef(C).second;
3803
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003804 case CXCursor_OverloadedDeclRef:
3805 return getCursorOverloadedDeclRef(C).second;
3806
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003807 default:
3808 // FIXME: Need a way to enumerate all non-reference cases.
3809 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003810 }
3811 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003812
3813 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003814 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003815
3816 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003817 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003818
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003819 if (clang_isAttribute(C.kind))
3820 return getCursorAttr(C)->getRange();
3821
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003822 if (C.kind == CXCursor_PreprocessingDirective)
3823 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003824
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003825 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003826 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003827
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003828 if (C.kind == CXCursor_MacroDefinition)
3829 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003830
3831 if (C.kind == CXCursor_InclusionDirective)
3832 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3833
Ted Kremenek007a7c92010-11-01 23:26:51 +00003834 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3835 Decl *D = cxcursor::getCursorDecl(C);
3836 SourceRange R = D->getSourceRange();
3837 // FIXME: Multiple variables declared in a single declaration
3838 // currently lack the information needed to correctly determine their
3839 // ranges when accounting for the type-specifier. We use context
3840 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3841 // and if so, whether it is the first decl.
3842 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3843 if (!cxcursor::isFirstInDeclGroup(C))
3844 R.setBegin(VD->getLocation());
3845 }
3846 return R;
3847 }
Douglas Gregor66537982010-11-17 17:14:07 +00003848 return SourceRange();
3849}
3850
3851/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3852/// the decl-specifier-seq for declarations.
3853static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3854 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3855 Decl *D = cxcursor::getCursorDecl(C);
3856 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003857
Douglas Gregor2494dd02011-03-01 01:34:45 +00003858 // Adjust the start of the location for declarations preceded by
3859 // declaration specifiers.
3860 SourceLocation StartLoc;
3861 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3862 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3863 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3864 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3865 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3866 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3867 }
3868
3869 if (StartLoc.isValid() && R.getBegin().isValid() &&
3870 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3871 R.setBegin(StartLoc);
3872
3873 // FIXME: Multiple variables declared in a single declaration
3874 // currently lack the information needed to correctly determine their
3875 // ranges when accounting for the type-specifier. We use context
3876 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3877 // and if so, whether it is the first decl.
3878 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3879 if (!cxcursor::isFirstInDeclGroup(C))
3880 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003881 }
3882
3883 return R;
3884 }
3885
3886 return getRawCursorExtent(C);
3887}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003888
3889extern "C" {
3890
3891CXSourceRange clang_getCursorExtent(CXCursor C) {
3892 SourceRange R = getRawCursorExtent(C);
3893 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003894 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003895
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003896 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003897}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003898
3899CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003900 if (clang_isInvalid(C.kind))
3901 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003902
Ted Kremeneka60ed472010-11-16 08:15:36 +00003903 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003904 if (clang_isDeclaration(C.kind)) {
3905 Decl *D = getCursorDecl(C);
3906 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003907 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003908 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003909 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003910 if (ObjCForwardProtocolDecl *Protocols
3911 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003912 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003913 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003914 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3915 return MakeCXCursor(Property, tu);
3916
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003917 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003918 }
3919
Douglas Gregor97b98722010-01-19 23:20:36 +00003920 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003921 Expr *E = getCursorExpr(C);
3922 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003923 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003924 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003925
3926 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003927 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003928
Douglas Gregor97b98722010-01-19 23:20:36 +00003929 return clang_getNullCursor();
3930 }
3931
Douglas Gregor36897b02010-09-10 00:22:18 +00003932 if (clang_isStatement(C.kind)) {
3933 Stmt *S = getCursorStmt(C);
3934 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003935 if (LabelDecl *label = Goto->getLabel())
3936 if (LabelStmt *labelS = label->getStmt())
3937 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003938
3939 return clang_getNullCursor();
3940 }
3941
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003942 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003943 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003944 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003945 }
3946
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003947 if (!clang_isReference(C.kind))
3948 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003949
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003950 switch (C.kind) {
3951 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003952 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003953
3954 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003955 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003956
3957 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003958 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003959
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003960 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003961 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003962
3963 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003964 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003965
Douglas Gregor69319002010-08-31 23:48:11 +00003966 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003967 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003968
Douglas Gregora67e03f2010-09-09 21:42:20 +00003969 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003970 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003971
Ted Kremenek3064ef92010-08-27 21:34:58 +00003972 case CXCursor_CXXBaseSpecifier: {
3973 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3974 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003975 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003976 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003977
Douglas Gregor36897b02010-09-10 00:22:18 +00003978 case CXCursor_LabelRef:
3979 // FIXME: We end up faking the "parent" declaration here because we
3980 // don't want to make CXCursor larger.
3981 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003982 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3983 .getTranslationUnitDecl(),
3984 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003985
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003986 case CXCursor_OverloadedDeclRef:
3987 return C;
3988
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003989 default:
3990 // We would prefer to enumerate all non-reference cursor kinds here.
3991 llvm_unreachable("Unhandled reference cursor kind");
3992 break;
3993 }
3994 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003995
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003996 return clang_getNullCursor();
3997}
3998
Douglas Gregorb6998662010-01-19 19:34:47 +00003999CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004000 if (clang_isInvalid(C.kind))
4001 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004002
Ted Kremeneka60ed472010-11-16 08:15:36 +00004003 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004004
Douglas Gregorb6998662010-01-19 19:34:47 +00004005 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004006 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004007 C = clang_getCursorReferenced(C);
4008 WasReference = true;
4009 }
4010
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004011 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004012 return clang_getCursorReferenced(C);
4013
Douglas Gregorb6998662010-01-19 19:34:47 +00004014 if (!clang_isDeclaration(C.kind))
4015 return clang_getNullCursor();
4016
4017 Decl *D = getCursorDecl(C);
4018 if (!D)
4019 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004020
Douglas Gregorb6998662010-01-19 19:34:47 +00004021 switch (D->getKind()) {
4022 // Declaration kinds that don't really separate the notions of
4023 // declaration and definition.
4024 case Decl::Namespace:
4025 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004026 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004027 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004028 case Decl::TemplateTypeParm:
4029 case Decl::EnumConstant:
4030 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004031 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004032 case Decl::ObjCIvar:
4033 case Decl::ObjCAtDefsField:
4034 case Decl::ImplicitParam:
4035 case Decl::ParmVar:
4036 case Decl::NonTypeTemplateParm:
4037 case Decl::TemplateTemplateParm:
4038 case Decl::ObjCCategoryImpl:
4039 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004040 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004041 case Decl::LinkageSpec:
4042 case Decl::ObjCPropertyImpl:
4043 case Decl::FileScopeAsm:
4044 case Decl::StaticAssert:
4045 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004046 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004047 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004048 return C;
4049
4050 // Declaration kinds that don't make any sense here, but are
4051 // nonetheless harmless.
4052 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004053 break;
4054
4055 // Declaration kinds for which the definition is not resolvable.
4056 case Decl::UnresolvedUsingTypename:
4057 case Decl::UnresolvedUsingValue:
4058 break;
4059
4060 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004061 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004062 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004063
4064 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004065 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004066
4067 case Decl::Enum:
4068 case Decl::Record:
4069 case Decl::CXXRecord:
4070 case Decl::ClassTemplateSpecialization:
4071 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004072 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004073 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004074 return clang_getNullCursor();
4075
4076 case Decl::Function:
4077 case Decl::CXXMethod:
4078 case Decl::CXXConstructor:
4079 case Decl::CXXDestructor:
4080 case Decl::CXXConversion: {
4081 const FunctionDecl *Def = 0;
4082 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004083 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004084 return clang_getNullCursor();
4085 }
4086
4087 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004088 // Ask the variable if it has a definition.
4089 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004090 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004091 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004092 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004093
Douglas Gregorb6998662010-01-19 19:34:47 +00004094 case Decl::FunctionTemplate: {
4095 const FunctionDecl *Def = 0;
4096 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004097 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004098 return clang_getNullCursor();
4099 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004100
Douglas Gregorb6998662010-01-19 19:34:47 +00004101 case Decl::ClassTemplate: {
4102 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004103 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004104 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004105 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004106 return clang_getNullCursor();
4107 }
4108
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004109 case Decl::Using:
4110 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004111 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004112
4113 case Decl::UsingShadow:
4114 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004115 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004116 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004117
4118 case Decl::ObjCMethod: {
4119 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4120 if (Method->isThisDeclarationADefinition())
4121 return C;
4122
4123 // Dig out the method definition in the associated
4124 // @implementation, if we have it.
4125 // FIXME: The ASTs should make finding the definition easier.
4126 if (ObjCInterfaceDecl *Class
4127 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4128 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4129 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4130 Method->isInstanceMethod()))
4131 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004132 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004133
4134 return clang_getNullCursor();
4135 }
4136
4137 case Decl::ObjCCategory:
4138 if (ObjCCategoryImplDecl *Impl
4139 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004140 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004141 return clang_getNullCursor();
4142
4143 case Decl::ObjCProtocol:
4144 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4145 return C;
4146 return clang_getNullCursor();
4147
4148 case Decl::ObjCInterface:
4149 // There are two notions of a "definition" for an Objective-C
4150 // class: the interface and its implementation. When we resolved a
4151 // reference to an Objective-C class, produce the @interface as
4152 // the definition; when we were provided with the interface,
4153 // produce the @implementation as the definition.
4154 if (WasReference) {
4155 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4156 return C;
4157 } else if (ObjCImplementationDecl *Impl
4158 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004159 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004160 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004161
Douglas Gregorb6998662010-01-19 19:34:47 +00004162 case Decl::ObjCProperty:
4163 // FIXME: We don't really know where to find the
4164 // ObjCPropertyImplDecls that implement this property.
4165 return clang_getNullCursor();
4166
4167 case Decl::ObjCCompatibleAlias:
4168 if (ObjCInterfaceDecl *Class
4169 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4170 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004171 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004172
Douglas Gregorb6998662010-01-19 19:34:47 +00004173 return clang_getNullCursor();
4174
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004175 case Decl::ObjCForwardProtocol:
4176 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004177 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004178
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004179 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004180 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004181 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004182
4183 case Decl::Friend:
4184 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004185 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004186 return clang_getNullCursor();
4187
4188 case Decl::FriendTemplate:
4189 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004190 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004191 return clang_getNullCursor();
4192 }
4193
4194 return clang_getNullCursor();
4195}
4196
4197unsigned clang_isCursorDefinition(CXCursor C) {
4198 if (!clang_isDeclaration(C.kind))
4199 return 0;
4200
4201 return clang_getCursorDefinition(C) == C;
4202}
4203
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004204CXCursor clang_getCanonicalCursor(CXCursor C) {
4205 if (!clang_isDeclaration(C.kind))
4206 return C;
4207
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004208 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004209 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4210 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4211 return MakeCXCursor(CatD, getCursorTU(C));
4212
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004213 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4214 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4215 return MakeCXCursor(IFD, getCursorTU(C));
4216
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004217 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004218 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004219
4220 return C;
4221}
4222
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004223unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004224 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004225 return 0;
4226
4227 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4228 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4229 return E->getNumDecls();
4230
4231 if (OverloadedTemplateStorage *S
4232 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4233 return S->size();
4234
4235 Decl *D = Storage.get<Decl*>();
4236 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004237 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004238 if (isa<ObjCClassDecl>(D))
4239 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004240 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4241 return Protocols->protocol_size();
4242
4243 return 0;
4244}
4245
4246CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004247 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004248 return clang_getNullCursor();
4249
4250 if (index >= clang_getNumOverloadedDecls(cursor))
4251 return clang_getNullCursor();
4252
Ted Kremeneka60ed472010-11-16 08:15:36 +00004253 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004254 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4255 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004256 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004257
4258 if (OverloadedTemplateStorage *S
4259 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004260 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004261
4262 Decl *D = Storage.get<Decl*>();
4263 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4264 // FIXME: This is, unfortunately, linear time.
4265 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4266 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004267 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004268 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004269 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004270 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004271 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004272 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004273
4274 return clang_getNullCursor();
4275}
4276
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004277void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004278 const char **startBuf,
4279 const char **endBuf,
4280 unsigned *startLine,
4281 unsigned *startColumn,
4282 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004283 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004284 assert(getCursorDecl(C) && "CXCursor has null decl");
4285 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004286 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4287 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004288
Steve Naroff4ade6d62009-09-23 17:52:52 +00004289 SourceManager &SM = FD->getASTContext().getSourceManager();
4290 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4291 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4292 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4293 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4294 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4295 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4296}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004297
Douglas Gregor430d7a12011-07-25 17:48:11 +00004298
4299CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4300 unsigned PieceIndex) {
4301 RefNamePieces Pieces;
4302
4303 switch (C.kind) {
4304 case CXCursor_MemberRefExpr:
4305 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4306 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4307 E->getQualifierLoc().getSourceRange());
4308 break;
4309
4310 case CXCursor_DeclRefExpr:
4311 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4312 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4313 E->getQualifierLoc().getSourceRange(),
4314 E->getExplicitTemplateArgsOpt());
4315 break;
4316
4317 case CXCursor_CallExpr:
4318 if (CXXOperatorCallExpr *OCE =
4319 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4320 Expr *Callee = OCE->getCallee();
4321 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4322 Callee = ICE->getSubExpr();
4323
4324 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4325 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4326 DRE->getQualifierLoc().getSourceRange());
4327 }
4328 break;
4329
4330 default:
4331 break;
4332 }
4333
4334 if (Pieces.empty()) {
4335 if (PieceIndex == 0)
4336 return clang_getCursorExtent(C);
4337 } else if (PieceIndex < Pieces.size()) {
4338 SourceRange R = Pieces[PieceIndex];
4339 if (R.isValid())
4340 return cxloc::translateSourceRange(getCursorContext(C), R);
4341 }
4342
4343 return clang_getNullRange();
4344}
4345
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004346void clang_enableStackTraces(void) {
4347 llvm::sys::PrintStackTraceOnErrorSignal();
4348}
4349
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004350void clang_executeOnThread(void (*fn)(void*), void *user_data,
4351 unsigned stack_size) {
4352 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4353}
4354
Ted Kremenekfb480492010-01-13 21:46:36 +00004355} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004356
Ted Kremenekfb480492010-01-13 21:46:36 +00004357//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004358// Token-based Operations.
4359//===----------------------------------------------------------------------===//
4360
4361/* CXToken layout:
4362 * int_data[0]: a CXTokenKind
4363 * int_data[1]: starting token location
4364 * int_data[2]: token length
4365 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004366 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004367 * otherwise unused.
4368 */
4369extern "C" {
4370
4371CXTokenKind clang_getTokenKind(CXToken CXTok) {
4372 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4373}
4374
4375CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4376 switch (clang_getTokenKind(CXTok)) {
4377 case CXToken_Identifier:
4378 case CXToken_Keyword:
4379 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004380 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4381 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004382
4383 case CXToken_Literal: {
4384 // We have stashed the starting pointer in the ptr_data field. Use it.
4385 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004386 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004387 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004388
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004389 case CXToken_Punctuation:
4390 case CXToken_Comment:
4391 break;
4392 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004393
4394 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004395 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004396 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004397 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004398 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004399
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004400 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4401 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004402 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004403 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004404 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004405 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4406 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004407 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004408
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004409 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004410}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004411
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004412CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004413 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004414 if (!CXXUnit)
4415 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004416
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004417 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4418 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4419}
4420
4421CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004422 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004423 if (!CXXUnit)
4424 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004425
4426 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004427 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4428}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004429
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004430void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4431 CXToken **Tokens, unsigned *NumTokens) {
4432 if (Tokens)
4433 *Tokens = 0;
4434 if (NumTokens)
4435 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004436
Ted Kremeneka60ed472010-11-16 08:15:36 +00004437 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004438 if (!CXXUnit || !Tokens || !NumTokens)
4439 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004440
Douglas Gregorbdf60622010-03-05 21:16:25 +00004441 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4442
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004443 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004444 if (R.isInvalid())
4445 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004446
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004447 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4448 std::pair<FileID, unsigned> BeginLocInfo
4449 = SourceMgr.getDecomposedLoc(R.getBegin());
4450 std::pair<FileID, unsigned> EndLocInfo
4451 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004452
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004453 // Cannot tokenize across files.
4454 if (BeginLocInfo.first != EndLocInfo.first)
4455 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004456
4457 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004458 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004459 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004460 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004461 if (Invalid)
4462 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004463
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004464 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4465 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004466 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004467 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004468
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004469 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004470 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004471 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004472 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004473 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004474 do {
4475 // Lex the next token
4476 Lex.LexFromRawLexer(Tok);
4477 if (Tok.is(tok::eof))
4478 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004479
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004480 // Initialize the CXToken.
4481 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004482
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004483 // - Common fields
4484 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4485 CXTok.int_data[2] = Tok.getLength();
4486 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004487
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004488 // - Kind-specific fields
4489 if (Tok.isLiteral()) {
4490 CXTok.int_data[0] = CXToken_Literal;
4491 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004492 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004493 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004494 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004495 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004496
David Chisnall096428b2010-10-13 21:44:48 +00004497 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004498 CXTok.int_data[0] = CXToken_Keyword;
4499 }
4500 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004501 CXTok.int_data[0] = Tok.is(tok::identifier)
4502 ? CXToken_Identifier
4503 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004504 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004505 CXTok.ptr_data = II;
4506 } else if (Tok.is(tok::comment)) {
4507 CXTok.int_data[0] = CXToken_Comment;
4508 CXTok.ptr_data = 0;
4509 } else {
4510 CXTok.int_data[0] = CXToken_Punctuation;
4511 CXTok.ptr_data = 0;
4512 }
4513 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004514 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004515 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004516
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004517 if (CXTokens.empty())
4518 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004519
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004520 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4521 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4522 *NumTokens = CXTokens.size();
4523}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004524
Ted Kremenek6db61092010-05-05 00:55:15 +00004525void clang_disposeTokens(CXTranslationUnit TU,
4526 CXToken *Tokens, unsigned NumTokens) {
4527 free(Tokens);
4528}
4529
4530} // end: extern "C"
4531
4532//===----------------------------------------------------------------------===//
4533// Token annotation APIs.
4534//===----------------------------------------------------------------------===//
4535
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004536typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004537static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4538 CXCursor parent,
4539 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004540namespace {
4541class AnnotateTokensWorker {
4542 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004543 CXToken *Tokens;
4544 CXCursor *Cursors;
4545 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004546 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004547 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004548 CursorVisitor AnnotateVis;
4549 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004550 bool HasContextSensitiveKeywords;
4551
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004552 bool MoreTokens() const { return TokIdx < NumTokens; }
4553 unsigned NextToken() const { return TokIdx; }
4554 void AdvanceToken() { ++TokIdx; }
4555 SourceLocation GetTokenLoc(unsigned tokI) {
4556 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4557 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004558 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004559 return Tokens[tokI].int_data[3] != 0;
4560 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004561 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004562 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4563 }
4564
4565 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004566 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4567 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004568
Ted Kremenek6db61092010-05-05 00:55:15 +00004569public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004570 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004571 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004572 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004573 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004574 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004575 AnnotateVis(tu,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00004576 AnnotateTokensVisitor, this, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004577 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4578 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004579
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004580 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004581 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004582 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004583 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004584 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004585 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004586
4587 /// \brief Determine whether the annotator saw any cursors that have
4588 /// context-sensitive keywords.
4589 bool hasContextSensitiveKeywords() const {
4590 return HasContextSensitiveKeywords;
4591 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004592};
4593}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004594
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004595void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4596 // Walk the AST within the region of interest, annotating tokens
4597 // along the way.
4598 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004599
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004600 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4601 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004602 if (Pos != Annotated.end() &&
4603 (clang_isInvalid(Cursors[I].kind) ||
4604 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004605 Cursors[I] = Pos->second;
4606 }
4607
4608 // Finish up annotating any tokens left.
4609 if (!MoreTokens())
4610 return;
4611
4612 const CXCursor &C = clang_getNullCursor();
4613 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4614 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4615 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004616 }
4617}
4618
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004619/// \brief It annotates and advances tokens with a cursor until the comparison
4620//// between the cursor location and the source range is the same as
4621/// \arg compResult.
4622///
4623/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4624/// Pass RangeOverlap to annotate tokens inside a range.
4625void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4626 RangeComparisonResult compResult,
4627 SourceRange range) {
4628 while (MoreTokens()) {
4629 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004630 if (isFunctionMacroToken(I))
4631 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004632
4633 SourceLocation TokLoc = GetTokenLoc(I);
4634 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4635 Cursors[I] = updateC;
4636 AdvanceToken();
4637 continue;
4638 }
4639 break;
4640 }
4641}
4642
4643/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004644void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4645 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004646 RangeComparisonResult compResult,
4647 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004648 assert(MoreTokens());
4649 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004650 "Should be called only for macro arg tokens");
4651
4652 // This works differently than annotateAndAdvanceTokens; because expanded
4653 // macro arguments can have arbitrary translation-unit source order, we do not
4654 // advance the token index one by one until a token fails the range test.
4655 // We only advance once past all of the macro arg tokens if all of them
4656 // pass the range test. If one of them fails we keep the token index pointing
4657 // at the start of the macro arg tokens so that the failing token will be
4658 // annotated by a subsequent annotation try.
4659
4660 bool atLeastOneCompFail = false;
4661
4662 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004663 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4664 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004665 if (TokLoc.isFileID())
4666 continue; // not macro arg token, it's parens or comma.
4667 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4668 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4669 Cursors[I] = updateC;
4670 } else
4671 atLeastOneCompFail = true;
4672 }
4673
4674 if (!atLeastOneCompFail)
4675 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4676}
4677
Ted Kremenek6db61092010-05-05 00:55:15 +00004678enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004679AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004680 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004681 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004682 if (cursorRange.isInvalid())
4683 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004684
4685 if (!HasContextSensitiveKeywords) {
4686 // Objective-C properties can have context-sensitive keywords.
4687 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4688 if (ObjCPropertyDecl *Property
4689 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4690 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4691 }
4692 // Objective-C methods can have context-sensitive keywords.
4693 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4694 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4695 if (ObjCMethodDecl *Method
4696 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4697 if (Method->getObjCDeclQualifier())
4698 HasContextSensitiveKeywords = true;
4699 else {
4700 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4701 PEnd = Method->param_end();
4702 P != PEnd; ++P) {
4703 if ((*P)->getObjCDeclQualifier()) {
4704 HasContextSensitiveKeywords = true;
4705 break;
4706 }
4707 }
4708 }
4709 }
4710 }
4711 // C++ methods can have context-sensitive keywords.
4712 else if (cursor.kind == CXCursor_CXXMethod) {
4713 if (CXXMethodDecl *Method
4714 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4715 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4716 HasContextSensitiveKeywords = true;
4717 }
4718 }
4719 // C++ classes can have context-sensitive keywords.
4720 else if (cursor.kind == CXCursor_StructDecl ||
4721 cursor.kind == CXCursor_ClassDecl ||
4722 cursor.kind == CXCursor_ClassTemplate ||
4723 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4724 if (Decl *D = getCursorDecl(cursor))
4725 if (D->hasAttr<FinalAttr>())
4726 HasContextSensitiveKeywords = true;
4727 }
4728 }
4729
Douglas Gregor4419b672010-10-21 06:10:04 +00004730 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004731 // For macro expansions, just note where the beginning of the macro
4732 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004733 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004734 Annotated[Loc.int_data] = cursor;
4735 return CXChildVisit_Recurse;
4736 }
4737
Douglas Gregor4419b672010-10-21 06:10:04 +00004738 // Items in the preprocessing record are kept separate from items in
4739 // declarations, so we keep a separate token index.
4740 unsigned SavedTokIdx = TokIdx;
4741 TokIdx = PreprocessingTokIdx;
4742
4743 // Skip tokens up until we catch up to the beginning of the preprocessing
4744 // entry.
4745 while (MoreTokens()) {
4746 const unsigned I = NextToken();
4747 SourceLocation TokLoc = GetTokenLoc(I);
4748 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4749 case RangeBefore:
4750 AdvanceToken();
4751 continue;
4752 case RangeAfter:
4753 case RangeOverlap:
4754 break;
4755 }
4756 break;
4757 }
4758
4759 // Look at all of the tokens within this range.
4760 while (MoreTokens()) {
4761 const unsigned I = NextToken();
4762 SourceLocation TokLoc = GetTokenLoc(I);
4763 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4764 case RangeBefore:
4765 assert(0 && "Infeasible");
4766 case RangeAfter:
4767 break;
4768 case RangeOverlap:
4769 Cursors[I] = cursor;
4770 AdvanceToken();
4771 continue;
4772 }
4773 break;
4774 }
4775
4776 // Save the preprocessing token index; restore the non-preprocessing
4777 // token index.
4778 PreprocessingTokIdx = TokIdx;
4779 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004780 return CXChildVisit_Recurse;
4781 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004782
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004783 if (cursorRange.isInvalid())
4784 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004785
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004786 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4787
Ted Kremeneka333c662010-05-12 05:29:33 +00004788 // Adjust the annotated range based specific declarations.
4789 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4790 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004791 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004792
4793 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004794 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004795 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4796 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4797 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4798 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4799 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004800 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004801
4802 if (StartLoc.isValid() && L.isValid() &&
4803 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4804 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004805 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004806
Ted Kremenek3f404602010-08-14 01:14:06 +00004807 // If the location of the cursor occurs within a macro instantiation, record
4808 // the spelling location of the cursor in our annotation map. We can then
4809 // paper over the token labelings during a post-processing step to try and
4810 // get cursor mappings for tokens that are the *arguments* of a macro
4811 // instantiation.
4812 if (L.isMacroID()) {
4813 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4814 // Only invalidate the old annotation if it isn't part of a preprocessing
4815 // directive. Here we assume that the default construction of CXCursor
4816 // results in CXCursor.kind being an initialized value (i.e., 0). If
4817 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004818
Ted Kremenek3f404602010-08-14 01:14:06 +00004819 CXCursor &oldC = Annotated[rawEncoding];
4820 if (!clang_isPreprocessing(oldC.kind))
4821 oldC = cursor;
4822 }
4823
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004824 const enum CXCursorKind K = clang_getCursorKind(parent);
4825 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004826 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4827 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004828
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004829 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004830
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004831 // Avoid having the cursor of an expression "overwrite" the annotation of the
4832 // variable declaration that it belongs to.
4833 // This can happen for C++ constructor expressions whose range generally
4834 // include the variable declaration, e.g.:
4835 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4836 if (clang_isExpression(cursorK)) {
4837 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004838 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004839 const unsigned I = NextToken();
4840 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4841 E->getLocStart() == D->getLocation() &&
4842 E->getLocStart() == GetTokenLoc(I)) {
4843 Cursors[I] = updateC;
4844 AdvanceToken();
4845 }
4846 }
4847 }
4848
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004849 // Visit children to get their cursor information.
4850 const unsigned BeforeChildren = NextToken();
4851 VisitChildren(cursor);
4852 const unsigned AfterChildren = NextToken();
4853
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004854 // Scan the tokens that are at the end of the cursor, but are not captured
4855 // but the child cursors.
4856 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004857
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004858 // Scan the tokens that are at the beginning of the cursor, but are not
4859 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004860 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4861 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4862 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004863
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004864 Cursors[I] = cursor;
4865 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004866
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004867 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004868}
4869
Ted Kremenek6db61092010-05-05 00:55:15 +00004870static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4871 CXCursor parent,
4872 CXClientData client_data) {
4873 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4874}
4875
Ted Kremenek6628a612011-03-18 22:51:30 +00004876namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004877
4878/// \brief Uses the macro expansions in the preprocessing record to find
4879/// and mark tokens that are macro arguments. This info is used by the
4880/// AnnotateTokensWorker.
4881class MarkMacroArgTokensVisitor {
4882 SourceManager &SM;
4883 CXToken *Tokens;
4884 unsigned NumTokens;
4885 unsigned CurIdx;
4886
4887public:
4888 MarkMacroArgTokensVisitor(SourceManager &SM,
4889 CXToken *tokens, unsigned numTokens)
4890 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4891
4892 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4893 if (cursor.kind != CXCursor_MacroExpansion)
4894 return CXChildVisit_Continue;
4895
4896 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4897 if (macroRange.getBegin() == macroRange.getEnd())
4898 return CXChildVisit_Continue; // it's not a function macro.
4899
4900 for (; CurIdx < NumTokens; ++CurIdx) {
4901 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4902 macroRange.getBegin()))
4903 break;
4904 }
4905
4906 if (CurIdx == NumTokens)
4907 return CXChildVisit_Break;
4908
4909 for (; CurIdx < NumTokens; ++CurIdx) {
4910 SourceLocation tokLoc = getTokenLoc(CurIdx);
4911 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4912 break;
4913
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004914 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004915 }
4916
4917 if (CurIdx == NumTokens)
4918 return CXChildVisit_Break;
4919
4920 return CXChildVisit_Continue;
4921 }
4922
4923private:
4924 SourceLocation getTokenLoc(unsigned tokI) {
4925 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4926 }
4927
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004928 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004929 // The third field is reserved and currently not used. Use it here
4930 // to mark macro arg expanded tokens with their expanded locations.
4931 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4932 }
4933};
4934
4935} // end anonymous namespace
4936
4937static CXChildVisitResult
4938MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4939 CXClientData client_data) {
4940 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4941 parent);
4942}
4943
4944namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004945 struct clang_annotateTokens_Data {
4946 CXTranslationUnit TU;
4947 ASTUnit *CXXUnit;
4948 CXToken *Tokens;
4949 unsigned NumTokens;
4950 CXCursor *Cursors;
4951 };
4952}
4953
Ted Kremenekab979612010-11-11 08:05:23 +00004954// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004955static void clang_annotateTokensImpl(void *UserData) {
4956 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4957 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4958 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4959 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4960 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4961
4962 // Determine the region of interest, which contains all of the tokens.
4963 SourceRange RegionOfInterest;
4964 RegionOfInterest.setBegin(
4965 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4966 RegionOfInterest.setEnd(
4967 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4968 Tokens[NumTokens-1])));
4969
4970 // A mapping from the source locations found when re-lexing or traversing the
4971 // region of interest to the corresponding cursors.
4972 AnnotateTokensData Annotated;
4973
4974 // Relex the tokens within the source range to look for preprocessing
4975 // directives.
4976 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4977 std::pair<FileID, unsigned> BeginLocInfo
4978 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4979 std::pair<FileID, unsigned> EndLocInfo
4980 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4981
Chris Lattner5f9e2722011-07-23 10:55:15 +00004982 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00004983 bool Invalid = false;
4984 if (BeginLocInfo.first == EndLocInfo.first &&
4985 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4986 !Invalid) {
4987 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4988 CXXUnit->getASTContext().getLangOptions(),
4989 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4990 Buffer.end());
4991 Lex.SetCommentRetentionState(true);
4992
4993 // Lex tokens in raw mode until we hit the end of the range, to avoid
4994 // entering #includes or expanding macros.
4995 while (true) {
4996 Token Tok;
4997 Lex.LexFromRawLexer(Tok);
4998
4999 reprocess:
5000 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5001 // We have found a preprocessing directive. Gobble it up so that we
5002 // don't see it while preprocessing these tokens later, but keep track
5003 // of all of the token locations inside this preprocessing directive so
5004 // that we can annotate them appropriately.
5005 //
5006 // FIXME: Some simple tests here could identify macro definitions and
5007 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005008 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00005009 do {
5010 Locations.push_back(Tok.getLocation());
5011 Lex.LexFromRawLexer(Tok);
5012 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5013
5014 using namespace cxcursor;
5015 CXCursor Cursor
5016 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5017 Locations.back()),
5018 TU);
5019 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5020 Annotated[Locations[I].getRawEncoding()] = Cursor;
5021 }
5022
5023 if (Tok.isAtStartOfLine())
5024 goto reprocess;
5025
5026 continue;
5027 }
5028
5029 if (Tok.is(tok::eof))
5030 break;
5031 }
5032 }
5033
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005034 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5035 // Search and mark tokens that are macro argument expansions.
5036 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5037 Tokens, NumTokens);
5038 CursorVisitor MacroArgMarker(TU,
5039 MarkMacroArgTokensVisitorDelegate, &Visitor,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00005040 true, RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005041 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5042 }
5043
Ted Kremenek6628a612011-03-18 22:51:30 +00005044 // Annotate all of the source locations in the region of interest that map to
5045 // a specific cursor.
5046 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5047 TU, RegionOfInterest);
5048
5049 // FIXME: We use a ridiculous stack size here because the data-recursion
5050 // algorithm uses a large stack frame than the non-data recursive version,
5051 // and AnnotationTokensWorker currently transforms the data-recursion
5052 // algorithm back into a traditional recursion by explicitly calling
5053 // VisitChildren(). We will need to remove this explicit recursive call.
5054 W.AnnotateTokens();
5055
5056 // If we ran into any entities that involve context-sensitive keywords,
5057 // take another pass through the tokens to mark them as such.
5058 if (W.hasContextSensitiveKeywords()) {
5059 for (unsigned I = 0; I != NumTokens; ++I) {
5060 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5061 continue;
5062
5063 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5064 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5065 if (ObjCPropertyDecl *Property
5066 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5067 if (Property->getPropertyAttributesAsWritten() != 0 &&
5068 llvm::StringSwitch<bool>(II->getName())
5069 .Case("readonly", true)
5070 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005071 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005072 .Case("readwrite", true)
5073 .Case("retain", true)
5074 .Case("copy", true)
5075 .Case("nonatomic", true)
5076 .Case("atomic", true)
5077 .Case("getter", true)
5078 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005079 .Case("strong", true)
5080 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005081 .Default(false))
5082 Tokens[I].int_data[0] = CXToken_Keyword;
5083 }
5084 continue;
5085 }
5086
5087 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5088 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5089 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5090 if (llvm::StringSwitch<bool>(II->getName())
5091 .Case("in", true)
5092 .Case("out", true)
5093 .Case("inout", true)
5094 .Case("oneway", true)
5095 .Case("bycopy", true)
5096 .Case("byref", true)
5097 .Default(false))
5098 Tokens[I].int_data[0] = CXToken_Keyword;
5099 continue;
5100 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005101
5102 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5103 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5104 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005105 continue;
5106 }
5107 }
5108 }
Ted Kremenekab979612010-11-11 08:05:23 +00005109}
5110
Ted Kremenek6db61092010-05-05 00:55:15 +00005111extern "C" {
5112
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005113void clang_annotateTokens(CXTranslationUnit TU,
5114 CXToken *Tokens, unsigned NumTokens,
5115 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005116
5117 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005118 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005119
Douglas Gregor4419b672010-10-21 06:10:04 +00005120 // Any token we don't specifically annotate will have a NULL cursor.
5121 CXCursor C = clang_getNullCursor();
5122 for (unsigned I = 0; I != NumTokens; ++I)
5123 Cursors[I] = C;
5124
Ted Kremeneka60ed472010-11-16 08:15:36 +00005125 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005126 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005127 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005128
Douglas Gregorbdf60622010-03-05 21:16:25 +00005129 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005130
5131 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005132 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005133 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005134 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005135 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5136 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005137}
Ted Kremenek6628a612011-03-18 22:51:30 +00005138
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005139} // end: extern "C"
5140
5141//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005142// Operations for querying linkage of a cursor.
5143//===----------------------------------------------------------------------===//
5144
5145extern "C" {
5146CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005147 if (!clang_isDeclaration(cursor.kind))
5148 return CXLinkage_Invalid;
5149
Ted Kremenek16b42592010-03-03 06:36:57 +00005150 Decl *D = cxcursor::getCursorDecl(cursor);
5151 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5152 switch (ND->getLinkage()) {
5153 case NoLinkage: return CXLinkage_NoLinkage;
5154 case InternalLinkage: return CXLinkage_Internal;
5155 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5156 case ExternalLinkage: return CXLinkage_External;
5157 };
5158
5159 return CXLinkage_Invalid;
5160}
5161} // end: extern "C"
5162
5163//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005164// Operations for querying language of a cursor.
5165//===----------------------------------------------------------------------===//
5166
5167static CXLanguageKind getDeclLanguage(const Decl *D) {
5168 switch (D->getKind()) {
5169 default:
5170 break;
5171 case Decl::ImplicitParam:
5172 case Decl::ObjCAtDefsField:
5173 case Decl::ObjCCategory:
5174 case Decl::ObjCCategoryImpl:
5175 case Decl::ObjCClass:
5176 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005177 case Decl::ObjCForwardProtocol:
5178 case Decl::ObjCImplementation:
5179 case Decl::ObjCInterface:
5180 case Decl::ObjCIvar:
5181 case Decl::ObjCMethod:
5182 case Decl::ObjCProperty:
5183 case Decl::ObjCPropertyImpl:
5184 case Decl::ObjCProtocol:
5185 return CXLanguage_ObjC;
5186 case Decl::CXXConstructor:
5187 case Decl::CXXConversion:
5188 case Decl::CXXDestructor:
5189 case Decl::CXXMethod:
5190 case Decl::CXXRecord:
5191 case Decl::ClassTemplate:
5192 case Decl::ClassTemplatePartialSpecialization:
5193 case Decl::ClassTemplateSpecialization:
5194 case Decl::Friend:
5195 case Decl::FriendTemplate:
5196 case Decl::FunctionTemplate:
5197 case Decl::LinkageSpec:
5198 case Decl::Namespace:
5199 case Decl::NamespaceAlias:
5200 case Decl::NonTypeTemplateParm:
5201 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005202 case Decl::TemplateTemplateParm:
5203 case Decl::TemplateTypeParm:
5204 case Decl::UnresolvedUsingTypename:
5205 case Decl::UnresolvedUsingValue:
5206 case Decl::Using:
5207 case Decl::UsingDirective:
5208 case Decl::UsingShadow:
5209 return CXLanguage_CPlusPlus;
5210 }
5211
5212 return CXLanguage_C;
5213}
5214
5215extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005216
5217enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5218 if (clang_isDeclaration(cursor.kind))
5219 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005220 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005221 return CXAvailability_Available;
5222
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005223 switch (D->getAvailability()) {
5224 case AR_Available:
5225 case AR_NotYetIntroduced:
5226 return CXAvailability_Available;
5227
5228 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005229 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005230
5231 case AR_Unavailable:
5232 return CXAvailability_NotAvailable;
5233 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005234 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005235
Douglas Gregor58ddb602010-08-23 23:00:57 +00005236 return CXAvailability_Available;
5237}
5238
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005239CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5240 if (clang_isDeclaration(cursor.kind))
5241 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5242
5243 return CXLanguage_Invalid;
5244}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005245
5246 /// \brief If the given cursor is the "templated" declaration
5247 /// descibing a class or function template, return the class or
5248 /// function template.
5249static Decl *maybeGetTemplateCursor(Decl *D) {
5250 if (!D)
5251 return 0;
5252
5253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5254 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5255 return FunTmpl;
5256
5257 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5258 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5259 return ClassTmpl;
5260
5261 return D;
5262}
5263
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005264CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5265 if (clang_isDeclaration(cursor.kind)) {
5266 if (Decl *D = getCursorDecl(cursor)) {
5267 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005268 if (!DC)
5269 return clang_getNullCursor();
5270
5271 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5272 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005273 }
5274 }
5275
5276 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5277 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005278 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005279 }
5280
5281 return clang_getNullCursor();
5282}
5283
5284CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5285 if (clang_isDeclaration(cursor.kind)) {
5286 if (Decl *D = getCursorDecl(cursor)) {
5287 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005288 if (!DC)
5289 return clang_getNullCursor();
5290
5291 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5292 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005293 }
5294 }
5295
5296 // FIXME: Note that we can't easily compute the lexical context of a
5297 // statement or expression, so we return nothing.
5298 return clang_getNullCursor();
5299}
5300
Douglas Gregor9f592342010-10-01 20:25:15 +00005301static void CollectOverriddenMethods(DeclContext *Ctx,
5302 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005303 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005304 if (!Ctx)
5305 return;
5306
5307 // If we have a class or category implementation, jump straight to the
5308 // interface.
5309 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5310 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5311
5312 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5313 if (!Container)
5314 return;
5315
5316 // Check whether we have a matching method at this level.
5317 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5318 Method->isInstanceMethod()))
5319 if (Method != Overridden) {
5320 // We found an override at this level; there is no need to look
5321 // into other protocols or categories.
5322 Methods.push_back(Overridden);
5323 return;
5324 }
5325
5326 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5327 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5328 PEnd = Protocol->protocol_end();
5329 P != PEnd; ++P)
5330 CollectOverriddenMethods(*P, Method, Methods);
5331 }
5332
5333 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5334 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5335 PEnd = Category->protocol_end();
5336 P != PEnd; ++P)
5337 CollectOverriddenMethods(*P, Method, Methods);
5338 }
5339
5340 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5341 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5342 PEnd = Interface->protocol_end();
5343 P != PEnd; ++P)
5344 CollectOverriddenMethods(*P, Method, Methods);
5345
5346 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5347 Category; Category = Category->getNextClassCategory())
5348 CollectOverriddenMethods(Category, Method, Methods);
5349
5350 // We only look into the superclass if we haven't found anything yet.
5351 if (Methods.empty())
5352 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5353 return CollectOverriddenMethods(Super, Method, Methods);
5354 }
5355}
5356
5357void clang_getOverriddenCursors(CXCursor cursor,
5358 CXCursor **overridden,
5359 unsigned *num_overridden) {
5360 if (overridden)
5361 *overridden = 0;
5362 if (num_overridden)
5363 *num_overridden = 0;
5364 if (!overridden || !num_overridden)
5365 return;
5366
5367 if (!clang_isDeclaration(cursor.kind))
5368 return;
5369
5370 Decl *D = getCursorDecl(cursor);
5371 if (!D)
5372 return;
5373
5374 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005375 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005376 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5377 *num_overridden = CXXMethod->size_overridden_methods();
5378 if (!*num_overridden)
5379 return;
5380
5381 *overridden = new CXCursor [*num_overridden];
5382 unsigned I = 0;
5383 for (CXXMethodDecl::method_iterator
5384 M = CXXMethod->begin_overridden_methods(),
5385 MEnd = CXXMethod->end_overridden_methods();
5386 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005387 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005388 return;
5389 }
5390
5391 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5392 if (!Method)
5393 return;
5394
5395 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005396 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005397 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5398
5399 if (Methods.empty())
5400 return;
5401
5402 *num_overridden = Methods.size();
5403 *overridden = new CXCursor [Methods.size()];
5404 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005405 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005406}
5407
5408void clang_disposeOverriddenCursors(CXCursor *overridden) {
5409 delete [] overridden;
5410}
5411
Douglas Gregorecdcb882010-10-20 22:00:55 +00005412CXFile clang_getIncludedFile(CXCursor cursor) {
5413 if (cursor.kind != CXCursor_InclusionDirective)
5414 return 0;
5415
5416 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5417 return (void *)ID->getFile();
5418}
5419
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005420} // end: extern "C"
5421
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005422
5423//===----------------------------------------------------------------------===//
5424// C++ AST instrospection.
5425//===----------------------------------------------------------------------===//
5426
5427extern "C" {
5428unsigned clang_CXXMethod_isStatic(CXCursor C) {
5429 if (!clang_isDeclaration(C.kind))
5430 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005431
5432 CXXMethodDecl *Method = 0;
5433 Decl *D = cxcursor::getCursorDecl(C);
5434 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5435 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5436 else
5437 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5438 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005439}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005440
Douglas Gregor211924b2011-05-12 15:17:24 +00005441unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5442 if (!clang_isDeclaration(C.kind))
5443 return 0;
5444
5445 CXXMethodDecl *Method = 0;
5446 Decl *D = cxcursor::getCursorDecl(C);
5447 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5448 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5449 else
5450 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5451 return (Method && Method->isVirtual()) ? 1 : 0;
5452}
5453
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005454} // end: extern "C"
5455
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005456//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005457// Attribute introspection.
5458//===----------------------------------------------------------------------===//
5459
5460extern "C" {
5461CXType clang_getIBOutletCollectionType(CXCursor C) {
5462 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005463 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005464
5465 IBOutletCollectionAttr *A =
5466 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5467
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005468 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005469}
5470} // end: extern "C"
5471
5472//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005473// Inspecting memory usage.
5474//===----------------------------------------------------------------------===//
5475
Ted Kremenekf7870022011-04-20 16:41:07 +00005476typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005477
Ted Kremenekf7870022011-04-20 16:41:07 +00005478static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5479 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005480 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005481 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005482 entries.push_back(entry);
5483}
5484
5485extern "C" {
5486
Ted Kremenekf7870022011-04-20 16:41:07 +00005487const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005488 const char *str = "";
5489 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005490 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005491 str = "ASTContext: expressions, declarations, and types";
5492 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005493 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005494 str = "ASTContext: identifiers";
5495 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005496 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005497 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005498 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005499 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005500 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005501 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005502 case CXTUResourceUsage_SourceManagerContentCache:
5503 str = "SourceManager: content cache allocator";
5504 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005505 case CXTUResourceUsage_AST_SideTables:
5506 str = "ASTContext: side tables";
5507 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005508 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5509 str = "SourceManager: malloc'ed memory buffers";
5510 break;
5511 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5512 str = "SourceManager: mmap'ed memory buffers";
5513 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005514 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5515 str = "ExternalASTSource: malloc'ed memory buffers";
5516 break;
5517 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5518 str = "ExternalASTSource: mmap'ed memory buffers";
5519 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005520 case CXTUResourceUsage_Preprocessor:
5521 str = "Preprocessor: malloc'ed memory";
5522 break;
5523 case CXTUResourceUsage_PreprocessingRecord:
5524 str = "Preprocessor: PreprocessingRecord";
5525 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005526 case CXTUResourceUsage_SourceManager_DataStructures:
5527 str = "SourceManager: data structures and tables";
5528 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005529 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5530 str = "Preprocessor: header search tables";
5531 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005532 }
5533 return str;
5534}
5535
Ted Kremenekf7870022011-04-20 16:41:07 +00005536CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005537 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005538 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005539 return usage;
5540 }
5541
5542 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5543 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5544 ASTContext &astContext = astUnit->getASTContext();
5545
5546 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005547 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005548 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005549
5550 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005551 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005552 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5553
5554 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005555 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005556 (unsigned long) astContext.Selectors.getTotalMemory());
5557
Ted Kremenekba29bd22011-04-28 04:53:38 +00005558 // How much memory is used by ASTContext's side tables?
5559 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5560 (unsigned long) astContext.getSideTableAllocatedMemory());
5561
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005562 // How much memory is used for caching global code completion results?
5563 unsigned long completionBytes = 0;
5564 if (GlobalCodeCompletionAllocator *completionAllocator =
5565 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005566 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005567 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005568 createCXTUResourceUsageEntry(*entries,
5569 CXTUResourceUsage_GlobalCompletionResults,
5570 completionBytes);
5571
5572 // How much memory is being used by SourceManager's content cache?
5573 createCXTUResourceUsageEntry(*entries,
5574 CXTUResourceUsage_SourceManagerContentCache,
5575 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005576
5577 // How much memory is being used by the MemoryBuffer's in SourceManager?
5578 const SourceManager::MemoryBufferSizes &srcBufs =
5579 astUnit->getSourceManager().getMemoryBufferSizes();
5580
5581 createCXTUResourceUsageEntry(*entries,
5582 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5583 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005584 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005585 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5586 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005587 createCXTUResourceUsageEntry(*entries,
5588 CXTUResourceUsage_SourceManager_DataStructures,
5589 (unsigned long) astContext.getSourceManager()
5590 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005591
5592 // How much memory is being used by the ExternalASTSource?
5593 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5594 const ExternalASTSource::MemoryBufferSizes &sizes =
5595 esrc->getMemoryBufferSizes();
5596
5597 createCXTUResourceUsageEntry(*entries,
5598 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5599 (unsigned long) sizes.malloc_bytes);
5600 createCXTUResourceUsageEntry(*entries,
5601 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5602 (unsigned long) sizes.mmap_bytes);
5603 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005604
5605 // How much memory is being used by the Preprocessor?
5606 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005607 createCXTUResourceUsageEntry(*entries,
5608 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005609 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005610
5611 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5612 createCXTUResourceUsageEntry(*entries,
5613 CXTUResourceUsage_PreprocessingRecord,
5614 pRec->getTotalMemory());
5615 }
5616
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005617 createCXTUResourceUsageEntry(*entries,
5618 CXTUResourceUsage_Preprocessor_HeaderSearch,
5619 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005620
Ted Kremenekf7870022011-04-20 16:41:07 +00005621 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005622 (unsigned) entries->size(),
5623 entries->size() ? &(*entries)[0] : 0 };
5624 entries.take();
5625 return usage;
5626}
5627
Ted Kremenekf7870022011-04-20 16:41:07 +00005628void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005629 if (usage.data)
5630 delete (MemUsageEntries*) usage.data;
5631}
5632
5633} // end extern "C"
5634
Douglas Gregor6df78732011-05-05 20:27:22 +00005635void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5636 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5637 for (unsigned I = 0; I != Usage.numEntries; ++I)
5638 fprintf(stderr, " %s: %lu\n",
5639 clang_getTUResourceUsageName(Usage.entries[I].kind),
5640 Usage.entries[I].amount);
5641
5642 clang_disposeCXTUResourceUsage(Usage);
5643}
5644
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005645//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005646// Misc. utility functions.
5647//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005648
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005649/// Default to using an 8 MB stack size on "safety" threads.
5650static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005651
5652namespace clang {
5653
5654bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005655 void (*Fn)(void*), void *UserData,
5656 unsigned Size) {
5657 if (!Size)
5658 Size = GetSafetyThreadStackSize();
5659 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005660 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5661 return CRC.RunSafely(Fn, UserData);
5662}
5663
5664unsigned GetSafetyThreadStackSize() {
5665 return SafetyStackThreadSize;
5666}
5667
5668void SetSafetyThreadStackSize(unsigned Value) {
5669 SafetyStackThreadSize = Value;
5670}
5671
5672}
5673
Ted Kremenek04bb7162010-01-22 22:44:15 +00005674extern "C" {
5675
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005676CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005677 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005678}
5679
5680} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005681