blob: e6e1b90534d01d1eb346cedc82f389c6d17a0864 [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 }
562
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000564 return false;
565}
566
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000567bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000568 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
569 if (Visit(TSInfo->getTypeLoc()))
570 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000571
Ted Kremenek664cffd2010-07-22 11:30:19 +0000572 if (Stmt *Body = B->getBody())
573 return Visit(MakeCXCursor(Body, StmtParent, TU));
574
575 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000576}
577
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000578llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
579 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000580 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000581 if (Range.isInvalid())
582 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000583
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000584 switch (CompareRegionOfInterest(Range)) {
585 case RangeBefore:
586 // This declaration comes before the region of interest; skip it.
587 return llvm::Optional<bool>();
588
589 case RangeAfter:
590 // This declaration comes after the region of interest; we're done.
591 return false;
592
593 case RangeOverlap:
594 // This declaration overlaps the region of interest; visit it.
595 break;
596 }
597 }
598 return true;
599}
600
601bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
602 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
603
604 // FIXME: Eventually remove. This part of a hack to support proper
605 // iteration over all Decls contained lexically within an ObjC container.
606 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
607 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
608
609 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000610 Decl *D = *I;
611 if (D->getLexicalDeclContext() != DC)
612 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000613 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000614 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
615 if (!V.hasValue())
616 continue;
617 if (!V.getValue())
618 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000619 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000620 return true;
621 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000622 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000623}
624
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000625bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
626 llvm_unreachable("Translation units are visited directly by Visit()");
627 return false;
628}
629
Richard Smith162e1c12011-04-15 14:24:37 +0000630bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
631 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
632 return Visit(TSInfo->getTypeLoc());
633
634 return false;
635}
636
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000637bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
638 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
639 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000640
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000641 return false;
642}
643
644bool CursorVisitor::VisitTagDecl(TagDecl *D) {
645 return VisitDeclContext(D);
646}
647
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000648bool CursorVisitor::VisitClassTemplateSpecializationDecl(
649 ClassTemplateSpecializationDecl *D) {
650 bool ShouldVisitBody = false;
651 switch (D->getSpecializationKind()) {
652 case TSK_Undeclared:
653 case TSK_ImplicitInstantiation:
654 // Nothing to visit
655 return false;
656
657 case TSK_ExplicitInstantiationDeclaration:
658 case TSK_ExplicitInstantiationDefinition:
659 break;
660
661 case TSK_ExplicitSpecialization:
662 ShouldVisitBody = true;
663 break;
664 }
665
666 // Visit the template arguments used in the specialization.
667 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
668 TypeLoc TL = SpecType->getTypeLoc();
669 if (TemplateSpecializationTypeLoc *TSTLoc
670 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
671 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
672 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
673 return true;
674 }
675 }
676
677 if (ShouldVisitBody && VisitCXXRecordDecl(D))
678 return true;
679
680 return false;
681}
682
Douglas Gregor74dbe642010-08-31 19:31:58 +0000683bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
684 ClassTemplatePartialSpecializationDecl *D) {
685 // FIXME: Visit the "outer" template parameter lists on the TagDecl
686 // before visiting these template parameters.
687 if (VisitTemplateParameters(D->getTemplateParameters()))
688 return true;
689
690 // Visit the partial specialization arguments.
691 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
692 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
693 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
694 return true;
695
696 return VisitCXXRecordDecl(D);
697}
698
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000699bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000700 // Visit the default argument.
701 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
702 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
703 if (Visit(DefArg->getTypeLoc()))
704 return true;
705
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000706 return false;
707}
708
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000709bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
710 if (Expr *Init = D->getInitExpr())
711 return Visit(MakeCXCursor(Init, StmtParent, TU));
712 return false;
713}
714
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000715bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
716 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
717 if (Visit(TSInfo->getTypeLoc()))
718 return true;
719
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000720 // Visit the nested-name-specifier, if present.
721 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
722 if (VisitNestedNameSpecifierLoc(QualifierLoc))
723 return true;
724
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000725 return false;
726}
727
Douglas Gregora67e03f2010-09-09 21:42:20 +0000728/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000729static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
730 CXXCtorInitializer const * const *X
731 = static_cast<CXXCtorInitializer const * const *>(Xp);
732 CXXCtorInitializer const * const *Y
733 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000734
735 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
736 return -1;
737 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
738 return 1;
739 else
740 return 0;
741}
742
Douglas Gregorb1373d02010-01-20 20:59:29 +0000743bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000744 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
745 // Visit the function declaration's syntactic components in the order
746 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000747 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000748 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
749
750 // If we have a function declared directly (without the use of a typedef),
751 // visit just the return type. Otherwise, just visit the function's type
752 // now.
753 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
754 (!FTL && Visit(TL)))
755 return true;
756
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000757 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000758 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
759 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000760 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000761
762 // Visit the declaration name.
763 if (VisitDeclarationNameInfo(ND->getNameInfo()))
764 return true;
765
766 // FIXME: Visit explicitly-specified template arguments!
767
768 // Visit the function parameters, if we have a function type.
769 if (FTL && VisitFunctionTypeLoc(*FTL, true))
770 return true;
771
772 // FIXME: Attributes?
773 }
774
Sean Hunt10620eb2011-05-06 20:44:56 +0000775 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000776 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
777 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000778 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000779 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
780 IEnd = Constructor->init_end();
781 I != IEnd; ++I) {
782 if (!(*I)->isWritten())
783 continue;
784
785 WrittenInits.push_back(*I);
786 }
787
788 // Sort the initializers in source order
789 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000790 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000791
792 // Visit the initializers in source order
793 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000794 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000795 if (Init->isAnyMemberInitializer()) {
796 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000797 Init->getMemberLocation(), TU)))
798 return true;
799 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
800 if (Visit(BaseInfo->getTypeLoc()))
801 return true;
802 }
803
804 // Visit the initializer value.
805 if (Expr *Initializer = Init->getInit())
806 if (Visit(MakeCXCursor(Initializer, ND, TU)))
807 return true;
808 }
809 }
810
811 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
812 return true;
813 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregorb1373d02010-01-20 20:59:29 +0000815 return false;
816}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000817
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000818bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
819 if (VisitDeclaratorDecl(D))
820 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000821
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000822 if (Expr *BitWidth = D->getBitWidth())
823 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000824
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000825 return false;
826}
827
828bool CursorVisitor::VisitVarDecl(VarDecl *D) {
829 if (VisitDeclaratorDecl(D))
830 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832 if (Expr *Init = D->getInit())
833 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000834
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000835 return false;
836}
837
Douglas Gregor84b51d72010-09-01 20:16:53 +0000838bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
839 if (VisitDeclaratorDecl(D))
840 return true;
841
842 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
843 if (Expr *DefArg = D->getDefaultArgument())
844 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
845
846 return false;
847}
848
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000849bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
850 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
851 // before visiting these template parameters.
852 if (VisitTemplateParameters(D->getTemplateParameters()))
853 return true;
854
855 return VisitFunctionDecl(D->getTemplatedDecl());
856}
857
Douglas Gregor39d6f072010-08-31 19:02:00 +0000858bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
859 // FIXME: Visit the "outer" template parameter lists on the TagDecl
860 // before visiting these template parameters.
861 if (VisitTemplateParameters(D->getTemplateParameters()))
862 return true;
863
864 return VisitCXXRecordDecl(D->getTemplatedDecl());
865}
866
Douglas Gregor84b51d72010-09-01 20:16:53 +0000867bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
868 if (VisitTemplateParameters(D->getTemplateParameters()))
869 return true;
870
871 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
872 VisitTemplateArgumentLoc(D->getDefaultArgument()))
873 return true;
874
875 return false;
876}
877
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000878bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000879 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
880 if (Visit(TSInfo->getTypeLoc()))
881 return true;
882
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000883 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000884 PEnd = ND->param_end();
885 P != PEnd; ++P) {
886 if (Visit(MakeCXCursor(*P, TU)))
887 return true;
888 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000889
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000890 if (ND->isThisDeclarationADefinition() &&
891 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
892 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000893
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000894 return false;
895}
896
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000897namespace {
898 struct ContainerDeclsSort {
899 SourceManager &SM;
900 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
901 bool operator()(Decl *A, Decl *B) {
902 SourceLocation L_A = A->getLocStart();
903 SourceLocation L_B = B->getLocStart();
904 assert(L_A.isValid() && L_B.isValid());
905 return SM.isBeforeInTranslationUnit(L_A, L_B);
906 }
907 };
908}
909
Douglas Gregora59e3902010-01-21 23:27:09 +0000910bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000911 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
912 // an @implementation can lexically contain Decls that are not properly
913 // nested in the AST. When we identify such cases, we need to retrofit
914 // this nesting here.
915 if (!DI_current)
916 return VisitDeclContext(D);
917
918 // Scan the Decls that immediately come after the container
919 // in the current DeclContext. If any fall within the
920 // container's lexical region, stash them into a vector
921 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000922 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000923 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000924 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000925 if (EndLoc.isValid()) {
926 DeclContext::decl_iterator next = *DI_current;
927 while (++next != DE_current) {
928 Decl *D_next = *next;
929 if (!D_next)
930 break;
931 SourceLocation L = D_next->getLocStart();
932 if (!L.isValid())
933 break;
934 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
935 *DI_current = next;
936 DeclsInContainer.push_back(D_next);
937 continue;
938 }
939 break;
940 }
941 }
942
943 // The common case.
944 if (DeclsInContainer.empty())
945 return VisitDeclContext(D);
946
947 // Get all the Decls in the DeclContext, and sort them with the
948 // additional ones we've collected. Then visit them.
949 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
950 I!=E; ++I) {
951 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000952 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
953 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000954 continue;
955 DeclsInContainer.push_back(subDecl);
956 }
957
958 // Now sort the Decls so that they appear in lexical order.
959 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
960 ContainerDeclsSort(SM));
961
962 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000963 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000964 E = DeclsInContainer.end(); I != E; ++I) {
965 CXCursor Cursor = MakeCXCursor(*I, TU);
966 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
967 if (!V.hasValue())
968 continue;
969 if (!V.getValue())
970 return false;
971 if (Visit(Cursor, true))
972 return true;
973 }
974 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000975}
976
Douglas Gregorb1373d02010-01-20 20:59:29 +0000977bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000978 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
979 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000980 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000981
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000982 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
983 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
984 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000985 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000986 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000987
Douglas Gregora59e3902010-01-21 23:27:09 +0000988 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000989}
990
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000991bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
992 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
993 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
994 E = PID->protocol_end(); I != E; ++I, ++PL)
995 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
996 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000997
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000998 return VisitObjCContainerDecl(PID);
999}
1000
Ted Kremenek23173d72010-05-18 21:09:07 +00001001bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001002 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001003 return true;
1004
Ted Kremenek23173d72010-05-18 21:09:07 +00001005 // FIXME: This implements a workaround with @property declarations also being
1006 // installed in the DeclContext for the @interface. Eventually this code
1007 // should be removed.
1008 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1009 if (!CDecl || !CDecl->IsClassExtension())
1010 return false;
1011
1012 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1013 if (!ID)
1014 return false;
1015
1016 IdentifierInfo *PropertyId = PD->getIdentifier();
1017 ObjCPropertyDecl *prevDecl =
1018 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1019
1020 if (!prevDecl)
1021 return false;
1022
1023 // Visit synthesized methods since they will be skipped when visiting
1024 // the @interface.
1025 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001026 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001027 if (Visit(MakeCXCursor(MD, TU)))
1028 return true;
1029
1030 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001031 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001032 if (Visit(MakeCXCursor(MD, TU)))
1033 return true;
1034
1035 return false;
1036}
1037
Douglas Gregorb1373d02010-01-20 20:59:29 +00001038bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001039 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001040 if (D->getSuperClass() &&
1041 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001043 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001044 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001046 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1047 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1048 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001049 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001050 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001051
Douglas Gregora59e3902010-01-21 23:27:09 +00001052 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001053}
1054
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001055bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1056 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001057}
1058
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001059bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001060 // 'ID' could be null when dealing with invalid code.
1061 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1062 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1063 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001064
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001065 return VisitObjCImplDecl(D);
1066}
1067
1068bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1069#if 0
1070 // Issue callbacks for super class.
1071 // FIXME: No source location information!
1072 if (D->getSuperClass() &&
1073 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001074 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001075 TU)))
1076 return true;
1077#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001078
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001079 return VisitObjCImplDecl(D);
1080}
1081
1082bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1083 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1084 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1085 E = D->protocol_end();
1086 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001087 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001088 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001089
1090 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001091}
1092
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001093bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001094 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1095 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001096 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001097 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001098}
1099
Douglas Gregora4ffd852010-11-17 01:03:52 +00001100bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1101 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1102 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1103
1104 return false;
1105}
1106
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001107bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1108 return VisitDeclContext(D);
1109}
1110
Douglas Gregor69319002010-08-31 23:48:11 +00001111bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001112 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001113 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1114 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001116
1117 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1118 D->getTargetNameLoc(), TU));
1119}
1120
Douglas Gregor7e242562010-09-01 19:52:22 +00001121bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001122 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001123 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1124 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001125 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001126 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001127
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001128 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1129 return true;
1130
Douglas Gregor7e242562010-09-01 19:52:22 +00001131 return VisitDeclarationNameInfo(D->getNameInfo());
1132}
1133
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001134bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001135 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001136 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1137 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001138 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001139
1140 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1141 D->getIdentLocation(), TU));
1142}
1143
Douglas Gregor7e242562010-09-01 19:52:22 +00001144bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001145 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001146 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1147 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001148 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001149 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001150
Douglas Gregor7e242562010-09-01 19:52:22 +00001151 return VisitDeclarationNameInfo(D->getNameInfo());
1152}
1153
1154bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1155 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001156 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001157 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1158 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001159 return true;
1160
Douglas Gregor7e242562010-09-01 19:52:22 +00001161 return false;
1162}
1163
Douglas Gregor01829d32010-08-31 14:41:23 +00001164bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1165 switch (Name.getName().getNameKind()) {
1166 case clang::DeclarationName::Identifier:
1167 case clang::DeclarationName::CXXLiteralOperatorName:
1168 case clang::DeclarationName::CXXOperatorName:
1169 case clang::DeclarationName::CXXUsingDirective:
1170 return false;
1171
1172 case clang::DeclarationName::CXXConstructorName:
1173 case clang::DeclarationName::CXXDestructorName:
1174 case clang::DeclarationName::CXXConversionFunctionName:
1175 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1176 return Visit(TSInfo->getTypeLoc());
1177 return false;
1178
1179 case clang::DeclarationName::ObjCZeroArgSelector:
1180 case clang::DeclarationName::ObjCOneArgSelector:
1181 case clang::DeclarationName::ObjCMultiArgSelector:
1182 // FIXME: Per-identifier location info?
1183 return false;
1184 }
1185
1186 return false;
1187}
1188
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001189bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1190 SourceRange Range) {
1191 // FIXME: This whole routine is a hack to work around the lack of proper
1192 // source information in nested-name-specifiers (PR5791). Since we do have
1193 // a beginning source location, we can visit the first component of the
1194 // nested-name-specifier, if it's a single-token component.
1195 if (!NNS)
1196 return false;
1197
1198 // Get the first component in the nested-name-specifier.
1199 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1200 NNS = Prefix;
1201
1202 switch (NNS->getKind()) {
1203 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001204 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1205 TU));
1206
Douglas Gregor14aba762011-02-24 02:36:08 +00001207 case NestedNameSpecifier::NamespaceAlias:
1208 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1209 Range.getBegin(), TU));
1210
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001211 case NestedNameSpecifier::TypeSpec: {
1212 // If the type has a form where we know that the beginning of the source
1213 // range matches up with a reference cursor. Visit the appropriate reference
1214 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001215 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001216 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1217 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1218 if (const TagType *Tag = dyn_cast<TagType>(T))
1219 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1220 if (const TemplateSpecializationType *TST
1221 = dyn_cast<TemplateSpecializationType>(T))
1222 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1223 break;
1224 }
1225
1226 case NestedNameSpecifier::TypeSpecWithTemplate:
1227 case NestedNameSpecifier::Global:
1228 case NestedNameSpecifier::Identifier:
1229 break;
1230 }
1231
1232 return false;
1233}
1234
Douglas Gregordc355712011-02-25 00:36:19 +00001235bool
1236CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001237 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001238 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1239 Qualifiers.push_back(Qualifier);
1240
1241 while (!Qualifiers.empty()) {
1242 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1243 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1244 switch (NNS->getKind()) {
1245 case NestedNameSpecifier::Namespace:
1246 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001247 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001248 TU)))
1249 return true;
1250
1251 break;
1252
1253 case NestedNameSpecifier::NamespaceAlias:
1254 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
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::TypeSpec:
1262 case NestedNameSpecifier::TypeSpecWithTemplate:
1263 if (Visit(Q.getTypeLoc()))
1264 return true;
1265
1266 break;
1267
1268 case NestedNameSpecifier::Global:
1269 case NestedNameSpecifier::Identifier:
1270 break;
1271 }
1272 }
1273
1274 return false;
1275}
1276
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001277bool CursorVisitor::VisitTemplateParameters(
1278 const TemplateParameterList *Params) {
1279 if (!Params)
1280 return false;
1281
1282 for (TemplateParameterList::const_iterator P = Params->begin(),
1283 PEnd = Params->end();
1284 P != PEnd; ++P) {
1285 if (Visit(MakeCXCursor(*P, TU)))
1286 return true;
1287 }
1288
1289 return false;
1290}
1291
Douglas Gregor0b36e612010-08-31 20:37:03 +00001292bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1293 switch (Name.getKind()) {
1294 case TemplateName::Template:
1295 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1296
1297 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001298 // Visit the overloaded template set.
1299 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1300 return true;
1301
Douglas Gregor0b36e612010-08-31 20:37:03 +00001302 return false;
1303
1304 case TemplateName::DependentTemplate:
1305 // FIXME: Visit nested-name-specifier.
1306 return false;
1307
1308 case TemplateName::QualifiedTemplate:
1309 // FIXME: Visit nested-name-specifier.
1310 return Visit(MakeCursorTemplateRef(
1311 Name.getAsQualifiedTemplateName()->getDecl(),
1312 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001313
1314 case TemplateName::SubstTemplateTemplateParm:
1315 return Visit(MakeCursorTemplateRef(
1316 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1317 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001318
1319 case TemplateName::SubstTemplateTemplateParmPack:
1320 return Visit(MakeCursorTemplateRef(
1321 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1322 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001323 }
1324
1325 return false;
1326}
1327
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001328bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1329 switch (TAL.getArgument().getKind()) {
1330 case TemplateArgument::Null:
1331 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001332 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001333 return false;
1334
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001335 case TemplateArgument::Type:
1336 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1337 return Visit(TSInfo->getTypeLoc());
1338 return false;
1339
1340 case TemplateArgument::Declaration:
1341 if (Expr *E = TAL.getSourceDeclExpression())
1342 return Visit(MakeCXCursor(E, StmtParent, TU));
1343 return false;
1344
1345 case TemplateArgument::Expression:
1346 if (Expr *E = TAL.getSourceExpression())
1347 return Visit(MakeCXCursor(E, StmtParent, TU));
1348 return false;
1349
1350 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001351 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001352 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1353 return true;
1354
Douglas Gregora7fc9012011-01-05 18:58:31 +00001355 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001356 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001357 }
1358
1359 return false;
1360}
1361
Ted Kremeneka0536d82010-05-07 01:04:29 +00001362bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1363 return VisitDeclContext(D);
1364}
1365
Douglas Gregor01829d32010-08-31 14:41:23 +00001366bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1367 return Visit(TL.getUnqualifiedLoc());
1368}
1369
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001371 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001372
1373 // Some builtin types (such as Objective-C's "id", "sel", and
1374 // "Class") have associated declarations. Create cursors for those.
1375 QualType VisitType;
1376 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001377 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001379 case BuiltinType::Char_U:
1380 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381 case BuiltinType::Char16:
1382 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001383 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384 case BuiltinType::UInt:
1385 case BuiltinType::ULong:
1386 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001387 case BuiltinType::UInt128:
1388 case BuiltinType::Char_S:
1389 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001390 case BuiltinType::WChar_U:
1391 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001392 case BuiltinType::Short:
1393 case BuiltinType::Int:
1394 case BuiltinType::Long:
1395 case BuiltinType::LongLong:
1396 case BuiltinType::Int128:
1397 case BuiltinType::Float:
1398 case BuiltinType::Double:
1399 case BuiltinType::LongDouble:
1400 case BuiltinType::NullPtr:
1401 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001402 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001403 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001404 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001405 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001406
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001407 case BuiltinType::ObjCId:
1408 VisitType = Context.getObjCIdType();
1409 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001410
1411 case BuiltinType::ObjCClass:
1412 VisitType = Context.getObjCClassType();
1413 break;
1414
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001415 case BuiltinType::ObjCSel:
1416 VisitType = Context.getObjCSelType();
1417 break;
1418 }
1419
1420 if (!VisitType.isNull()) {
1421 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001422 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423 TU));
1424 }
1425
1426 return false;
1427}
1428
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001429bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001430 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001431}
1432
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001433bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1434 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1435}
1436
1437bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001438 if (TL.isDefinition())
1439 return Visit(MakeCXCursor(TL.getDecl(), TU));
1440
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001441 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1442}
1443
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001444bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001445 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001446}
1447
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001448bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1449 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1450 return true;
1451
John McCallc12c5bb2010-05-15 11:32:37 +00001452 return false;
1453}
1454
1455bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1456 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1457 return true;
1458
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001459 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1460 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1461 TU)))
1462 return true;
1463 }
1464
1465 return false;
1466}
1467
1468bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001469 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001470}
1471
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001472bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1473 return Visit(TL.getInnerLoc());
1474}
1475
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001476bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1477 return Visit(TL.getPointeeLoc());
1478}
1479
1480bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1481 return Visit(TL.getPointeeLoc());
1482}
1483
1484bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1485 return Visit(TL.getPointeeLoc());
1486}
1487
1488bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001489 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001490}
1491
1492bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001493 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001494}
1495
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001496bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1497 return Visit(TL.getModifiedLoc());
1498}
1499
Douglas Gregor01829d32010-08-31 14:41:23 +00001500bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1501 bool SkipResultType) {
1502 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001503 return true;
1504
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001505 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001506 if (Decl *D = TL.getArg(I))
1507 if (Visit(MakeCXCursor(D, TU)))
1508 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001509
1510 return false;
1511}
1512
1513bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1514 if (Visit(TL.getElementLoc()))
1515 return true;
1516
1517 if (Expr *Size = TL.getSizeExpr())
1518 return Visit(MakeCXCursor(Size, StmtParent, TU));
1519
1520 return false;
1521}
1522
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001523bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1524 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001525 // Visit the template name.
1526 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1527 TL.getTemplateNameLoc()))
1528 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001529
1530 // Visit the template arguments.
1531 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1532 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1533 return true;
1534
1535 return false;
1536}
1537
Douglas Gregor2332c112010-01-21 20:48:56 +00001538bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1539 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1540}
1541
1542bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1543 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1544 return Visit(TSInfo->getTypeLoc());
1545
1546 return false;
1547}
1548
Sean Huntca63c202011-05-24 22:41:36 +00001549bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1550 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1551 return Visit(TSInfo->getTypeLoc());
1552
1553 return false;
1554}
1555
Douglas Gregor2494dd02011-03-01 01:34:45 +00001556bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1557 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1558 return true;
1559
1560 return false;
1561}
1562
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001563bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1564 DependentTemplateSpecializationTypeLoc TL) {
1565 // Visit the nested-name-specifier, if there is one.
1566 if (TL.getQualifierLoc() &&
1567 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1568 return true;
1569
1570 // Visit the template arguments.
1571 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1572 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1573 return true;
1574
1575 return false;
1576}
1577
Douglas Gregor9e876872011-03-01 18:12:44 +00001578bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1579 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1580 return true;
1581
1582 return Visit(TL.getNamedTypeLoc());
1583}
1584
Douglas Gregor7536dd52010-12-20 02:24:11 +00001585bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1586 return Visit(TL.getPatternLoc());
1587}
1588
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001589bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1590 if (Expr *E = TL.getUnderlyingExpr())
1591 return Visit(MakeCXCursor(E, StmtParent, TU));
1592
1593 return false;
1594}
1595
1596bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1597 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1598}
1599
1600#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1601bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1602 return Visit##PARENT##Loc(TL); \
1603}
1604
1605DEFAULT_TYPELOC_IMPL(Complex, Type)
1606DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1607DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1608DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1609DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1610DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1611DEFAULT_TYPELOC_IMPL(Vector, Type)
1612DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1613DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1614DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1615DEFAULT_TYPELOC_IMPL(Record, TagType)
1616DEFAULT_TYPELOC_IMPL(Enum, TagType)
1617DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1618DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1619DEFAULT_TYPELOC_IMPL(Auto, Type)
1620
Ted Kremenek3064ef92010-08-27 21:34:58 +00001621bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001622 // Visit the nested-name-specifier, if present.
1623 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1624 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1625 return true;
1626
Ted Kremenek3064ef92010-08-27 21:34:58 +00001627 if (D->isDefinition()) {
1628 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1629 E = D->bases_end(); I != E; ++I) {
1630 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1631 return true;
1632 }
1633 }
1634
1635 return VisitTagDecl(D);
1636}
1637
Ted Kremenek09dfa372010-02-18 05:46:33 +00001638bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001639 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1640 i != e; ++i)
1641 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001642 return true;
1643
1644 return false;
1645}
1646
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001647//===----------------------------------------------------------------------===//
1648// Data-recursive visitor methods.
1649//===----------------------------------------------------------------------===//
1650
Ted Kremenek28a71942010-11-13 00:36:47 +00001651namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001652#define DEF_JOB(NAME, DATA, KIND)\
1653class NAME : public VisitorJob {\
1654public:\
1655 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1656 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001657 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001658};
1659
1660DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1661DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001662DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001663DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001664DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1665 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001666DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001667#undef DEF_JOB
1668
1669class DeclVisit : public VisitorJob {
1670public:
1671 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1672 VisitorJob(parent, VisitorJob::DeclVisitKind,
1673 d, isFirst ? (void*) 1 : (void*) 0) {}
1674 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001675 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001676 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001677 Decl *get() const { return static_cast<Decl*>(data[0]); }
1678 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001679};
Ted Kremenek035dc412010-11-13 00:36:50 +00001680class TypeLocVisit : public VisitorJob {
1681public:
1682 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1683 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1684 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1685
1686 static bool classof(const VisitorJob *VJ) {
1687 return VJ->getKind() == TypeLocVisitKind;
1688 }
1689
Ted Kremenek82f3c502010-11-15 22:23:26 +00001690 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001691 QualType T = QualType::getFromOpaquePtr(data[0]);
1692 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001693 }
1694};
1695
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001696class LabelRefVisit : public VisitorJob {
1697public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001698 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1699 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001700 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001701
1702 static bool classof(const VisitorJob *VJ) {
1703 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1704 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001705 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001706 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001707 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001708};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001709
1710class NestedNameSpecifierLocVisit : public VisitorJob {
1711public:
1712 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1713 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1714 Qualifier.getNestedNameSpecifier(),
1715 Qualifier.getOpaqueData()) { }
1716
1717 static bool classof(const VisitorJob *VJ) {
1718 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1719 }
1720
1721 NestedNameSpecifierLoc get() const {
1722 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1723 data[1]);
1724 }
1725};
1726
Ted Kremenekf64d8032010-11-18 00:02:32 +00001727class DeclarationNameInfoVisit : public VisitorJob {
1728public:
1729 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1730 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1731 static bool classof(const VisitorJob *VJ) {
1732 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1733 }
1734 DeclarationNameInfo get() const {
1735 Stmt *S = static_cast<Stmt*>(data[0]);
1736 switch (S->getStmtClass()) {
1737 default:
1738 llvm_unreachable("Unhandled Stmt");
1739 case Stmt::CXXDependentScopeMemberExprClass:
1740 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1741 case Stmt::DependentScopeDeclRefExprClass:
1742 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1743 }
1744 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001745};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001746class MemberRefVisit : public VisitorJob {
1747public:
1748 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1749 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001750 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001751 static bool classof(const VisitorJob *VJ) {
1752 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1753 }
1754 FieldDecl *get() const {
1755 return static_cast<FieldDecl*>(data[0]);
1756 }
1757 SourceLocation getLoc() const {
1758 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1759 }
1760};
Ted Kremenek28a71942010-11-13 00:36:47 +00001761class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1762 VisitorWorkList &WL;
1763 CXCursor Parent;
1764public:
1765 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1766 : WL(wl), Parent(parent) {}
1767
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001768 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001769 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001770 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001771 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001772 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001773 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001774 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001775 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001776 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001777 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001778 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001779 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001780 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001781 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001782 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001783 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001784 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001785 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001786 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1787 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001788 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001789 void VisitIfStmt(IfStmt *If);
1790 void VisitInitListExpr(InitListExpr *IE);
1791 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001792 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001793 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001794 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1795 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001796 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001797 void VisitStmt(Stmt *S);
1798 void VisitSwitchStmt(SwitchStmt *S);
1799 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001800 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001801 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001802 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001803 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001804 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001805 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001806 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001807
Ted Kremenek28a71942010-11-13 00:36:47 +00001808private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001809 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001810 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001811 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001812 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001813 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001814 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001815 void AddTypeLoc(TypeSourceInfo *TI);
1816 void EnqueueChildren(Stmt *S);
1817};
1818} // end anonyous namespace
1819
Ted Kremenekf64d8032010-11-18 00:02:32 +00001820void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1821 // 'S' should always be non-null, since it comes from the
1822 // statement we are visiting.
1823 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1824}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001825
1826void
1827EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1828 if (Qualifier)
1829 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1830}
1831
Ted Kremenek28a71942010-11-13 00:36:47 +00001832void EnqueueVisitor::AddStmt(Stmt *S) {
1833 if (S)
1834 WL.push_back(StmtVisit(S, Parent));
1835}
Ted Kremenek035dc412010-11-13 00:36:50 +00001836void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001837 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001838 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001839}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001840void EnqueueVisitor::
1841 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1842 if (A)
1843 WL.push_back(ExplicitTemplateArgsVisit(
1844 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1845}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001846void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1847 if (D)
1848 WL.push_back(MemberRefVisit(D, L, Parent));
1849}
Ted Kremenek28a71942010-11-13 00:36:47 +00001850void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1851 if (TI)
1852 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1853 }
1854void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001855 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001856 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001857 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001858 }
1859 if (size == WL.size())
1860 return;
1861 // Now reverse the entries we just added. This will match the DFS
1862 // ordering performed by the worklist.
1863 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1864 std::reverse(I, E);
1865}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001866void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1867 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1868}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001869void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1870 AddDecl(B->getBlockDecl());
1871}
Ted Kremenek28a71942010-11-13 00:36:47 +00001872void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1873 EnqueueChildren(E);
1874 AddTypeLoc(E->getTypeSourceInfo());
1875}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001876void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1877 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1878 E = S->body_rend(); I != E; ++I) {
1879 AddStmt(*I);
1880 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001881}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001882void EnqueueVisitor::
1883VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1884 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1885 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001886 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1887 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001888 if (!E->isImplicitAccess())
1889 AddStmt(E->getBase());
1890}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001891void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1892 // Enqueue the initializer or constructor arguments.
1893 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1894 AddStmt(E->getConstructorArg(I-1));
1895 // Enqueue the array size, if any.
1896 AddStmt(E->getArraySize());
1897 // Enqueue the allocated type.
1898 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1899 // Enqueue the placement arguments.
1900 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1901 AddStmt(E->getPlacementArg(I-1));
1902}
Ted Kremenek28a71942010-11-13 00:36:47 +00001903void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001904 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1905 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001906 AddStmt(CE->getCallee());
1907 AddStmt(CE->getArg(0));
1908}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001909void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1910 // Visit the name of the type being destroyed.
1911 AddTypeLoc(E->getDestroyedTypeInfo());
1912 // Visit the scope type that looks disturbingly like the nested-name-specifier
1913 // but isn't.
1914 AddTypeLoc(E->getScopeTypeInfo());
1915 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001916 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1917 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001918 // Visit base expression.
1919 AddStmt(E->getBase());
1920}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001921void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1922 AddTypeLoc(E->getTypeSourceInfo());
1923}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001924void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1925 EnqueueChildren(E);
1926 AddTypeLoc(E->getTypeSourceInfo());
1927}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001928void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1929 EnqueueChildren(E);
1930 if (E->isTypeOperand())
1931 AddTypeLoc(E->getTypeOperandSourceInfo());
1932}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001933
1934void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1935 *E) {
1936 EnqueueChildren(E);
1937 AddTypeLoc(E->getTypeSourceInfo());
1938}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001939void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1940 EnqueueChildren(E);
1941 if (E->isTypeOperand())
1942 AddTypeLoc(E->getTypeOperandSourceInfo());
1943}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001944void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001945 if (DR->hasExplicitTemplateArgs()) {
1946 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1947 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001948 WL.push_back(DeclRefExprParts(DR, Parent));
1949}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001950void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1951 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1952 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001953 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001954}
Ted Kremenek035dc412010-11-13 00:36:50 +00001955void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1956 unsigned size = WL.size();
1957 bool isFirst = true;
1958 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1959 D != DEnd; ++D) {
1960 AddDecl(*D, isFirst);
1961 isFirst = false;
1962 }
1963 if (size == WL.size())
1964 return;
1965 // Now reverse the entries we just added. This will match the DFS
1966 // ordering performed by the worklist.
1967 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1968 std::reverse(I, E);
1969}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001970void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1971 AddStmt(E->getInit());
1972 typedef DesignatedInitExpr::Designator Designator;
1973 for (DesignatedInitExpr::reverse_designators_iterator
1974 D = E->designators_rbegin(), DEnd = E->designators_rend();
1975 D != DEnd; ++D) {
1976 if (D->isFieldDesignator()) {
1977 if (FieldDecl *Field = D->getField())
1978 AddMemberRef(Field, D->getFieldLoc());
1979 continue;
1980 }
1981 if (D->isArrayDesignator()) {
1982 AddStmt(E->getArrayIndex(*D));
1983 continue;
1984 }
1985 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1986 AddStmt(E->getArrayRangeEnd(*D));
1987 AddStmt(E->getArrayRangeStart(*D));
1988 }
1989}
Ted Kremenek28a71942010-11-13 00:36:47 +00001990void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1991 EnqueueChildren(E);
1992 AddTypeLoc(E->getTypeInfoAsWritten());
1993}
1994void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1995 AddStmt(FS->getBody());
1996 AddStmt(FS->getInc());
1997 AddStmt(FS->getCond());
1998 AddDecl(FS->getConditionVariable());
1999 AddStmt(FS->getInit());
2000}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002001void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2002 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2003}
Ted Kremenek28a71942010-11-13 00:36:47 +00002004void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2005 AddStmt(If->getElse());
2006 AddStmt(If->getThen());
2007 AddStmt(If->getCond());
2008 AddDecl(If->getConditionVariable());
2009}
2010void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2011 // We care about the syntactic form of the initializer list, only.
2012 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2013 IE = Syntactic;
2014 EnqueueChildren(IE);
2015}
2016void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002017 WL.push_back(MemberExprParts(M, Parent));
2018
2019 // If the base of the member access expression is an implicit 'this', don't
2020 // visit it.
2021 // FIXME: If we ever want to show these implicit accesses, this will be
2022 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002023 if (!M->isImplicitAccess())
2024 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002025}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002026void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2027 AddTypeLoc(E->getEncodedTypeSourceInfo());
2028}
Ted Kremenek28a71942010-11-13 00:36:47 +00002029void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2030 EnqueueChildren(M);
2031 AddTypeLoc(M->getClassReceiverTypeInfo());
2032}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002033void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2034 // Visit the components of the offsetof expression.
2035 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2036 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2037 const OffsetOfNode &Node = E->getComponent(I-1);
2038 switch (Node.getKind()) {
2039 case OffsetOfNode::Array:
2040 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2041 break;
2042 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002043 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002044 break;
2045 case OffsetOfNode::Identifier:
2046 case OffsetOfNode::Base:
2047 continue;
2048 }
2049 }
2050 // Visit the type into which we're computing the offset.
2051 AddTypeLoc(E->getTypeSourceInfo());
2052}
Ted Kremenek28a71942010-11-13 00:36:47 +00002053void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002054 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002055 WL.push_back(OverloadExprParts(E, Parent));
2056}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002057void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2058 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002059 EnqueueChildren(E);
2060 if (E->isArgumentType())
2061 AddTypeLoc(E->getArgumentTypeInfo());
2062}
Ted Kremenek28a71942010-11-13 00:36:47 +00002063void EnqueueVisitor::VisitStmt(Stmt *S) {
2064 EnqueueChildren(S);
2065}
2066void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2067 AddStmt(S->getBody());
2068 AddStmt(S->getCond());
2069 AddDecl(S->getConditionVariable());
2070}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002071
Ted Kremenek28a71942010-11-13 00:36:47 +00002072void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2073 AddStmt(W->getBody());
2074 AddStmt(W->getCond());
2075 AddDecl(W->getConditionVariable());
2076}
John Wiegley21ff2e52011-04-28 00:16:57 +00002077
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002078void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2079 AddTypeLoc(E->getQueriedTypeSourceInfo());
2080}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002081
2082void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002083 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002084 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002085}
2086
John Wiegley21ff2e52011-04-28 00:16:57 +00002087void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2088 AddTypeLoc(E->getQueriedTypeSourceInfo());
2089}
2090
John Wiegley55262202011-04-25 06:54:41 +00002091void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2092 EnqueueChildren(E);
2093}
2094
Ted Kremenek28a71942010-11-13 00:36:47 +00002095void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2096 VisitOverloadExpr(U);
2097 if (!U->isImplicitAccess())
2098 AddStmt(U->getBase());
2099}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002100void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2101 AddStmt(E->getSubExpr());
2102 AddTypeLoc(E->getWrittenTypeInfo());
2103}
Douglas Gregor94d96292011-01-19 20:34:17 +00002104void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2105 WL.push_back(SizeOfPackExprParts(E, Parent));
2106}
Ted Kremenek60458782010-11-12 21:34:16 +00002107
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002108void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002109 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002110}
2111
2112bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2113 if (RegionOfInterest.isValid()) {
2114 SourceRange Range = getRawCursorExtent(C);
2115 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2116 return false;
2117 }
2118 return true;
2119}
2120
2121bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2122 while (!WL.empty()) {
2123 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002124 VisitorJob LI = WL.back();
2125 WL.pop_back();
2126
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002127 // Set the Parent field, then back to its old value once we're done.
2128 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2129
2130 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002131 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002132 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002133 if (!D)
2134 continue;
2135
2136 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002137 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002138 return true;
2139
2140 continue;
2141 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002142 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2143 const ExplicitTemplateArgumentList *ArgList =
2144 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2145 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2146 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2147 Arg != ArgEnd; ++Arg) {
2148 if (VisitTemplateArgumentLoc(*Arg))
2149 return true;
2150 }
2151 continue;
2152 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002153 case VisitorJob::TypeLocVisitKind: {
2154 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002155 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002156 return true;
2157 continue;
2158 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002159 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002160 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002161 if (LabelStmt *stmt = LS->getStmt()) {
2162 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2163 TU))) {
2164 return true;
2165 }
2166 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002167 continue;
2168 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002169
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002170 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2171 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2172 if (VisitNestedNameSpecifierLoc(V->get()))
2173 return true;
2174 continue;
2175 }
2176
Ted Kremenekf64d8032010-11-18 00:02:32 +00002177 case VisitorJob::DeclarationNameInfoVisitKind: {
2178 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2179 ->get()))
2180 return true;
2181 continue;
2182 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002183 case VisitorJob::MemberRefVisitKind: {
2184 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2185 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2186 return true;
2187 continue;
2188 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002189 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002190 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002191 if (!S)
2192 continue;
2193
Ted Kremenekf1107452010-11-12 18:26:56 +00002194 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002195 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002196 if (!IsInRegionOfInterest(Cursor))
2197 continue;
2198 switch (Visitor(Cursor, Parent, ClientData)) {
2199 case CXChildVisit_Break: return true;
2200 case CXChildVisit_Continue: break;
2201 case CXChildVisit_Recurse:
2202 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002203 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002204 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002205 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002206 }
2207 case VisitorJob::MemberExprPartsKind: {
2208 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002209 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002210
2211 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002212 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2213 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002214 return true;
2215
2216 // Visit the declaration name.
2217 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2218 return true;
2219
2220 // Visit the explicitly-specified template arguments, if any.
2221 if (M->hasExplicitTemplateArgs()) {
2222 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2223 *ArgEnd = Arg + M->getNumTemplateArgs();
2224 Arg != ArgEnd; ++Arg) {
2225 if (VisitTemplateArgumentLoc(*Arg))
2226 return true;
2227 }
2228 }
2229 continue;
2230 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002231 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002232 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002233 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002234 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2235 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002236 return true;
2237 // Visit declaration name.
2238 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2239 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002240 continue;
2241 }
Ted Kremenek60458782010-11-12 21:34:16 +00002242 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002243 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002244 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002245 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2246 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002247 return true;
2248 // Visit the declaration name.
2249 if (VisitDeclarationNameInfo(O->getNameInfo()))
2250 return true;
2251 // Visit the overloaded declaration reference.
2252 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2253 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002254 continue;
2255 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002256 case VisitorJob::SizeOfPackExprPartsKind: {
2257 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2258 NamedDecl *Pack = E->getPack();
2259 if (isa<TemplateTypeParmDecl>(Pack)) {
2260 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2261 E->getPackLoc(), TU)))
2262 return true;
2263
2264 continue;
2265 }
2266
2267 if (isa<TemplateTemplateParmDecl>(Pack)) {
2268 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2269 E->getPackLoc(), TU)))
2270 return true;
2271
2272 continue;
2273 }
2274
2275 // Non-type template parameter packs and function parameter packs are
2276 // treated like DeclRefExpr cursors.
2277 continue;
2278 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002279 }
2280 }
2281 return false;
2282}
2283
Ted Kremenekcdba6592010-11-18 00:42:18 +00002284bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002285 VisitorWorkList *WL = 0;
2286 if (!WorkListFreeList.empty()) {
2287 WL = WorkListFreeList.back();
2288 WL->clear();
2289 WorkListFreeList.pop_back();
2290 }
2291 else {
2292 WL = new VisitorWorkList();
2293 WorkListCache.push_back(WL);
2294 }
2295 EnqueueWorkList(*WL, S);
2296 bool result = RunVisitorWorkList(*WL);
2297 WorkListFreeList.push_back(WL);
2298 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002299}
2300
Francois Pichet48a8d142011-07-25 22:00:44 +00002301namespace {
2302typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2303RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2304 const DeclarationNameInfo &NI,
2305 const SourceRange &QLoc,
2306 const ExplicitTemplateArgumentList *TemplateArgs = 0){
2307 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2308 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2309 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2310
2311 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2312
2313 RefNamePieces Pieces;
2314
2315 if (WantQualifier && QLoc.isValid())
2316 Pieces.push_back(QLoc);
2317
2318 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2319 Pieces.push_back(NI.getLoc());
2320
2321 if (WantTemplateArgs && TemplateArgs)
2322 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2323 TemplateArgs->RAngleLoc));
2324
2325 if (Kind == DeclarationName::CXXOperatorName) {
2326 Pieces.push_back(SourceLocation::getFromRawEncoding(
2327 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2328 Pieces.push_back(SourceLocation::getFromRawEncoding(
2329 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2330 }
2331
2332 if (WantSinglePiece) {
2333 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2334 Pieces.clear();
2335 Pieces.push_back(R);
2336 }
2337
2338 return Pieces;
2339}
2340}
2341
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002342//===----------------------------------------------------------------------===//
2343// Misc. API hooks.
2344//===----------------------------------------------------------------------===//
2345
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002346static llvm::sys::Mutex EnableMultithreadingMutex;
2347static bool EnabledMultithreading;
2348
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002349extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002350CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2351 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002352 // Disable pretty stack trace functionality, which will otherwise be a very
2353 // poor citizen of the world and set up all sorts of signal handlers.
2354 llvm::DisablePrettyStackTrace = true;
2355
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002356 // We use crash recovery to make some of our APIs more reliable, implicitly
2357 // enable it.
2358 llvm::CrashRecoveryContext::Enable();
2359
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002360 // Enable support for multithreading in LLVM.
2361 {
2362 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2363 if (!EnabledMultithreading) {
2364 llvm::llvm_start_multithreaded();
2365 EnabledMultithreading = true;
2366 }
2367 }
2368
Douglas Gregora030b7c2010-01-22 20:35:53 +00002369 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002370 if (excludeDeclarationsFromPCH)
2371 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002372 if (displayDiagnostics)
2373 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002374 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002375}
2376
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002377void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002378 if (CIdx)
2379 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002380}
2381
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002382void clang_toggleCrashRecovery(unsigned isEnabled) {
2383 if (isEnabled)
2384 llvm::CrashRecoveryContext::Enable();
2385 else
2386 llvm::CrashRecoveryContext::Disable();
2387}
2388
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002389CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002390 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002391 if (!CIdx)
2392 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002393
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002394 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002395 FileSystemOptions FileSystemOpts;
2396 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002397
Douglas Gregor28019772010-04-05 23:52:57 +00002398 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002399 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002400 CXXIdx->getOnlyLocalDecls(),
2401 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002402 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002403}
2404
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002405unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002406 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002407 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002408}
2409
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002410CXTranslationUnit
2411clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2412 const char *source_filename,
2413 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002414 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002415 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002416 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002417 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002418 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002419 return clang_parseTranslationUnit(CIdx, source_filename,
2420 command_line_args, num_command_line_args,
2421 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002422 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002423}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002424
2425struct ParseTranslationUnitInfo {
2426 CXIndex CIdx;
2427 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002428 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002429 int num_command_line_args;
2430 struct CXUnsavedFile *unsaved_files;
2431 unsigned num_unsaved_files;
2432 unsigned options;
2433 CXTranslationUnit result;
2434};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002435static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002436 ParseTranslationUnitInfo *PTUI =
2437 static_cast<ParseTranslationUnitInfo*>(UserData);
2438 CXIndex CIdx = PTUI->CIdx;
2439 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002440 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002441 int num_command_line_args = PTUI->num_command_line_args;
2442 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2443 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2444 unsigned options = PTUI->options;
2445 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002446
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002447 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002448 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002449
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002450 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2451
Douglas Gregor44c181a2010-07-23 00:33:23 +00002452 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002453 // FIXME: Add a flag for modules.
2454 TranslationUnitKind TUKind
2455 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002456 bool CacheCodeCompetionResults
2457 = options & CXTranslationUnit_CacheCompletionResults;
2458
Douglas Gregor5352ac02010-01-28 00:27:43 +00002459 // Configure the diagnostics.
2460 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002461 llvm::IntrusiveRefCntPtr<Diagnostic>
2462 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2463 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002464
Ted Kremenek25a11e12011-03-22 01:15:24 +00002465 // Recover resources if we crash before exiting this function.
2466 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2467 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2468 DiagCleanup(Diags.getPtr());
2469
2470 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2471 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2472
2473 // Recover resources if we crash before exiting this function.
2474 llvm::CrashRecoveryContextCleanupRegistrar<
2475 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2476
Douglas Gregor4db64a42010-01-23 00:14:00 +00002477 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002478 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002479 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002480 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002481 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2482 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002483 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002484
Ted Kremenek25a11e12011-03-22 01:15:24 +00002485 llvm::OwningPtr<std::vector<const char *> >
2486 Args(new std::vector<const char*>());
2487
2488 // Recover resources if we crash before exiting this method.
2489 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2490 ArgsCleanup(Args.get());
2491
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002492 // Since the Clang C library is primarily used by batch tools dealing with
2493 // (often very broken) source code, where spell-checking can have a
2494 // significant negative impact on performance (particularly when
2495 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002496 // Only do this if we haven't found a spell-checking-related argument.
2497 bool FoundSpellCheckingArgument = false;
2498 for (int I = 0; I != num_command_line_args; ++I) {
2499 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2500 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2501 FoundSpellCheckingArgument = true;
2502 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002503 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002504 }
2505 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002506 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002507
Ted Kremenek25a11e12011-03-22 01:15:24 +00002508 Args->insert(Args->end(), command_line_args,
2509 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002510
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002511 // The 'source_filename' argument is optional. If the caller does not
2512 // specify it then it is assumed that the source file is specified
2513 // in the actual argument list.
2514 // Put the source file after command_line_args otherwise if '-x' flag is
2515 // present it will be unused.
2516 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002517 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002518
Douglas Gregor44c181a2010-07-23 00:33:23 +00002519 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002520 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002521 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002522 Args->push_back("-Xclang");
2523 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002524 NestedMacroExpansions
2525 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002526 }
2527
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002528 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002529 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002530 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2531 /* vector::data() not portable */,
2532 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002533 Diags,
2534 CXXIdx->getClangResourcesPath(),
2535 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002536 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002537 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002538 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002539 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002540 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002541 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002542 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002543 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002544
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002545 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002546 // Make sure to check that 'Unit' is non-NULL.
2547 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2548 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2549 DEnd = Unit->stored_diag_end();
2550 D != DEnd; ++D) {
2551 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2552 CXString Msg = clang_formatDiagnostic(&Diag,
2553 clang_defaultDiagnosticDisplayOptions());
2554 fprintf(stderr, "%s\n", clang_getCString(Msg));
2555 clang_disposeString(Msg);
2556 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002557#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002558 // On Windows, force a flush, since there may be multiple copies of
2559 // stderr and stdout in the file system, all with different buffers
2560 // but writing to the same device.
2561 fflush(stderr);
2562#endif
2563 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002564 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002565
Ted Kremeneka60ed472010-11-16 08:15:36 +00002566 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002567}
2568CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2569 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002570 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002571 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002572 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002573 unsigned num_unsaved_files,
2574 unsigned options) {
2575 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002576 num_command_line_args, unsaved_files,
2577 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002578 llvm::CrashRecoveryContext CRC;
2579
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002580 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002581 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2582 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2583 fprintf(stderr, " 'command_line_args' : [");
2584 for (int i = 0; i != num_command_line_args; ++i) {
2585 if (i)
2586 fprintf(stderr, ", ");
2587 fprintf(stderr, "'%s'", command_line_args[i]);
2588 }
2589 fprintf(stderr, "],\n");
2590 fprintf(stderr, " 'unsaved_files' : [");
2591 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2592 if (i)
2593 fprintf(stderr, ", ");
2594 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2595 unsaved_files[i].Length);
2596 }
2597 fprintf(stderr, "],\n");
2598 fprintf(stderr, " 'options' : %d,\n", options);
2599 fprintf(stderr, "}\n");
2600
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002601 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002602 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2603 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002604 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002605
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002606 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002607}
2608
Douglas Gregor19998442010-08-13 15:35:05 +00002609unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2610 return CXSaveTranslationUnit_None;
2611}
2612
2613int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2614 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002615 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002616 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002617
Douglas Gregor39c411f2011-07-06 16:43:36 +00002618 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002619 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2620 PrintLibclangResourceUsage(TU);
2621 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002622}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002623
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002624void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002625 if (CTUnit) {
2626 // If the translation unit has been marked as unsafe to free, just discard
2627 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002628 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002629 return;
2630
Ted Kremeneka60ed472010-11-16 08:15:36 +00002631 delete static_cast<ASTUnit *>(CTUnit->TUData);
2632 disposeCXStringPool(CTUnit->StringPool);
2633 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002634 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002635}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002636
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002637unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2638 return CXReparse_None;
2639}
2640
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002641struct ReparseTranslationUnitInfo {
2642 CXTranslationUnit TU;
2643 unsigned num_unsaved_files;
2644 struct CXUnsavedFile *unsaved_files;
2645 unsigned options;
2646 int result;
2647};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002648
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002649static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002650 ReparseTranslationUnitInfo *RTUI =
2651 static_cast<ReparseTranslationUnitInfo*>(UserData);
2652 CXTranslationUnit TU = RTUI->TU;
2653 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2654 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2655 unsigned options = RTUI->options;
2656 (void) options;
2657 RTUI->result = 1;
2658
Douglas Gregorabc563f2010-07-19 21:46:24 +00002659 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002660 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002661
Ted Kremeneka60ed472010-11-16 08:15:36 +00002662 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002663 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002664
Ted Kremenek25a11e12011-03-22 01:15:24 +00002665 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2666 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2667
2668 // Recover resources if we crash before exiting this function.
2669 llvm::CrashRecoveryContextCleanupRegistrar<
2670 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2671
Douglas Gregorabc563f2010-07-19 21:46:24 +00002672 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002673 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002674 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002675 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002676 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2677 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002678 }
2679
Ted Kremenek4ee99262011-03-22 20:16:19 +00002680 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2681 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002682 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002683}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002684
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002685int clang_reparseTranslationUnit(CXTranslationUnit TU,
2686 unsigned num_unsaved_files,
2687 struct CXUnsavedFile *unsaved_files,
2688 unsigned options) {
2689 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2690 options, 0 };
2691 llvm::CrashRecoveryContext CRC;
2692
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002693 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002694 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002695 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002696 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002697 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2698 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002699
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002700 return RTUI.result;
2701}
2702
Douglas Gregordf95a132010-08-09 20:45:32 +00002703
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002704CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002705 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002706 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002707
Ted Kremeneka60ed472010-11-16 08:15:36 +00002708 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002709 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002710}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002711
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002712CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002713 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002714 return Result;
2715}
2716
Ted Kremenekfb480492010-01-13 21:46:36 +00002717} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002718
Ted Kremenekfb480492010-01-13 21:46:36 +00002719//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002720// CXSourceLocation and CXSourceRange Operations.
2721//===----------------------------------------------------------------------===//
2722
Douglas Gregorb9790342010-01-22 21:44:22 +00002723extern "C" {
2724CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002725 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002726 return Result;
2727}
2728
2729unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002730 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2731 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2732 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002733}
2734
2735CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2736 CXFile file,
2737 unsigned line,
2738 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002739 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002740 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002741
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002742 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002743 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002744 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002745 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002746 = CXXUnit->getSourceManager().getLocation(File, line, column);
2747 if (SLoc.isInvalid()) {
2748 if (Logging)
2749 llvm::errs() << "clang_getLocation(\"" << File->getName()
2750 << "\", " << line << ", " << column << ") = invalid\n";
2751 return clang_getNullLocation();
2752 }
2753
2754 if (Logging)
2755 llvm::errs() << "clang_getLocation(\"" << File->getName()
2756 << "\", " << line << ", " << column << ") = "
2757 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002758
2759 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2760}
2761
2762CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2763 CXFile file,
2764 unsigned offset) {
2765 if (!tu || !file)
2766 return clang_getNullLocation();
2767
Ted Kremeneka60ed472010-11-16 08:15:36 +00002768 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002769 SourceLocation Start
2770 = CXXUnit->getSourceManager().getLocation(
2771 static_cast<const FileEntry *>(file),
2772 1, 1);
2773 if (Start.isInvalid()) return clang_getNullLocation();
2774
2775 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2776
2777 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002778
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002779 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002780}
2781
Douglas Gregor5352ac02010-01-28 00:27:43 +00002782CXSourceRange clang_getNullRange() {
2783 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2784 return Result;
2785}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002786
Douglas Gregor5352ac02010-01-28 00:27:43 +00002787CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2788 if (begin.ptr_data[0] != end.ptr_data[0] ||
2789 begin.ptr_data[1] != end.ptr_data[1])
2790 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002791
2792 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002793 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002794 return Result;
2795}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002796
2797unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2798{
2799 return range1.ptr_data[0] == range2.ptr_data[0]
2800 && range1.ptr_data[1] == range2.ptr_data[1]
2801 && range1.begin_int_data == range2.begin_int_data
2802 && range1.end_int_data == range2.end_int_data;
2803}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002804} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002805
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002806static void createNullLocation(CXFile *file, unsigned *line,
2807 unsigned *column, unsigned *offset) {
2808 if (file)
2809 *file = 0;
2810 if (line)
2811 *line = 0;
2812 if (column)
2813 *column = 0;
2814 if (offset)
2815 *offset = 0;
2816 return;
2817}
2818
2819extern "C" {
Chandler Carruth20174222011-08-31 16:53:37 +00002820void clang_getExpansionLocation(CXSourceLocation location,
2821 CXFile *file,
2822 unsigned *line,
2823 unsigned *column,
2824 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002825 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2826
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002827 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002828 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002829 return;
2830 }
2831
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002832 const SourceManager &SM =
2833 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth20174222011-08-31 16:53:37 +00002834 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002835
Chandler Carruthcea731a2011-07-14 16:07:57 +00002836 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002837 // This can manifest in invalid code.
Chandler Carruth20174222011-08-31 16:53:37 +00002838 FileID fileID = SM.getFileID(ExpansionLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002839 bool Invalid = false;
2840 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2841 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002842 createNullLocation(file, line, column, offset);
2843 return;
2844 }
2845
Douglas Gregor1db19de2010-01-19 21:36:55 +00002846 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002847 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002848 if (line)
Chandler Carruth20174222011-08-31 16:53:37 +00002849 *line = SM.getExpansionLineNumber(ExpansionLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002850 if (column)
Chandler Carruth20174222011-08-31 16:53:37 +00002851 *column = SM.getExpansionColumnNumber(ExpansionLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002852 if (offset)
Chandler Carruth20174222011-08-31 16:53:37 +00002853 *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2854}
2855
2856void clang_getInstantiationLocation(CXSourceLocation location,
2857 CXFile *file,
2858 unsigned *line,
2859 unsigned *column,
2860 unsigned *offset) {
2861 // Redirect to new API.
2862 clang_getExpansionLocation(location, file, line, column, offset);
Douglas Gregore69517c2010-01-26 03:07:15 +00002863}
2864
Douglas Gregora9b06d42010-11-09 06:24:54 +00002865void clang_getSpellingLocation(CXSourceLocation location,
2866 CXFile *file,
2867 unsigned *line,
2868 unsigned *column,
2869 unsigned *offset) {
2870 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2871
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002872 if (!location.ptr_data[0] || Loc.isInvalid())
2873 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002874
2875 const SourceManager &SM =
2876 *static_cast<const SourceManager*>(location.ptr_data[0]);
2877 SourceLocation SpellLoc = Loc;
2878 if (SpellLoc.isMacroID()) {
2879 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2880 if (SimpleSpellingLoc.isFileID() &&
2881 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2882 SpellLoc = SimpleSpellingLoc;
2883 else
Chandler Carruth40278532011-07-25 16:49:02 +00002884 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002885 }
2886
2887 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2888 FileID FID = LocInfo.first;
2889 unsigned FileOffset = LocInfo.second;
2890
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002891 if (FID.isInvalid())
2892 return createNullLocation(file, line, column, offset);
2893
Douglas Gregora9b06d42010-11-09 06:24:54 +00002894 if (file)
2895 *file = (void *)SM.getFileEntryForID(FID);
2896 if (line)
2897 *line = SM.getLineNumber(FID, FileOffset);
2898 if (column)
2899 *column = SM.getColumnNumber(FID, FileOffset);
2900 if (offset)
2901 *offset = FileOffset;
2902}
2903
Douglas Gregor1db19de2010-01-19 21:36:55 +00002904CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002905 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002906 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002907 return Result;
2908}
2909
2910CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002911 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002912 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002913 return Result;
2914}
2915
Douglas Gregorb9790342010-01-22 21:44:22 +00002916} // end: extern "C"
2917
Douglas Gregor1db19de2010-01-19 21:36:55 +00002918//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002919// CXFile Operations.
2920//===----------------------------------------------------------------------===//
2921
2922extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002923CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002924 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002925 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002926
Steve Naroff88145032009-10-27 14:35:18 +00002927 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002928 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002929}
2930
2931time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002932 if (!SFile)
2933 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002934
Steve Naroff88145032009-10-27 14:35:18 +00002935 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2936 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002937}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002938
Douglas Gregorb9790342010-01-22 21:44:22 +00002939CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2940 if (!tu)
2941 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002942
Ted Kremeneka60ed472010-11-16 08:15:36 +00002943 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002944
Douglas Gregorb9790342010-01-22 21:44:22 +00002945 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002946 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002947}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002948
Douglas Gregordd3e5542011-05-04 00:14:37 +00002949unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2950 if (!tu || !file)
2951 return 0;
2952
2953 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2954 FileEntry *FEnt = static_cast<FileEntry *>(file);
2955 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2956 .isFileMultipleIncludeGuarded(FEnt);
2957}
2958
Ted Kremenekfb480492010-01-13 21:46:36 +00002959} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002960
Ted Kremenekfb480492010-01-13 21:46:36 +00002961//===----------------------------------------------------------------------===//
2962// CXCursor Operations.
2963//===----------------------------------------------------------------------===//
2964
Ted Kremenekfb480492010-01-13 21:46:36 +00002965static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002966 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2967 return getDeclFromExpr(CE->getSubExpr());
2968
Ted Kremenekfb480492010-01-13 21:46:36 +00002969 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2970 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002971 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2972 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002973 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2974 return ME->getMemberDecl();
2975 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2976 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002977 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002978 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002979
Ted Kremenekfb480492010-01-13 21:46:36 +00002980 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2981 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002982 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002983 if (!CE->isElidable())
2984 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002985 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2986 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002987
Douglas Gregordb1314e2010-10-01 21:11:22 +00002988 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2989 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002990 if (SubstNonTypeTemplateParmPackExpr *NTTP
2991 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2992 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002993 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2994 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2995 isa<ParmVarDecl>(SizeOfPack->getPack()))
2996 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002997
Ted Kremenekfb480492010-01-13 21:46:36 +00002998 return 0;
2999}
3000
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003001static SourceLocation getLocationFromExpr(Expr *E) {
3002 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3003 return /*FIXME:*/Msg->getLeftLoc();
3004 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3005 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003006 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3007 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003008 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3009 return Member->getMemberLoc();
3010 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3011 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003012 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3013 return SizeOfPack->getPackLoc();
3014
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003015 return E->getLocStart();
3016}
3017
Ted Kremenekfb480492010-01-13 21:46:36 +00003018extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003019
3020unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003021 CXCursorVisitor visitor,
3022 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003023 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003024 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003025 return CursorVis.VisitChildren(parent);
3026}
3027
David Chisnall3387c652010-11-03 14:12:26 +00003028#ifndef __has_feature
3029#define __has_feature(x) 0
3030#endif
3031#if __has_feature(blocks)
3032typedef enum CXChildVisitResult
3033 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3034
3035static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3036 CXClientData client_data) {
3037 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3038 return block(cursor, parent);
3039}
3040#else
3041// If we are compiled with a compiler that doesn't have native blocks support,
3042// define and call the block manually, so the
3043typedef struct _CXChildVisitResult
3044{
3045 void *isa;
3046 int flags;
3047 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003048 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3049 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003050} *CXCursorVisitorBlock;
3051
3052static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3053 CXClientData client_data) {
3054 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3055 return block->invoke(block, cursor, parent);
3056}
3057#endif
3058
3059
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003060unsigned clang_visitChildrenWithBlock(CXCursor parent,
3061 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003062 return clang_visitChildren(parent, visitWithBlock, block);
3063}
3064
Douglas Gregor78205d42010-01-20 21:45:58 +00003065static CXString getDeclSpelling(Decl *D) {
3066 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003067 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003068 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003069 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3070 return createCXString(Property->getIdentifier()->getName());
3071
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003072 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003073 }
3074
Douglas Gregor78205d42010-01-20 21:45:58 +00003075 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003076 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003077
Douglas Gregor78205d42010-01-20 21:45:58 +00003078 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3079 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3080 // and returns different names. NamedDecl returns the class name and
3081 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003082 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003083
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003084 if (isa<UsingDirectiveDecl>(D))
3085 return createCXString("");
3086
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003087 llvm::SmallString<1024> S;
3088 llvm::raw_svector_ostream os(S);
3089 ND->printName(os);
3090
3091 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003092}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003093
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003094CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003095 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003096 return clang_getTranslationUnitSpelling(
3097 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003098
Steve Narofff334b4e2009-09-02 18:26:48 +00003099 if (clang_isReference(C.kind)) {
3100 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003101 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003102 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003103 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003104 }
3105 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003106 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003107 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003108 }
3109 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003110 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003111 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003112 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003113 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003114 case CXCursor_CXXBaseSpecifier: {
3115 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3116 return createCXString(B->getType().getAsString());
3117 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003118 case CXCursor_TypeRef: {
3119 TypeDecl *Type = getCursorTypeRef(C).first;
3120 assert(Type && "Missing type decl");
3121
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003122 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3123 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003124 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003125 case CXCursor_TemplateRef: {
3126 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003127 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003128
3129 return createCXString(Template->getNameAsString());
3130 }
Douglas Gregor69319002010-08-31 23:48:11 +00003131
3132 case CXCursor_NamespaceRef: {
3133 NamedDecl *NS = getCursorNamespaceRef(C).first;
3134 assert(NS && "Missing namespace decl");
3135
3136 return createCXString(NS->getNameAsString());
3137 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003138
Douglas Gregora67e03f2010-09-09 21:42:20 +00003139 case CXCursor_MemberRef: {
3140 FieldDecl *Field = getCursorMemberRef(C).first;
3141 assert(Field && "Missing member decl");
3142
3143 return createCXString(Field->getNameAsString());
3144 }
3145
Douglas Gregor36897b02010-09-10 00:22:18 +00003146 case CXCursor_LabelRef: {
3147 LabelStmt *Label = getCursorLabelRef(C).first;
3148 assert(Label && "Missing label");
3149
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003150 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003151 }
3152
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003153 case CXCursor_OverloadedDeclRef: {
3154 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3155 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3156 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3157 return createCXString(ND->getNameAsString());
3158 return createCXString("");
3159 }
3160 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3161 return createCXString(E->getName().getAsString());
3162 OverloadedTemplateStorage *Ovl
3163 = Storage.get<OverloadedTemplateStorage*>();
3164 if (Ovl->size() == 0)
3165 return createCXString("");
3166 return createCXString((*Ovl->begin())->getNameAsString());
3167 }
3168
Daniel Dunbaracca7252009-11-30 20:42:49 +00003169 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003170 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003171 }
3172 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003173
3174 if (clang_isExpression(C.kind)) {
3175 Decl *D = getDeclFromExpr(getCursorExpr(C));
3176 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003177 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003178 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003179 }
3180
Douglas Gregor36897b02010-09-10 00:22:18 +00003181 if (clang_isStatement(C.kind)) {
3182 Stmt *S = getCursorStmt(C);
3183 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003184 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003185
3186 return createCXString("");
3187 }
3188
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003189 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003190 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003191 ->getNameStart());
3192
Douglas Gregor572feb22010-03-18 18:04:21 +00003193 if (C.kind == CXCursor_MacroDefinition)
3194 return createCXString(getCursorMacroDefinition(C)->getName()
3195 ->getNameStart());
3196
Douglas Gregorecdcb882010-10-20 22:00:55 +00003197 if (C.kind == CXCursor_InclusionDirective)
3198 return createCXString(getCursorInclusionDirective(C)->getFileName());
3199
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003200 if (clang_isDeclaration(C.kind))
3201 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003202
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003203 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003204}
3205
Douglas Gregor358559d2010-10-02 22:49:11 +00003206CXString clang_getCursorDisplayName(CXCursor C) {
3207 if (!clang_isDeclaration(C.kind))
3208 return clang_getCursorSpelling(C);
3209
3210 Decl *D = getCursorDecl(C);
3211 if (!D)
3212 return createCXString("");
3213
3214 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3215 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3216 D = FunTmpl->getTemplatedDecl();
3217
3218 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3219 llvm::SmallString<64> Str;
3220 llvm::raw_svector_ostream OS(Str);
3221 OS << Function->getNameAsString();
3222 if (Function->getPrimaryTemplate())
3223 OS << "<>";
3224 OS << "(";
3225 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3226 if (I)
3227 OS << ", ";
3228 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3229 }
3230
3231 if (Function->isVariadic()) {
3232 if (Function->getNumParams())
3233 OS << ", ";
3234 OS << "...";
3235 }
3236 OS << ")";
3237 return createCXString(OS.str());
3238 }
3239
3240 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3241 llvm::SmallString<64> Str;
3242 llvm::raw_svector_ostream OS(Str);
3243 OS << ClassTemplate->getNameAsString();
3244 OS << "<";
3245 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3246 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3247 if (I)
3248 OS << ", ";
3249
3250 NamedDecl *Param = Params->getParam(I);
3251 if (Param->getIdentifier()) {
3252 OS << Param->getIdentifier()->getName();
3253 continue;
3254 }
3255
3256 // There is no parameter name, which makes this tricky. Try to come up
3257 // with something useful that isn't too long.
3258 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3259 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3260 else if (NonTypeTemplateParmDecl *NTTP
3261 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3262 OS << NTTP->getType().getAsString(Policy);
3263 else
3264 OS << "template<...> class";
3265 }
3266
3267 OS << ">";
3268 return createCXString(OS.str());
3269 }
3270
3271 if (ClassTemplateSpecializationDecl *ClassSpec
3272 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3273 // If the type was explicitly written, use that.
3274 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3275 return createCXString(TSInfo->getType().getAsString(Policy));
3276
3277 llvm::SmallString<64> Str;
3278 llvm::raw_svector_ostream OS(Str);
3279 OS << ClassSpec->getNameAsString();
3280 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003281 ClassSpec->getTemplateArgs().data(),
3282 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003283 Policy);
3284 return createCXString(OS.str());
3285 }
3286
3287 return clang_getCursorSpelling(C);
3288}
3289
Ted Kremeneke68fff62010-02-17 00:41:32 +00003290CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003291 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003292 case CXCursor_FunctionDecl:
3293 return createCXString("FunctionDecl");
3294 case CXCursor_TypedefDecl:
3295 return createCXString("TypedefDecl");
3296 case CXCursor_EnumDecl:
3297 return createCXString("EnumDecl");
3298 case CXCursor_EnumConstantDecl:
3299 return createCXString("EnumConstantDecl");
3300 case CXCursor_StructDecl:
3301 return createCXString("StructDecl");
3302 case CXCursor_UnionDecl:
3303 return createCXString("UnionDecl");
3304 case CXCursor_ClassDecl:
3305 return createCXString("ClassDecl");
3306 case CXCursor_FieldDecl:
3307 return createCXString("FieldDecl");
3308 case CXCursor_VarDecl:
3309 return createCXString("VarDecl");
3310 case CXCursor_ParmDecl:
3311 return createCXString("ParmDecl");
3312 case CXCursor_ObjCInterfaceDecl:
3313 return createCXString("ObjCInterfaceDecl");
3314 case CXCursor_ObjCCategoryDecl:
3315 return createCXString("ObjCCategoryDecl");
3316 case CXCursor_ObjCProtocolDecl:
3317 return createCXString("ObjCProtocolDecl");
3318 case CXCursor_ObjCPropertyDecl:
3319 return createCXString("ObjCPropertyDecl");
3320 case CXCursor_ObjCIvarDecl:
3321 return createCXString("ObjCIvarDecl");
3322 case CXCursor_ObjCInstanceMethodDecl:
3323 return createCXString("ObjCInstanceMethodDecl");
3324 case CXCursor_ObjCClassMethodDecl:
3325 return createCXString("ObjCClassMethodDecl");
3326 case CXCursor_ObjCImplementationDecl:
3327 return createCXString("ObjCImplementationDecl");
3328 case CXCursor_ObjCCategoryImplDecl:
3329 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003330 case CXCursor_CXXMethod:
3331 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003332 case CXCursor_UnexposedDecl:
3333 return createCXString("UnexposedDecl");
3334 case CXCursor_ObjCSuperClassRef:
3335 return createCXString("ObjCSuperClassRef");
3336 case CXCursor_ObjCProtocolRef:
3337 return createCXString("ObjCProtocolRef");
3338 case CXCursor_ObjCClassRef:
3339 return createCXString("ObjCClassRef");
3340 case CXCursor_TypeRef:
3341 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003342 case CXCursor_TemplateRef:
3343 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003344 case CXCursor_NamespaceRef:
3345 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003346 case CXCursor_MemberRef:
3347 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003348 case CXCursor_LabelRef:
3349 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003350 case CXCursor_OverloadedDeclRef:
3351 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003352 case CXCursor_UnexposedExpr:
3353 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003354 case CXCursor_BlockExpr:
3355 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003356 case CXCursor_DeclRefExpr:
3357 return createCXString("DeclRefExpr");
3358 case CXCursor_MemberRefExpr:
3359 return createCXString("MemberRefExpr");
3360 case CXCursor_CallExpr:
3361 return createCXString("CallExpr");
3362 case CXCursor_ObjCMessageExpr:
3363 return createCXString("ObjCMessageExpr");
3364 case CXCursor_UnexposedStmt:
3365 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003366 case CXCursor_LabelStmt:
3367 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003368 case CXCursor_InvalidFile:
3369 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003370 case CXCursor_InvalidCode:
3371 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003372 case CXCursor_NoDeclFound:
3373 return createCXString("NoDeclFound");
3374 case CXCursor_NotImplemented:
3375 return createCXString("NotImplemented");
3376 case CXCursor_TranslationUnit:
3377 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003378 case CXCursor_UnexposedAttr:
3379 return createCXString("UnexposedAttr");
3380 case CXCursor_IBActionAttr:
3381 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003382 case CXCursor_IBOutletAttr:
3383 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003384 case CXCursor_IBOutletCollectionAttr:
3385 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003386 case CXCursor_PreprocessingDirective:
3387 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003388 case CXCursor_MacroDefinition:
3389 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003390 case CXCursor_MacroExpansion:
3391 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003392 case CXCursor_InclusionDirective:
3393 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003394 case CXCursor_Namespace:
3395 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003396 case CXCursor_LinkageSpec:
3397 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003398 case CXCursor_CXXBaseSpecifier:
3399 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003400 case CXCursor_Constructor:
3401 return createCXString("CXXConstructor");
3402 case CXCursor_Destructor:
3403 return createCXString("CXXDestructor");
3404 case CXCursor_ConversionFunction:
3405 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003406 case CXCursor_TemplateTypeParameter:
3407 return createCXString("TemplateTypeParameter");
3408 case CXCursor_NonTypeTemplateParameter:
3409 return createCXString("NonTypeTemplateParameter");
3410 case CXCursor_TemplateTemplateParameter:
3411 return createCXString("TemplateTemplateParameter");
3412 case CXCursor_FunctionTemplate:
3413 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003414 case CXCursor_ClassTemplate:
3415 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003416 case CXCursor_ClassTemplatePartialSpecialization:
3417 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003418 case CXCursor_NamespaceAlias:
3419 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003420 case CXCursor_UsingDirective:
3421 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003422 case CXCursor_UsingDeclaration:
3423 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003424 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003425 return createCXString("TypeAliasDecl");
3426 case CXCursor_ObjCSynthesizeDecl:
3427 return createCXString("ObjCSynthesizeDecl");
3428 case CXCursor_ObjCDynamicDecl:
3429 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003430 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003431
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003432 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003433 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003434}
Steve Naroff89922f82009-08-31 00:59:03 +00003435
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003436struct GetCursorData {
3437 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003438 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003439 CXCursor &BestCursor;
3440
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003441 GetCursorData(SourceManager &SM,
3442 SourceLocation tokenBegin, CXCursor &outputCursor)
3443 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3444 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3445 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003446};
3447
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003448static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3449 CXCursor parent,
3450 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003451 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3452 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003453
3454 // If we point inside a macro argument we should provide info of what the
3455 // token is so use the actual cursor, don't replace it with a macro expansion
3456 // cursor.
3457 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3458 return CXChildVisit_Recurse;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003459
3460 if (clang_isExpression(cursor.kind) &&
3461 clang_isDeclaration(BestCursor->kind)) {
3462 Decl *D = getCursorDecl(*BestCursor);
3463
3464 // Avoid having the cursor of an expression replace the declaration cursor
3465 // when the expression source range overlaps the declaration range.
3466 // This can happen for C++ constructor expressions whose range generally
3467 // include the variable declaration, e.g.:
3468 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3469 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3470 D->getLocation() == Data->TokenBeginLoc)
3471 return CXChildVisit_Break;
3472 }
3473
Douglas Gregor93798e22010-11-05 21:11:19 +00003474 // If our current best cursor is the construction of a temporary object,
3475 // don't replace that cursor with a type reference, because we want
3476 // clang_getCursor() to point at the constructor.
3477 if (clang_isExpression(BestCursor->kind) &&
3478 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3479 cursor.kind == CXCursor_TypeRef)
3480 return CXChildVisit_Recurse;
3481
Douglas Gregor85fe1562010-12-10 07:23:11 +00003482 // Don't override a preprocessing cursor with another preprocessing
3483 // cursor; we want the outermost preprocessing cursor.
3484 if (clang_isPreprocessing(cursor.kind) &&
3485 clang_isPreprocessing(BestCursor->kind))
3486 return CXChildVisit_Recurse;
3487
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003488 *BestCursor = cursor;
3489 return CXChildVisit_Recurse;
3490}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003491
Douglas Gregorb9790342010-01-22 21:44:22 +00003492CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3493 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003494 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003495
Ted Kremeneka60ed472010-11-16 08:15:36 +00003496 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003497 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3498
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003499 // Translate the given source location to make it point at the beginning of
3500 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003501 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003502
3503 // Guard against an invalid SourceLocation, or we may assert in one
3504 // of the following calls.
3505 if (SLoc.isInvalid())
3506 return clang_getNullCursor();
3507
Douglas Gregor40749ee2010-11-03 00:35:38 +00003508 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003509 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3510 CXXUnit->getASTContext().getLangOptions());
3511
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003512 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3513 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003514 // FIXME: Would be great to have a "hint" cursor, then walk from that
3515 // hint cursor upward until we find a cursor whose source range encloses
3516 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003517 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003518 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003519 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00003520 /*VisitPreprocessorLast=*/true,
3521 SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003522 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003523 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003524
3525 if (Logging) {
3526 CXFile SearchFile;
3527 unsigned SearchLine, SearchColumn;
3528 CXFile ResultFile;
3529 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003530 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3531 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003532 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3533
Chandler Carruth20174222011-08-31 16:53:37 +00003534 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3535 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3536 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003537 SearchFileName = clang_getFileName(SearchFile);
3538 ResultFileName = clang_getFileName(ResultFile);
3539 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003540 USR = clang_getCursorUSR(Result);
3541 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003542 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3543 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003544 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3545 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003546 clang_disposeString(SearchFileName);
3547 clang_disposeString(ResultFileName);
3548 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003549 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003550
3551 CXCursor Definition = clang_getCursorDefinition(Result);
3552 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3553 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3554 CXString DefinitionKindSpelling
3555 = clang_getCursorKindSpelling(Definition.kind);
3556 CXFile DefinitionFile;
3557 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003558 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3559 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003560 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3561 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3562 clang_getCString(DefinitionKindSpelling),
3563 clang_getCString(DefinitionFileName),
3564 DefinitionLine, DefinitionColumn);
3565 clang_disposeString(DefinitionFileName);
3566 clang_disposeString(DefinitionKindSpelling);
3567 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003568 }
3569
Ted Kremeneke68fff62010-02-17 00:41:32 +00003570 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003571}
3572
Ted Kremenek73885552009-11-17 19:28:59 +00003573CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003574 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003575}
3576
3577unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003578 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003579}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003580
Douglas Gregor9ce55842010-11-20 00:09:34 +00003581unsigned clang_hashCursor(CXCursor C) {
3582 unsigned Index = 0;
3583 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3584 Index = 1;
3585
3586 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3587 std::make_pair(C.kind, C.data[Index]));
3588}
3589
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003590unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003591 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3592}
3593
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003594unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003595 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3596}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003597
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003598unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003599 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3600}
3601
Douglas Gregor97b98722010-01-19 23:20:36 +00003602unsigned clang_isExpression(enum CXCursorKind K) {
3603 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3604}
3605
3606unsigned clang_isStatement(enum CXCursorKind K) {
3607 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3608}
3609
Douglas Gregor8be80e12011-07-06 03:00:34 +00003610unsigned clang_isAttribute(enum CXCursorKind K) {
3611 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3612}
3613
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003614unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3615 return K == CXCursor_TranslationUnit;
3616}
3617
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003618unsigned clang_isPreprocessing(enum CXCursorKind K) {
3619 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3620}
3621
Ted Kremenekad6eff62010-03-08 21:17:29 +00003622unsigned clang_isUnexposed(enum CXCursorKind K) {
3623 switch (K) {
3624 case CXCursor_UnexposedDecl:
3625 case CXCursor_UnexposedExpr:
3626 case CXCursor_UnexposedStmt:
3627 case CXCursor_UnexposedAttr:
3628 return true;
3629 default:
3630 return false;
3631 }
3632}
3633
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003634CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003635 return C.kind;
3636}
3637
Douglas Gregor98258af2010-01-18 22:46:11 +00003638CXSourceLocation clang_getCursorLocation(CXCursor C) {
3639 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003640 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003641 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003642 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3643 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003644 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003645 }
3646
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003647 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003648 std::pair<ObjCProtocolDecl *, SourceLocation> P
3649 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003650 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003651 }
3652
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003653 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003654 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3655 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003656 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003657 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003658
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003659 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003660 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003661 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003662 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003663
3664 case CXCursor_TemplateRef: {
3665 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3666 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3667 }
3668
Douglas Gregor69319002010-08-31 23:48:11 +00003669 case CXCursor_NamespaceRef: {
3670 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3671 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3672 }
3673
Douglas Gregora67e03f2010-09-09 21:42:20 +00003674 case CXCursor_MemberRef: {
3675 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3676 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3677 }
3678
Ted Kremenek3064ef92010-08-27 21:34:58 +00003679 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003680 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3681 if (!BaseSpec)
3682 return clang_getNullLocation();
3683
3684 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3685 return cxloc::translateSourceLocation(getCursorContext(C),
3686 TSInfo->getTypeLoc().getBeginLoc());
3687
3688 return cxloc::translateSourceLocation(getCursorContext(C),
3689 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003690 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003691
Douglas Gregor36897b02010-09-10 00:22:18 +00003692 case CXCursor_LabelRef: {
3693 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3694 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3695 }
3696
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003697 case CXCursor_OverloadedDeclRef:
3698 return cxloc::translateSourceLocation(getCursorContext(C),
3699 getCursorOverloadedDeclRef(C).second);
3700
Douglas Gregorf46034a2010-01-18 23:41:10 +00003701 default:
3702 // FIXME: Need a way to enumerate all non-reference cases.
3703 llvm_unreachable("Missed a reference kind");
3704 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003705 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003706
3707 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003708 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003709 getLocationFromExpr(getCursorExpr(C)));
3710
Douglas Gregor36897b02010-09-10 00:22:18 +00003711 if (clang_isStatement(C.kind))
3712 return cxloc::translateSourceLocation(getCursorContext(C),
3713 getCursorStmt(C)->getLocStart());
3714
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003715 if (C.kind == CXCursor_PreprocessingDirective) {
3716 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3717 return cxloc::translateSourceLocation(getCursorContext(C), L);
3718 }
Douglas Gregor48072312010-03-18 15:23:44 +00003719
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003720 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003721 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003722 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003723 return cxloc::translateSourceLocation(getCursorContext(C), L);
3724 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003725
3726 if (C.kind == CXCursor_MacroDefinition) {
3727 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3728 return cxloc::translateSourceLocation(getCursorContext(C), L);
3729 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003730
3731 if (C.kind == CXCursor_InclusionDirective) {
3732 SourceLocation L
3733 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3734 return cxloc::translateSourceLocation(getCursorContext(C), L);
3735 }
3736
Ted Kremenek9a700d22010-05-12 06:16:13 +00003737 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003738 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003739
Douglas Gregorf46034a2010-01-18 23:41:10 +00003740 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003741 SourceLocation Loc = D->getLocation();
3742 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3743 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003744 // FIXME: Multiple variables declared in a single declaration
3745 // currently lack the information needed to correctly determine their
3746 // ranges when accounting for the type-specifier. We use context
3747 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3748 // and if so, whether it is the first decl.
3749 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3750 if (!cxcursor::isFirstInDeclGroup(C))
3751 Loc = VD->getLocation();
3752 }
3753
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003754 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003755}
Douglas Gregora7bde202010-01-19 00:34:46 +00003756
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003757} // end extern "C"
3758
3759static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003760 if (clang_isReference(C.kind)) {
3761 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003762 case CXCursor_ObjCSuperClassRef:
3763 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003764
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003765 case CXCursor_ObjCProtocolRef:
3766 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003767
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003768 case CXCursor_ObjCClassRef:
3769 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003770
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003771 case CXCursor_TypeRef:
3772 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003773
3774 case CXCursor_TemplateRef:
3775 return getCursorTemplateRef(C).second;
3776
Douglas Gregor69319002010-08-31 23:48:11 +00003777 case CXCursor_NamespaceRef:
3778 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003779
3780 case CXCursor_MemberRef:
3781 return getCursorMemberRef(C).second;
3782
Ted Kremenek3064ef92010-08-27 21:34:58 +00003783 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003784 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003785
Douglas Gregor36897b02010-09-10 00:22:18 +00003786 case CXCursor_LabelRef:
3787 return getCursorLabelRef(C).second;
3788
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003789 case CXCursor_OverloadedDeclRef:
3790 return getCursorOverloadedDeclRef(C).second;
3791
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003792 default:
3793 // FIXME: Need a way to enumerate all non-reference cases.
3794 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003795 }
3796 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003797
3798 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003799 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003800
3801 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003802 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003803
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003804 if (C.kind == CXCursor_PreprocessingDirective)
3805 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003806
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003807 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003808 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003809
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003810 if (C.kind == CXCursor_MacroDefinition)
3811 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003812
3813 if (C.kind == CXCursor_InclusionDirective)
3814 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3815
Ted Kremenek007a7c92010-11-01 23:26:51 +00003816 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3817 Decl *D = cxcursor::getCursorDecl(C);
3818 SourceRange R = D->getSourceRange();
3819 // FIXME: Multiple variables declared in a single declaration
3820 // currently lack the information needed to correctly determine their
3821 // ranges when accounting for the type-specifier. We use context
3822 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3823 // and if so, whether it is the first decl.
3824 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3825 if (!cxcursor::isFirstInDeclGroup(C))
3826 R.setBegin(VD->getLocation());
3827 }
3828 return R;
3829 }
Douglas Gregor66537982010-11-17 17:14:07 +00003830 return SourceRange();
3831}
3832
3833/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3834/// the decl-specifier-seq for declarations.
3835static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3836 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3837 Decl *D = cxcursor::getCursorDecl(C);
3838 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003839
Douglas Gregor2494dd02011-03-01 01:34:45 +00003840 // Adjust the start of the location for declarations preceded by
3841 // declaration specifiers.
3842 SourceLocation StartLoc;
3843 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3844 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3845 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3846 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3847 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3848 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3849 }
3850
3851 if (StartLoc.isValid() && R.getBegin().isValid() &&
3852 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3853 R.setBegin(StartLoc);
3854
3855 // FIXME: Multiple variables declared in a single declaration
3856 // currently lack the information needed to correctly determine their
3857 // ranges when accounting for the type-specifier. We use context
3858 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3859 // and if so, whether it is the first decl.
3860 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3861 if (!cxcursor::isFirstInDeclGroup(C))
3862 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003863 }
3864
3865 return R;
3866 }
3867
3868 return getRawCursorExtent(C);
3869}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003870
3871extern "C" {
3872
3873CXSourceRange clang_getCursorExtent(CXCursor C) {
3874 SourceRange R = getRawCursorExtent(C);
3875 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003876 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003877
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003878 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003879}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003880
3881CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003882 if (clang_isInvalid(C.kind))
3883 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003884
Ted Kremeneka60ed472010-11-16 08:15:36 +00003885 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003886 if (clang_isDeclaration(C.kind)) {
3887 Decl *D = getCursorDecl(C);
3888 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003889 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003890 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003891 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003892 if (ObjCForwardProtocolDecl *Protocols
3893 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003894 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003895 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003896 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3897 return MakeCXCursor(Property, tu);
3898
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003899 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003900 }
3901
Douglas Gregor97b98722010-01-19 23:20:36 +00003902 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003903 Expr *E = getCursorExpr(C);
3904 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003905 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003906 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003907
3908 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003909 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003910
Douglas Gregor97b98722010-01-19 23:20:36 +00003911 return clang_getNullCursor();
3912 }
3913
Douglas Gregor36897b02010-09-10 00:22:18 +00003914 if (clang_isStatement(C.kind)) {
3915 Stmt *S = getCursorStmt(C);
3916 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003917 if (LabelDecl *label = Goto->getLabel())
3918 if (LabelStmt *labelS = label->getStmt())
3919 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003920
3921 return clang_getNullCursor();
3922 }
3923
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003924 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003925 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003926 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003927 }
3928
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003929 if (!clang_isReference(C.kind))
3930 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003931
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003932 switch (C.kind) {
3933 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003934 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003935
3936 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003937 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003938
3939 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003940 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003941
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003942 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003943 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003944
3945 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003946 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003947
Douglas Gregor69319002010-08-31 23:48:11 +00003948 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003949 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003950
Douglas Gregora67e03f2010-09-09 21:42:20 +00003951 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003952 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003953
Ted Kremenek3064ef92010-08-27 21:34:58 +00003954 case CXCursor_CXXBaseSpecifier: {
3955 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3956 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003957 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003958 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003959
Douglas Gregor36897b02010-09-10 00:22:18 +00003960 case CXCursor_LabelRef:
3961 // FIXME: We end up faking the "parent" declaration here because we
3962 // don't want to make CXCursor larger.
3963 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003964 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3965 .getTranslationUnitDecl(),
3966 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003967
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003968 case CXCursor_OverloadedDeclRef:
3969 return C;
3970
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003971 default:
3972 // We would prefer to enumerate all non-reference cursor kinds here.
3973 llvm_unreachable("Unhandled reference cursor kind");
3974 break;
3975 }
3976 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003977
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003978 return clang_getNullCursor();
3979}
3980
Douglas Gregorb6998662010-01-19 19:34:47 +00003981CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003982 if (clang_isInvalid(C.kind))
3983 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003984
Ted Kremeneka60ed472010-11-16 08:15:36 +00003985 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003986
Douglas Gregorb6998662010-01-19 19:34:47 +00003987 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003988 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003989 C = clang_getCursorReferenced(C);
3990 WasReference = true;
3991 }
3992
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003993 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003994 return clang_getCursorReferenced(C);
3995
Douglas Gregorb6998662010-01-19 19:34:47 +00003996 if (!clang_isDeclaration(C.kind))
3997 return clang_getNullCursor();
3998
3999 Decl *D = getCursorDecl(C);
4000 if (!D)
4001 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004002
Douglas Gregorb6998662010-01-19 19:34:47 +00004003 switch (D->getKind()) {
4004 // Declaration kinds that don't really separate the notions of
4005 // declaration and definition.
4006 case Decl::Namespace:
4007 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004008 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004009 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004010 case Decl::TemplateTypeParm:
4011 case Decl::EnumConstant:
4012 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004013 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004014 case Decl::ObjCIvar:
4015 case Decl::ObjCAtDefsField:
4016 case Decl::ImplicitParam:
4017 case Decl::ParmVar:
4018 case Decl::NonTypeTemplateParm:
4019 case Decl::TemplateTemplateParm:
4020 case Decl::ObjCCategoryImpl:
4021 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004022 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004023 case Decl::LinkageSpec:
4024 case Decl::ObjCPropertyImpl:
4025 case Decl::FileScopeAsm:
4026 case Decl::StaticAssert:
4027 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004028 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004029 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004030 return C;
4031
4032 // Declaration kinds that don't make any sense here, but are
4033 // nonetheless harmless.
4034 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004035 break;
4036
4037 // Declaration kinds for which the definition is not resolvable.
4038 case Decl::UnresolvedUsingTypename:
4039 case Decl::UnresolvedUsingValue:
4040 break;
4041
4042 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004043 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004044 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004045
4046 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004047 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004048
4049 case Decl::Enum:
4050 case Decl::Record:
4051 case Decl::CXXRecord:
4052 case Decl::ClassTemplateSpecialization:
4053 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004054 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004055 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004056 return clang_getNullCursor();
4057
4058 case Decl::Function:
4059 case Decl::CXXMethod:
4060 case Decl::CXXConstructor:
4061 case Decl::CXXDestructor:
4062 case Decl::CXXConversion: {
4063 const FunctionDecl *Def = 0;
4064 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004065 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004066 return clang_getNullCursor();
4067 }
4068
4069 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004070 // Ask the variable if it has a definition.
4071 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004072 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004073 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004074 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004075
Douglas Gregorb6998662010-01-19 19:34:47 +00004076 case Decl::FunctionTemplate: {
4077 const FunctionDecl *Def = 0;
4078 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004079 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004080 return clang_getNullCursor();
4081 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004082
Douglas Gregorb6998662010-01-19 19:34:47 +00004083 case Decl::ClassTemplate: {
4084 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004085 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004086 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004087 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004088 return clang_getNullCursor();
4089 }
4090
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004091 case Decl::Using:
4092 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004093 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004094
4095 case Decl::UsingShadow:
4096 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004097 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004098 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004099
4100 case Decl::ObjCMethod: {
4101 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4102 if (Method->isThisDeclarationADefinition())
4103 return C;
4104
4105 // Dig out the method definition in the associated
4106 // @implementation, if we have it.
4107 // FIXME: The ASTs should make finding the definition easier.
4108 if (ObjCInterfaceDecl *Class
4109 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4110 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4111 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4112 Method->isInstanceMethod()))
4113 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004115
4116 return clang_getNullCursor();
4117 }
4118
4119 case Decl::ObjCCategory:
4120 if (ObjCCategoryImplDecl *Impl
4121 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004122 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004123 return clang_getNullCursor();
4124
4125 case Decl::ObjCProtocol:
4126 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4127 return C;
4128 return clang_getNullCursor();
4129
4130 case Decl::ObjCInterface:
4131 // There are two notions of a "definition" for an Objective-C
4132 // class: the interface and its implementation. When we resolved a
4133 // reference to an Objective-C class, produce the @interface as
4134 // the definition; when we were provided with the interface,
4135 // produce the @implementation as the definition.
4136 if (WasReference) {
4137 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4138 return C;
4139 } else if (ObjCImplementationDecl *Impl
4140 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004141 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004142 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004143
Douglas Gregorb6998662010-01-19 19:34:47 +00004144 case Decl::ObjCProperty:
4145 // FIXME: We don't really know where to find the
4146 // ObjCPropertyImplDecls that implement this property.
4147 return clang_getNullCursor();
4148
4149 case Decl::ObjCCompatibleAlias:
4150 if (ObjCInterfaceDecl *Class
4151 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4152 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004153 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004154
Douglas Gregorb6998662010-01-19 19:34:47 +00004155 return clang_getNullCursor();
4156
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004157 case Decl::ObjCForwardProtocol:
4158 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004159 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004160
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004161 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004162 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004163 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004164
4165 case Decl::Friend:
4166 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004167 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004168 return clang_getNullCursor();
4169
4170 case Decl::FriendTemplate:
4171 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004172 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004173 return clang_getNullCursor();
4174 }
4175
4176 return clang_getNullCursor();
4177}
4178
4179unsigned clang_isCursorDefinition(CXCursor C) {
4180 if (!clang_isDeclaration(C.kind))
4181 return 0;
4182
4183 return clang_getCursorDefinition(C) == C;
4184}
4185
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004186CXCursor clang_getCanonicalCursor(CXCursor C) {
4187 if (!clang_isDeclaration(C.kind))
4188 return C;
4189
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004190 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004191 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4192 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4193 return MakeCXCursor(CatD, getCursorTU(C));
4194
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004195 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4196 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4197 return MakeCXCursor(IFD, getCursorTU(C));
4198
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004199 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004200 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004201
4202 return C;
4203}
4204
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004205unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004206 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004207 return 0;
4208
4209 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4210 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4211 return E->getNumDecls();
4212
4213 if (OverloadedTemplateStorage *S
4214 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4215 return S->size();
4216
4217 Decl *D = Storage.get<Decl*>();
4218 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004219 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004220 if (isa<ObjCClassDecl>(D))
4221 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004222 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4223 return Protocols->protocol_size();
4224
4225 return 0;
4226}
4227
4228CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004229 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004230 return clang_getNullCursor();
4231
4232 if (index >= clang_getNumOverloadedDecls(cursor))
4233 return clang_getNullCursor();
4234
Ted Kremeneka60ed472010-11-16 08:15:36 +00004235 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004236 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4237 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004238 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004239
4240 if (OverloadedTemplateStorage *S
4241 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004242 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004243
4244 Decl *D = Storage.get<Decl*>();
4245 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4246 // FIXME: This is, unfortunately, linear time.
4247 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4248 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004249 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004250 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004251 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004252 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004253 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004254 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004255
4256 return clang_getNullCursor();
4257}
4258
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004259void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004260 const char **startBuf,
4261 const char **endBuf,
4262 unsigned *startLine,
4263 unsigned *startColumn,
4264 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004265 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004266 assert(getCursorDecl(C) && "CXCursor has null decl");
4267 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004268 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4269 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004270
Steve Naroff4ade6d62009-09-23 17:52:52 +00004271 SourceManager &SM = FD->getASTContext().getSourceManager();
4272 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4273 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4274 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4275 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4276 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4277 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4278}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004279
Douglas Gregor430d7a12011-07-25 17:48:11 +00004280
4281CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4282 unsigned PieceIndex) {
4283 RefNamePieces Pieces;
4284
4285 switch (C.kind) {
4286 case CXCursor_MemberRefExpr:
4287 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4288 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4289 E->getQualifierLoc().getSourceRange());
4290 break;
4291
4292 case CXCursor_DeclRefExpr:
4293 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4294 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4295 E->getQualifierLoc().getSourceRange(),
4296 E->getExplicitTemplateArgsOpt());
4297 break;
4298
4299 case CXCursor_CallExpr:
4300 if (CXXOperatorCallExpr *OCE =
4301 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4302 Expr *Callee = OCE->getCallee();
4303 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4304 Callee = ICE->getSubExpr();
4305
4306 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4307 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4308 DRE->getQualifierLoc().getSourceRange());
4309 }
4310 break;
4311
4312 default:
4313 break;
4314 }
4315
4316 if (Pieces.empty()) {
4317 if (PieceIndex == 0)
4318 return clang_getCursorExtent(C);
4319 } else if (PieceIndex < Pieces.size()) {
4320 SourceRange R = Pieces[PieceIndex];
4321 if (R.isValid())
4322 return cxloc::translateSourceRange(getCursorContext(C), R);
4323 }
4324
4325 return clang_getNullRange();
4326}
4327
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004328void clang_enableStackTraces(void) {
4329 llvm::sys::PrintStackTraceOnErrorSignal();
4330}
4331
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004332void clang_executeOnThread(void (*fn)(void*), void *user_data,
4333 unsigned stack_size) {
4334 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4335}
4336
Ted Kremenekfb480492010-01-13 21:46:36 +00004337} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004338
Ted Kremenekfb480492010-01-13 21:46:36 +00004339//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004340// Token-based Operations.
4341//===----------------------------------------------------------------------===//
4342
4343/* CXToken layout:
4344 * int_data[0]: a CXTokenKind
4345 * int_data[1]: starting token location
4346 * int_data[2]: token length
4347 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004348 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004349 * otherwise unused.
4350 */
4351extern "C" {
4352
4353CXTokenKind clang_getTokenKind(CXToken CXTok) {
4354 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4355}
4356
4357CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4358 switch (clang_getTokenKind(CXTok)) {
4359 case CXToken_Identifier:
4360 case CXToken_Keyword:
4361 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004362 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4363 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004364
4365 case CXToken_Literal: {
4366 // We have stashed the starting pointer in the ptr_data field. Use it.
4367 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004368 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004369 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004370
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004371 case CXToken_Punctuation:
4372 case CXToken_Comment:
4373 break;
4374 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004375
4376 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004377 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004378 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004379 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004380 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004381
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004382 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4383 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004384 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004385 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004386 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004387 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4388 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004389 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004390
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004391 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004392}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004393
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004394CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004395 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004396 if (!CXXUnit)
4397 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004398
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004399 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4400 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4401}
4402
4403CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004404 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004405 if (!CXXUnit)
4406 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004407
4408 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004409 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4410}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004411
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004412void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4413 CXToken **Tokens, unsigned *NumTokens) {
4414 if (Tokens)
4415 *Tokens = 0;
4416 if (NumTokens)
4417 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004418
Ted Kremeneka60ed472010-11-16 08:15:36 +00004419 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004420 if (!CXXUnit || !Tokens || !NumTokens)
4421 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004422
Douglas Gregorbdf60622010-03-05 21:16:25 +00004423 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4424
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004425 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004426 if (R.isInvalid())
4427 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004428
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004429 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4430 std::pair<FileID, unsigned> BeginLocInfo
4431 = SourceMgr.getDecomposedLoc(R.getBegin());
4432 std::pair<FileID, unsigned> EndLocInfo
4433 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004434
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004435 // Cannot tokenize across files.
4436 if (BeginLocInfo.first != EndLocInfo.first)
4437 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004438
4439 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004440 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004441 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004442 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004443 if (Invalid)
4444 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004445
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004446 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4447 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004448 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004449 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004450
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004451 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004452 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004453 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004454 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004455 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004456 do {
4457 // Lex the next token
4458 Lex.LexFromRawLexer(Tok);
4459 if (Tok.is(tok::eof))
4460 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004461
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004462 // Initialize the CXToken.
4463 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004464
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004465 // - Common fields
4466 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4467 CXTok.int_data[2] = Tok.getLength();
4468 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004469
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004470 // - Kind-specific fields
4471 if (Tok.isLiteral()) {
4472 CXTok.int_data[0] = CXToken_Literal;
4473 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004474 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004475 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004476 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004477 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004478
David Chisnall096428b2010-10-13 21:44:48 +00004479 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004480 CXTok.int_data[0] = CXToken_Keyword;
4481 }
4482 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004483 CXTok.int_data[0] = Tok.is(tok::identifier)
4484 ? CXToken_Identifier
4485 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004486 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004487 CXTok.ptr_data = II;
4488 } else if (Tok.is(tok::comment)) {
4489 CXTok.int_data[0] = CXToken_Comment;
4490 CXTok.ptr_data = 0;
4491 } else {
4492 CXTok.int_data[0] = CXToken_Punctuation;
4493 CXTok.ptr_data = 0;
4494 }
4495 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004496 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004497 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004498
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004499 if (CXTokens.empty())
4500 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004501
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004502 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4503 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4504 *NumTokens = CXTokens.size();
4505}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004506
Ted Kremenek6db61092010-05-05 00:55:15 +00004507void clang_disposeTokens(CXTranslationUnit TU,
4508 CXToken *Tokens, unsigned NumTokens) {
4509 free(Tokens);
4510}
4511
4512} // end: extern "C"
4513
4514//===----------------------------------------------------------------------===//
4515// Token annotation APIs.
4516//===----------------------------------------------------------------------===//
4517
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004518typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004519static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4520 CXCursor parent,
4521 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004522namespace {
4523class AnnotateTokensWorker {
4524 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004525 CXToken *Tokens;
4526 CXCursor *Cursors;
4527 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004528 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004529 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004530 CursorVisitor AnnotateVis;
4531 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004532 bool HasContextSensitiveKeywords;
4533
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004534 bool MoreTokens() const { return TokIdx < NumTokens; }
4535 unsigned NextToken() const { return TokIdx; }
4536 void AdvanceToken() { ++TokIdx; }
4537 SourceLocation GetTokenLoc(unsigned tokI) {
4538 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4539 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004540 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004541 return Tokens[tokI].int_data[3] != 0;
4542 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004543 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004544 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4545 }
4546
4547 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004548 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4549 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004550
Ted Kremenek6db61092010-05-05 00:55:15 +00004551public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004552 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004553 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004554 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004555 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004556 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004557 AnnotateVis(tu,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00004558 AnnotateTokensVisitor, this, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004559 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4560 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004561
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004562 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004563 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004564 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004565 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004566 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004567 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004568
4569 /// \brief Determine whether the annotator saw any cursors that have
4570 /// context-sensitive keywords.
4571 bool hasContextSensitiveKeywords() const {
4572 return HasContextSensitiveKeywords;
4573 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004574};
4575}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004576
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004577void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4578 // Walk the AST within the region of interest, annotating tokens
4579 // along the way.
4580 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004581
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004582 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4583 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004584 if (Pos != Annotated.end() &&
4585 (clang_isInvalid(Cursors[I].kind) ||
4586 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004587 Cursors[I] = Pos->second;
4588 }
4589
4590 // Finish up annotating any tokens left.
4591 if (!MoreTokens())
4592 return;
4593
4594 const CXCursor &C = clang_getNullCursor();
4595 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4596 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4597 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004598 }
4599}
4600
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004601/// \brief It annotates and advances tokens with a cursor until the comparison
4602//// between the cursor location and the source range is the same as
4603/// \arg compResult.
4604///
4605/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4606/// Pass RangeOverlap to annotate tokens inside a range.
4607void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4608 RangeComparisonResult compResult,
4609 SourceRange range) {
4610 while (MoreTokens()) {
4611 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004612 if (isFunctionMacroToken(I))
4613 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004614
4615 SourceLocation TokLoc = GetTokenLoc(I);
4616 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4617 Cursors[I] = updateC;
4618 AdvanceToken();
4619 continue;
4620 }
4621 break;
4622 }
4623}
4624
4625/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004626void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4627 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004628 RangeComparisonResult compResult,
4629 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004630 assert(MoreTokens());
4631 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004632 "Should be called only for macro arg tokens");
4633
4634 // This works differently than annotateAndAdvanceTokens; because expanded
4635 // macro arguments can have arbitrary translation-unit source order, we do not
4636 // advance the token index one by one until a token fails the range test.
4637 // We only advance once past all of the macro arg tokens if all of them
4638 // pass the range test. If one of them fails we keep the token index pointing
4639 // at the start of the macro arg tokens so that the failing token will be
4640 // annotated by a subsequent annotation try.
4641
4642 bool atLeastOneCompFail = false;
4643
4644 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004645 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4646 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004647 if (TokLoc.isFileID())
4648 continue; // not macro arg token, it's parens or comma.
4649 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4650 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4651 Cursors[I] = updateC;
4652 } else
4653 atLeastOneCompFail = true;
4654 }
4655
4656 if (!atLeastOneCompFail)
4657 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4658}
4659
Ted Kremenek6db61092010-05-05 00:55:15 +00004660enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004661AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004662 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004663 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004664 if (cursorRange.isInvalid())
4665 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004666
4667 if (!HasContextSensitiveKeywords) {
4668 // Objective-C properties can have context-sensitive keywords.
4669 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4670 if (ObjCPropertyDecl *Property
4671 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4672 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4673 }
4674 // Objective-C methods can have context-sensitive keywords.
4675 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4676 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4677 if (ObjCMethodDecl *Method
4678 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4679 if (Method->getObjCDeclQualifier())
4680 HasContextSensitiveKeywords = true;
4681 else {
4682 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4683 PEnd = Method->param_end();
4684 P != PEnd; ++P) {
4685 if ((*P)->getObjCDeclQualifier()) {
4686 HasContextSensitiveKeywords = true;
4687 break;
4688 }
4689 }
4690 }
4691 }
4692 }
4693 // C++ methods can have context-sensitive keywords.
4694 else if (cursor.kind == CXCursor_CXXMethod) {
4695 if (CXXMethodDecl *Method
4696 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4697 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4698 HasContextSensitiveKeywords = true;
4699 }
4700 }
4701 // C++ classes can have context-sensitive keywords.
4702 else if (cursor.kind == CXCursor_StructDecl ||
4703 cursor.kind == CXCursor_ClassDecl ||
4704 cursor.kind == CXCursor_ClassTemplate ||
4705 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4706 if (Decl *D = getCursorDecl(cursor))
4707 if (D->hasAttr<FinalAttr>())
4708 HasContextSensitiveKeywords = true;
4709 }
4710 }
4711
Douglas Gregor4419b672010-10-21 06:10:04 +00004712 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004713 // For macro expansions, just note where the beginning of the macro
4714 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004715 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004716 Annotated[Loc.int_data] = cursor;
4717 return CXChildVisit_Recurse;
4718 }
4719
Douglas Gregor4419b672010-10-21 06:10:04 +00004720 // Items in the preprocessing record are kept separate from items in
4721 // declarations, so we keep a separate token index.
4722 unsigned SavedTokIdx = TokIdx;
4723 TokIdx = PreprocessingTokIdx;
4724
4725 // Skip tokens up until we catch up to the beginning of the preprocessing
4726 // entry.
4727 while (MoreTokens()) {
4728 const unsigned I = NextToken();
4729 SourceLocation TokLoc = GetTokenLoc(I);
4730 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4731 case RangeBefore:
4732 AdvanceToken();
4733 continue;
4734 case RangeAfter:
4735 case RangeOverlap:
4736 break;
4737 }
4738 break;
4739 }
4740
4741 // Look at all of the tokens within this range.
4742 while (MoreTokens()) {
4743 const unsigned I = NextToken();
4744 SourceLocation TokLoc = GetTokenLoc(I);
4745 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4746 case RangeBefore:
4747 assert(0 && "Infeasible");
4748 case RangeAfter:
4749 break;
4750 case RangeOverlap:
4751 Cursors[I] = cursor;
4752 AdvanceToken();
4753 continue;
4754 }
4755 break;
4756 }
4757
4758 // Save the preprocessing token index; restore the non-preprocessing
4759 // token index.
4760 PreprocessingTokIdx = TokIdx;
4761 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004762 return CXChildVisit_Recurse;
4763 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004764
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004765 if (cursorRange.isInvalid())
4766 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004767
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004768 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4769
Ted Kremeneka333c662010-05-12 05:29:33 +00004770 // Adjust the annotated range based specific declarations.
4771 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4772 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004773 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004774
4775 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004776 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004777 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4778 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4779 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4780 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4781 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004782 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004783
4784 if (StartLoc.isValid() && L.isValid() &&
4785 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4786 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004787 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004788
Ted Kremenek3f404602010-08-14 01:14:06 +00004789 // If the location of the cursor occurs within a macro instantiation, record
4790 // the spelling location of the cursor in our annotation map. We can then
4791 // paper over the token labelings during a post-processing step to try and
4792 // get cursor mappings for tokens that are the *arguments* of a macro
4793 // instantiation.
4794 if (L.isMacroID()) {
4795 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4796 // Only invalidate the old annotation if it isn't part of a preprocessing
4797 // directive. Here we assume that the default construction of CXCursor
4798 // results in CXCursor.kind being an initialized value (i.e., 0). If
4799 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004800
Ted Kremenek3f404602010-08-14 01:14:06 +00004801 CXCursor &oldC = Annotated[rawEncoding];
4802 if (!clang_isPreprocessing(oldC.kind))
4803 oldC = cursor;
4804 }
4805
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004806 const enum CXCursorKind K = clang_getCursorKind(parent);
4807 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004808 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4809 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004810
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004811 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004812
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004813 // Avoid having the cursor of an expression "overwrite" the annotation of the
4814 // variable declaration that it belongs to.
4815 // This can happen for C++ constructor expressions whose range generally
4816 // include the variable declaration, e.g.:
4817 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4818 if (clang_isExpression(cursorK)) {
4819 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004820 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004821 const unsigned I = NextToken();
4822 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4823 E->getLocStart() == D->getLocation() &&
4824 E->getLocStart() == GetTokenLoc(I)) {
4825 Cursors[I] = updateC;
4826 AdvanceToken();
4827 }
4828 }
4829 }
4830
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004831 // Visit children to get their cursor information.
4832 const unsigned BeforeChildren = NextToken();
4833 VisitChildren(cursor);
4834 const unsigned AfterChildren = NextToken();
4835
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004836 // Scan the tokens that are at the end of the cursor, but are not captured
4837 // but the child cursors.
4838 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004839
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004840 // Scan the tokens that are at the beginning of the cursor, but are not
4841 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004842 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4843 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4844 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004845
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004846 Cursors[I] = cursor;
4847 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004848
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004849 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004850}
4851
Ted Kremenek6db61092010-05-05 00:55:15 +00004852static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4853 CXCursor parent,
4854 CXClientData client_data) {
4855 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4856}
4857
Ted Kremenek6628a612011-03-18 22:51:30 +00004858namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004859
4860/// \brief Uses the macro expansions in the preprocessing record to find
4861/// and mark tokens that are macro arguments. This info is used by the
4862/// AnnotateTokensWorker.
4863class MarkMacroArgTokensVisitor {
4864 SourceManager &SM;
4865 CXToken *Tokens;
4866 unsigned NumTokens;
4867 unsigned CurIdx;
4868
4869public:
4870 MarkMacroArgTokensVisitor(SourceManager &SM,
4871 CXToken *tokens, unsigned numTokens)
4872 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4873
4874 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4875 if (cursor.kind != CXCursor_MacroExpansion)
4876 return CXChildVisit_Continue;
4877
4878 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4879 if (macroRange.getBegin() == macroRange.getEnd())
4880 return CXChildVisit_Continue; // it's not a function macro.
4881
4882 for (; CurIdx < NumTokens; ++CurIdx) {
4883 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4884 macroRange.getBegin()))
4885 break;
4886 }
4887
4888 if (CurIdx == NumTokens)
4889 return CXChildVisit_Break;
4890
4891 for (; CurIdx < NumTokens; ++CurIdx) {
4892 SourceLocation tokLoc = getTokenLoc(CurIdx);
4893 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4894 break;
4895
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004896 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004897 }
4898
4899 if (CurIdx == NumTokens)
4900 return CXChildVisit_Break;
4901
4902 return CXChildVisit_Continue;
4903 }
4904
4905private:
4906 SourceLocation getTokenLoc(unsigned tokI) {
4907 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4908 }
4909
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004910 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004911 // The third field is reserved and currently not used. Use it here
4912 // to mark macro arg expanded tokens with their expanded locations.
4913 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4914 }
4915};
4916
4917} // end anonymous namespace
4918
4919static CXChildVisitResult
4920MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4921 CXClientData client_data) {
4922 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4923 parent);
4924}
4925
4926namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004927 struct clang_annotateTokens_Data {
4928 CXTranslationUnit TU;
4929 ASTUnit *CXXUnit;
4930 CXToken *Tokens;
4931 unsigned NumTokens;
4932 CXCursor *Cursors;
4933 };
4934}
4935
Ted Kremenekab979612010-11-11 08:05:23 +00004936// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004937static void clang_annotateTokensImpl(void *UserData) {
4938 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4939 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4940 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4941 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4942 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4943
4944 // Determine the region of interest, which contains all of the tokens.
4945 SourceRange RegionOfInterest;
4946 RegionOfInterest.setBegin(
4947 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4948 RegionOfInterest.setEnd(
4949 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4950 Tokens[NumTokens-1])));
4951
4952 // A mapping from the source locations found when re-lexing or traversing the
4953 // region of interest to the corresponding cursors.
4954 AnnotateTokensData Annotated;
4955
4956 // Relex the tokens within the source range to look for preprocessing
4957 // directives.
4958 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4959 std::pair<FileID, unsigned> BeginLocInfo
4960 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4961 std::pair<FileID, unsigned> EndLocInfo
4962 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4963
Chris Lattner5f9e2722011-07-23 10:55:15 +00004964 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00004965 bool Invalid = false;
4966 if (BeginLocInfo.first == EndLocInfo.first &&
4967 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4968 !Invalid) {
4969 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4970 CXXUnit->getASTContext().getLangOptions(),
4971 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4972 Buffer.end());
4973 Lex.SetCommentRetentionState(true);
4974
4975 // Lex tokens in raw mode until we hit the end of the range, to avoid
4976 // entering #includes or expanding macros.
4977 while (true) {
4978 Token Tok;
4979 Lex.LexFromRawLexer(Tok);
4980
4981 reprocess:
4982 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4983 // We have found a preprocessing directive. Gobble it up so that we
4984 // don't see it while preprocessing these tokens later, but keep track
4985 // of all of the token locations inside this preprocessing directive so
4986 // that we can annotate them appropriately.
4987 //
4988 // FIXME: Some simple tests here could identify macro definitions and
4989 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004990 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00004991 do {
4992 Locations.push_back(Tok.getLocation());
4993 Lex.LexFromRawLexer(Tok);
4994 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4995
4996 using namespace cxcursor;
4997 CXCursor Cursor
4998 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4999 Locations.back()),
5000 TU);
5001 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5002 Annotated[Locations[I].getRawEncoding()] = Cursor;
5003 }
5004
5005 if (Tok.isAtStartOfLine())
5006 goto reprocess;
5007
5008 continue;
5009 }
5010
5011 if (Tok.is(tok::eof))
5012 break;
5013 }
5014 }
5015
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005016 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5017 // Search and mark tokens that are macro argument expansions.
5018 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5019 Tokens, NumTokens);
5020 CursorVisitor MacroArgMarker(TU,
5021 MarkMacroArgTokensVisitorDelegate, &Visitor,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00005022 true, RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005023 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5024 }
5025
Ted Kremenek6628a612011-03-18 22:51:30 +00005026 // Annotate all of the source locations in the region of interest that map to
5027 // a specific cursor.
5028 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5029 TU, RegionOfInterest);
5030
5031 // FIXME: We use a ridiculous stack size here because the data-recursion
5032 // algorithm uses a large stack frame than the non-data recursive version,
5033 // and AnnotationTokensWorker currently transforms the data-recursion
5034 // algorithm back into a traditional recursion by explicitly calling
5035 // VisitChildren(). We will need to remove this explicit recursive call.
5036 W.AnnotateTokens();
5037
5038 // If we ran into any entities that involve context-sensitive keywords,
5039 // take another pass through the tokens to mark them as such.
5040 if (W.hasContextSensitiveKeywords()) {
5041 for (unsigned I = 0; I != NumTokens; ++I) {
5042 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5043 continue;
5044
5045 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5046 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5047 if (ObjCPropertyDecl *Property
5048 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5049 if (Property->getPropertyAttributesAsWritten() != 0 &&
5050 llvm::StringSwitch<bool>(II->getName())
5051 .Case("readonly", true)
5052 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005053 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005054 .Case("readwrite", true)
5055 .Case("retain", true)
5056 .Case("copy", true)
5057 .Case("nonatomic", true)
5058 .Case("atomic", true)
5059 .Case("getter", true)
5060 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005061 .Case("strong", true)
5062 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005063 .Default(false))
5064 Tokens[I].int_data[0] = CXToken_Keyword;
5065 }
5066 continue;
5067 }
5068
5069 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5070 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5071 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5072 if (llvm::StringSwitch<bool>(II->getName())
5073 .Case("in", true)
5074 .Case("out", true)
5075 .Case("inout", true)
5076 .Case("oneway", true)
5077 .Case("bycopy", true)
5078 .Case("byref", true)
5079 .Default(false))
5080 Tokens[I].int_data[0] = CXToken_Keyword;
5081 continue;
5082 }
5083
5084 if (Cursors[I].kind == CXCursor_CXXMethod) {
5085 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5086 if (CXXMethodDecl *Method
5087 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
5088 if ((Method->hasAttr<FinalAttr>() ||
5089 Method->hasAttr<OverrideAttr>()) &&
5090 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
5091 llvm::StringSwitch<bool>(II->getName())
5092 .Case("final", true)
5093 .Case("override", true)
5094 .Default(false))
5095 Tokens[I].int_data[0] = CXToken_Keyword;
5096 }
5097 continue;
5098 }
5099
5100 if (Cursors[I].kind == CXCursor_ClassDecl ||
5101 Cursors[I].kind == CXCursor_StructDecl ||
5102 Cursors[I].kind == CXCursor_ClassTemplate) {
5103 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5104 if (II->getName() == "final") {
5105 // We have to be careful with 'final', since it could be the name
5106 // of a member class rather than the context-sensitive keyword.
5107 // So, check whether the cursor associated with this
5108 Decl *D = getCursorDecl(Cursors[I]);
5109 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
5110 if ((Record->hasAttr<FinalAttr>()) &&
5111 Record->getIdentifier() != II)
5112 Tokens[I].int_data[0] = CXToken_Keyword;
5113 } else if (ClassTemplateDecl *ClassTemplate
5114 = dyn_cast_or_null<ClassTemplateDecl>(D)) {
5115 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
5116 if ((Record->hasAttr<FinalAttr>()) &&
5117 Record->getIdentifier() != II)
5118 Tokens[I].int_data[0] = CXToken_Keyword;
5119 }
5120 }
5121 continue;
5122 }
5123 }
5124 }
Ted Kremenekab979612010-11-11 08:05:23 +00005125}
5126
Ted Kremenek6db61092010-05-05 00:55:15 +00005127extern "C" {
5128
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005129void clang_annotateTokens(CXTranslationUnit TU,
5130 CXToken *Tokens, unsigned NumTokens,
5131 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005132
5133 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005134 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005135
Douglas Gregor4419b672010-10-21 06:10:04 +00005136 // Any token we don't specifically annotate will have a NULL cursor.
5137 CXCursor C = clang_getNullCursor();
5138 for (unsigned I = 0; I != NumTokens; ++I)
5139 Cursors[I] = C;
5140
Ted Kremeneka60ed472010-11-16 08:15:36 +00005141 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005142 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005143 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005144
Douglas Gregorbdf60622010-03-05 21:16:25 +00005145 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005146
5147 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005148 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005149 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005150 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005151 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5152 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005153}
Ted Kremenek6628a612011-03-18 22:51:30 +00005154
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005155} // end: extern "C"
5156
5157//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005158// Operations for querying linkage of a cursor.
5159//===----------------------------------------------------------------------===//
5160
5161extern "C" {
5162CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005163 if (!clang_isDeclaration(cursor.kind))
5164 return CXLinkage_Invalid;
5165
Ted Kremenek16b42592010-03-03 06:36:57 +00005166 Decl *D = cxcursor::getCursorDecl(cursor);
5167 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5168 switch (ND->getLinkage()) {
5169 case NoLinkage: return CXLinkage_NoLinkage;
5170 case InternalLinkage: return CXLinkage_Internal;
5171 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5172 case ExternalLinkage: return CXLinkage_External;
5173 };
5174
5175 return CXLinkage_Invalid;
5176}
5177} // end: extern "C"
5178
5179//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005180// Operations for querying language of a cursor.
5181//===----------------------------------------------------------------------===//
5182
5183static CXLanguageKind getDeclLanguage(const Decl *D) {
5184 switch (D->getKind()) {
5185 default:
5186 break;
5187 case Decl::ImplicitParam:
5188 case Decl::ObjCAtDefsField:
5189 case Decl::ObjCCategory:
5190 case Decl::ObjCCategoryImpl:
5191 case Decl::ObjCClass:
5192 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005193 case Decl::ObjCForwardProtocol:
5194 case Decl::ObjCImplementation:
5195 case Decl::ObjCInterface:
5196 case Decl::ObjCIvar:
5197 case Decl::ObjCMethod:
5198 case Decl::ObjCProperty:
5199 case Decl::ObjCPropertyImpl:
5200 case Decl::ObjCProtocol:
5201 return CXLanguage_ObjC;
5202 case Decl::CXXConstructor:
5203 case Decl::CXXConversion:
5204 case Decl::CXXDestructor:
5205 case Decl::CXXMethod:
5206 case Decl::CXXRecord:
5207 case Decl::ClassTemplate:
5208 case Decl::ClassTemplatePartialSpecialization:
5209 case Decl::ClassTemplateSpecialization:
5210 case Decl::Friend:
5211 case Decl::FriendTemplate:
5212 case Decl::FunctionTemplate:
5213 case Decl::LinkageSpec:
5214 case Decl::Namespace:
5215 case Decl::NamespaceAlias:
5216 case Decl::NonTypeTemplateParm:
5217 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005218 case Decl::TemplateTemplateParm:
5219 case Decl::TemplateTypeParm:
5220 case Decl::UnresolvedUsingTypename:
5221 case Decl::UnresolvedUsingValue:
5222 case Decl::Using:
5223 case Decl::UsingDirective:
5224 case Decl::UsingShadow:
5225 return CXLanguage_CPlusPlus;
5226 }
5227
5228 return CXLanguage_C;
5229}
5230
5231extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005232
5233enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5234 if (clang_isDeclaration(cursor.kind))
5235 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005236 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005237 return CXAvailability_Available;
5238
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005239 switch (D->getAvailability()) {
5240 case AR_Available:
5241 case AR_NotYetIntroduced:
5242 return CXAvailability_Available;
5243
5244 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005245 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005246
5247 case AR_Unavailable:
5248 return CXAvailability_NotAvailable;
5249 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005250 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005251
Douglas Gregor58ddb602010-08-23 23:00:57 +00005252 return CXAvailability_Available;
5253}
5254
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005255CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5256 if (clang_isDeclaration(cursor.kind))
5257 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5258
5259 return CXLanguage_Invalid;
5260}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005261
5262 /// \brief If the given cursor is the "templated" declaration
5263 /// descibing a class or function template, return the class or
5264 /// function template.
5265static Decl *maybeGetTemplateCursor(Decl *D) {
5266 if (!D)
5267 return 0;
5268
5269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5270 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5271 return FunTmpl;
5272
5273 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5274 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5275 return ClassTmpl;
5276
5277 return D;
5278}
5279
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005280CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5281 if (clang_isDeclaration(cursor.kind)) {
5282 if (Decl *D = getCursorDecl(cursor)) {
5283 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005284 if (!DC)
5285 return clang_getNullCursor();
5286
5287 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5288 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005289 }
5290 }
5291
5292 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5293 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005294 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005295 }
5296
5297 return clang_getNullCursor();
5298}
5299
5300CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5301 if (clang_isDeclaration(cursor.kind)) {
5302 if (Decl *D = getCursorDecl(cursor)) {
5303 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005304 if (!DC)
5305 return clang_getNullCursor();
5306
5307 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5308 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005309 }
5310 }
5311
5312 // FIXME: Note that we can't easily compute the lexical context of a
5313 // statement or expression, so we return nothing.
5314 return clang_getNullCursor();
5315}
5316
Douglas Gregor9f592342010-10-01 20:25:15 +00005317static void CollectOverriddenMethods(DeclContext *Ctx,
5318 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005319 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005320 if (!Ctx)
5321 return;
5322
5323 // If we have a class or category implementation, jump straight to the
5324 // interface.
5325 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5326 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5327
5328 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5329 if (!Container)
5330 return;
5331
5332 // Check whether we have a matching method at this level.
5333 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5334 Method->isInstanceMethod()))
5335 if (Method != Overridden) {
5336 // We found an override at this level; there is no need to look
5337 // into other protocols or categories.
5338 Methods.push_back(Overridden);
5339 return;
5340 }
5341
5342 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5343 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5344 PEnd = Protocol->protocol_end();
5345 P != PEnd; ++P)
5346 CollectOverriddenMethods(*P, Method, Methods);
5347 }
5348
5349 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5350 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5351 PEnd = Category->protocol_end();
5352 P != PEnd; ++P)
5353 CollectOverriddenMethods(*P, Method, Methods);
5354 }
5355
5356 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5357 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5358 PEnd = Interface->protocol_end();
5359 P != PEnd; ++P)
5360 CollectOverriddenMethods(*P, Method, Methods);
5361
5362 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5363 Category; Category = Category->getNextClassCategory())
5364 CollectOverriddenMethods(Category, Method, Methods);
5365
5366 // We only look into the superclass if we haven't found anything yet.
5367 if (Methods.empty())
5368 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5369 return CollectOverriddenMethods(Super, Method, Methods);
5370 }
5371}
5372
5373void clang_getOverriddenCursors(CXCursor cursor,
5374 CXCursor **overridden,
5375 unsigned *num_overridden) {
5376 if (overridden)
5377 *overridden = 0;
5378 if (num_overridden)
5379 *num_overridden = 0;
5380 if (!overridden || !num_overridden)
5381 return;
5382
5383 if (!clang_isDeclaration(cursor.kind))
5384 return;
5385
5386 Decl *D = getCursorDecl(cursor);
5387 if (!D)
5388 return;
5389
5390 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005391 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005392 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5393 *num_overridden = CXXMethod->size_overridden_methods();
5394 if (!*num_overridden)
5395 return;
5396
5397 *overridden = new CXCursor [*num_overridden];
5398 unsigned I = 0;
5399 for (CXXMethodDecl::method_iterator
5400 M = CXXMethod->begin_overridden_methods(),
5401 MEnd = CXXMethod->end_overridden_methods();
5402 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005403 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005404 return;
5405 }
5406
5407 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5408 if (!Method)
5409 return;
5410
5411 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005412 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005413 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5414
5415 if (Methods.empty())
5416 return;
5417
5418 *num_overridden = Methods.size();
5419 *overridden = new CXCursor [Methods.size()];
5420 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005421 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005422}
5423
5424void clang_disposeOverriddenCursors(CXCursor *overridden) {
5425 delete [] overridden;
5426}
5427
Douglas Gregorecdcb882010-10-20 22:00:55 +00005428CXFile clang_getIncludedFile(CXCursor cursor) {
5429 if (cursor.kind != CXCursor_InclusionDirective)
5430 return 0;
5431
5432 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5433 return (void *)ID->getFile();
5434}
5435
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005436} // end: extern "C"
5437
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005438
5439//===----------------------------------------------------------------------===//
5440// C++ AST instrospection.
5441//===----------------------------------------------------------------------===//
5442
5443extern "C" {
5444unsigned clang_CXXMethod_isStatic(CXCursor C) {
5445 if (!clang_isDeclaration(C.kind))
5446 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005447
5448 CXXMethodDecl *Method = 0;
5449 Decl *D = cxcursor::getCursorDecl(C);
5450 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5451 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5452 else
5453 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5454 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005455}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005456
Douglas Gregor211924b2011-05-12 15:17:24 +00005457unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5458 if (!clang_isDeclaration(C.kind))
5459 return 0;
5460
5461 CXXMethodDecl *Method = 0;
5462 Decl *D = cxcursor::getCursorDecl(C);
5463 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5464 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5465 else
5466 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5467 return (Method && Method->isVirtual()) ? 1 : 0;
5468}
5469
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005470} // end: extern "C"
5471
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005472//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005473// Attribute introspection.
5474//===----------------------------------------------------------------------===//
5475
5476extern "C" {
5477CXType clang_getIBOutletCollectionType(CXCursor C) {
5478 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005479 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005480
5481 IBOutletCollectionAttr *A =
5482 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5483
Douglas Gregor841b2382011-03-06 18:55:32 +00005484 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005485}
5486} // end: extern "C"
5487
5488//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005489// Inspecting memory usage.
5490//===----------------------------------------------------------------------===//
5491
Ted Kremenekf7870022011-04-20 16:41:07 +00005492typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005493
Ted Kremenekf7870022011-04-20 16:41:07 +00005494static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5495 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005496 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005497 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005498 entries.push_back(entry);
5499}
5500
5501extern "C" {
5502
Ted Kremenekf7870022011-04-20 16:41:07 +00005503const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005504 const char *str = "";
5505 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005506 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005507 str = "ASTContext: expressions, declarations, and types";
5508 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005509 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005510 str = "ASTContext: identifiers";
5511 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005512 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005513 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005514 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005515 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005516 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005517 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005518 case CXTUResourceUsage_SourceManagerContentCache:
5519 str = "SourceManager: content cache allocator";
5520 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005521 case CXTUResourceUsage_AST_SideTables:
5522 str = "ASTContext: side tables";
5523 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005524 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5525 str = "SourceManager: malloc'ed memory buffers";
5526 break;
5527 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5528 str = "SourceManager: mmap'ed memory buffers";
5529 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005530 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5531 str = "ExternalASTSource: malloc'ed memory buffers";
5532 break;
5533 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5534 str = "ExternalASTSource: mmap'ed memory buffers";
5535 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005536 case CXTUResourceUsage_Preprocessor:
5537 str = "Preprocessor: malloc'ed memory";
5538 break;
5539 case CXTUResourceUsage_PreprocessingRecord:
5540 str = "Preprocessor: PreprocessingRecord";
5541 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005542 case CXTUResourceUsage_SourceManager_DataStructures:
5543 str = "SourceManager: data structures and tables";
5544 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005545 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5546 str = "Preprocessor: header search tables";
5547 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005548 }
5549 return str;
5550}
5551
Ted Kremenekf7870022011-04-20 16:41:07 +00005552CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005553 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005554 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005555 return usage;
5556 }
5557
5558 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5559 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5560 ASTContext &astContext = astUnit->getASTContext();
5561
5562 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005563 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005564 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005565
5566 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005567 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005568 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5569
5570 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005571 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005572 (unsigned long) astContext.Selectors.getTotalMemory());
5573
Ted Kremenekba29bd22011-04-28 04:53:38 +00005574 // How much memory is used by ASTContext's side tables?
5575 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5576 (unsigned long) astContext.getSideTableAllocatedMemory());
5577
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005578 // How much memory is used for caching global code completion results?
5579 unsigned long completionBytes = 0;
5580 if (GlobalCodeCompletionAllocator *completionAllocator =
5581 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005582 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005583 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005584 createCXTUResourceUsageEntry(*entries,
5585 CXTUResourceUsage_GlobalCompletionResults,
5586 completionBytes);
5587
5588 // How much memory is being used by SourceManager's content cache?
5589 createCXTUResourceUsageEntry(*entries,
5590 CXTUResourceUsage_SourceManagerContentCache,
5591 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005592
5593 // How much memory is being used by the MemoryBuffer's in SourceManager?
5594 const SourceManager::MemoryBufferSizes &srcBufs =
5595 astUnit->getSourceManager().getMemoryBufferSizes();
5596
5597 createCXTUResourceUsageEntry(*entries,
5598 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5599 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005600 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005601 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5602 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005603 createCXTUResourceUsageEntry(*entries,
5604 CXTUResourceUsage_SourceManager_DataStructures,
5605 (unsigned long) astContext.getSourceManager()
5606 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005607
5608 // How much memory is being used by the ExternalASTSource?
5609 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5610 const ExternalASTSource::MemoryBufferSizes &sizes =
5611 esrc->getMemoryBufferSizes();
5612
5613 createCXTUResourceUsageEntry(*entries,
5614 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5615 (unsigned long) sizes.malloc_bytes);
5616 createCXTUResourceUsageEntry(*entries,
5617 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5618 (unsigned long) sizes.mmap_bytes);
5619 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005620
5621 // How much memory is being used by the Preprocessor?
5622 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005623 createCXTUResourceUsageEntry(*entries,
5624 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005625 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005626
5627 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5628 createCXTUResourceUsageEntry(*entries,
5629 CXTUResourceUsage_PreprocessingRecord,
5630 pRec->getTotalMemory());
5631 }
5632
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005633 createCXTUResourceUsageEntry(*entries,
5634 CXTUResourceUsage_Preprocessor_HeaderSearch,
5635 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005636
Ted Kremenekf7870022011-04-20 16:41:07 +00005637 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005638 (unsigned) entries->size(),
5639 entries->size() ? &(*entries)[0] : 0 };
5640 entries.take();
5641 return usage;
5642}
5643
Ted Kremenekf7870022011-04-20 16:41:07 +00005644void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005645 if (usage.data)
5646 delete (MemUsageEntries*) usage.data;
5647}
5648
5649} // end extern "C"
5650
Douglas Gregor6df78732011-05-05 20:27:22 +00005651void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5652 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5653 for (unsigned I = 0; I != Usage.numEntries; ++I)
5654 fprintf(stderr, " %s: %lu\n",
5655 clang_getTUResourceUsageName(Usage.entries[I].kind),
5656 Usage.entries[I].amount);
5657
5658 clang_disposeCXTUResourceUsage(Usage);
5659}
5660
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005661//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005662// Misc. utility functions.
5663//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005664
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005665/// Default to using an 8 MB stack size on "safety" threads.
5666static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005667
5668namespace clang {
5669
5670bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005671 void (*Fn)(void*), void *UserData,
5672 unsigned Size) {
5673 if (!Size)
5674 Size = GetSafetyThreadStackSize();
5675 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005676 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5677 return CRC.RunSafely(Fn, UserData);
5678}
5679
5680unsigned GetSafetyThreadStackSize() {
5681 return SafetyStackThreadSize;
5682}
5683
5684void SetSafetyThreadStackSize(unsigned Value) {
5685 SafetyStackThreadSize = Value;
5686}
5687
5688}
5689
Ted Kremenek04bb7162010-01-22 22:44:15 +00005690extern "C" {
5691
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005692CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005693 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005694}
5695
5696} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005697