blob: 40b21940afe0492ae9102d7e0ddb27a51d202dd1 [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) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002966 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002967 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) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00003002 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3003 return getLocationFromExpr(CE->getSubExpr());
3004
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003005 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3006 return /*FIXME:*/Msg->getLeftLoc();
3007 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3008 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003009 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3010 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003011 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3012 return Member->getMemberLoc();
3013 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3014 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003015 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3016 return SizeOfPack->getPackLoc();
3017
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003018 return E->getLocStart();
3019}
3020
Ted Kremenekfb480492010-01-13 21:46:36 +00003021extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003022
3023unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003024 CXCursorVisitor visitor,
3025 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003026 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003027 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003028 return CursorVis.VisitChildren(parent);
3029}
3030
David Chisnall3387c652010-11-03 14:12:26 +00003031#ifndef __has_feature
3032#define __has_feature(x) 0
3033#endif
3034#if __has_feature(blocks)
3035typedef enum CXChildVisitResult
3036 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3037
3038static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3039 CXClientData client_data) {
3040 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3041 return block(cursor, parent);
3042}
3043#else
3044// If we are compiled with a compiler that doesn't have native blocks support,
3045// define and call the block manually, so the
3046typedef struct _CXChildVisitResult
3047{
3048 void *isa;
3049 int flags;
3050 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003051 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3052 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003053} *CXCursorVisitorBlock;
3054
3055static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3056 CXClientData client_data) {
3057 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3058 return block->invoke(block, cursor, parent);
3059}
3060#endif
3061
3062
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003063unsigned clang_visitChildrenWithBlock(CXCursor parent,
3064 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003065 return clang_visitChildren(parent, visitWithBlock, block);
3066}
3067
Douglas Gregor78205d42010-01-20 21:45:58 +00003068static CXString getDeclSpelling(Decl *D) {
3069 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003070 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003071 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003072 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3073 return createCXString(Property->getIdentifier()->getName());
3074
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003075 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003076 }
3077
Douglas Gregor78205d42010-01-20 21:45:58 +00003078 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003079 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003080
Douglas Gregor78205d42010-01-20 21:45:58 +00003081 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3082 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3083 // and returns different names. NamedDecl returns the class name and
3084 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003085 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003086
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003087 if (isa<UsingDirectiveDecl>(D))
3088 return createCXString("");
3089
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003090 llvm::SmallString<1024> S;
3091 llvm::raw_svector_ostream os(S);
3092 ND->printName(os);
3093
3094 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003095}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003096
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003097CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003098 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003099 return clang_getTranslationUnitSpelling(
3100 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003101
Steve Narofff334b4e2009-09-02 18:26:48 +00003102 if (clang_isReference(C.kind)) {
3103 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003104 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003105 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003106 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003107 }
3108 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003109 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003110 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003111 }
3112 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003113 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003114 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003115 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003116 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003117 case CXCursor_CXXBaseSpecifier: {
3118 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3119 return createCXString(B->getType().getAsString());
3120 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003121 case CXCursor_TypeRef: {
3122 TypeDecl *Type = getCursorTypeRef(C).first;
3123 assert(Type && "Missing type decl");
3124
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003125 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3126 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003127 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003128 case CXCursor_TemplateRef: {
3129 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003130 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003131
3132 return createCXString(Template->getNameAsString());
3133 }
Douglas Gregor69319002010-08-31 23:48:11 +00003134
3135 case CXCursor_NamespaceRef: {
3136 NamedDecl *NS = getCursorNamespaceRef(C).first;
3137 assert(NS && "Missing namespace decl");
3138
3139 return createCXString(NS->getNameAsString());
3140 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003141
Douglas Gregora67e03f2010-09-09 21:42:20 +00003142 case CXCursor_MemberRef: {
3143 FieldDecl *Field = getCursorMemberRef(C).first;
3144 assert(Field && "Missing member decl");
3145
3146 return createCXString(Field->getNameAsString());
3147 }
3148
Douglas Gregor36897b02010-09-10 00:22:18 +00003149 case CXCursor_LabelRef: {
3150 LabelStmt *Label = getCursorLabelRef(C).first;
3151 assert(Label && "Missing label");
3152
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003153 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003154 }
3155
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003156 case CXCursor_OverloadedDeclRef: {
3157 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3158 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3159 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3160 return createCXString(ND->getNameAsString());
3161 return createCXString("");
3162 }
3163 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3164 return createCXString(E->getName().getAsString());
3165 OverloadedTemplateStorage *Ovl
3166 = Storage.get<OverloadedTemplateStorage*>();
3167 if (Ovl->size() == 0)
3168 return createCXString("");
3169 return createCXString((*Ovl->begin())->getNameAsString());
3170 }
3171
Daniel Dunbaracca7252009-11-30 20:42:49 +00003172 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003173 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003174 }
3175 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003176
3177 if (clang_isExpression(C.kind)) {
3178 Decl *D = getDeclFromExpr(getCursorExpr(C));
3179 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003180 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003181 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003182 }
3183
Douglas Gregor36897b02010-09-10 00:22:18 +00003184 if (clang_isStatement(C.kind)) {
3185 Stmt *S = getCursorStmt(C);
3186 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003187 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003188
3189 return createCXString("");
3190 }
3191
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003192 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003193 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003194 ->getNameStart());
3195
Douglas Gregor572feb22010-03-18 18:04:21 +00003196 if (C.kind == CXCursor_MacroDefinition)
3197 return createCXString(getCursorMacroDefinition(C)->getName()
3198 ->getNameStart());
3199
Douglas Gregorecdcb882010-10-20 22:00:55 +00003200 if (C.kind == CXCursor_InclusionDirective)
3201 return createCXString(getCursorInclusionDirective(C)->getFileName());
3202
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003203 if (clang_isDeclaration(C.kind))
3204 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003205
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003206 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003207}
3208
Douglas Gregor358559d2010-10-02 22:49:11 +00003209CXString clang_getCursorDisplayName(CXCursor C) {
3210 if (!clang_isDeclaration(C.kind))
3211 return clang_getCursorSpelling(C);
3212
3213 Decl *D = getCursorDecl(C);
3214 if (!D)
3215 return createCXString("");
3216
3217 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3218 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3219 D = FunTmpl->getTemplatedDecl();
3220
3221 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3222 llvm::SmallString<64> Str;
3223 llvm::raw_svector_ostream OS(Str);
3224 OS << Function->getNameAsString();
3225 if (Function->getPrimaryTemplate())
3226 OS << "<>";
3227 OS << "(";
3228 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3229 if (I)
3230 OS << ", ";
3231 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3232 }
3233
3234 if (Function->isVariadic()) {
3235 if (Function->getNumParams())
3236 OS << ", ";
3237 OS << "...";
3238 }
3239 OS << ")";
3240 return createCXString(OS.str());
3241 }
3242
3243 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3244 llvm::SmallString<64> Str;
3245 llvm::raw_svector_ostream OS(Str);
3246 OS << ClassTemplate->getNameAsString();
3247 OS << "<";
3248 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3249 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3250 if (I)
3251 OS << ", ";
3252
3253 NamedDecl *Param = Params->getParam(I);
3254 if (Param->getIdentifier()) {
3255 OS << Param->getIdentifier()->getName();
3256 continue;
3257 }
3258
3259 // There is no parameter name, which makes this tricky. Try to come up
3260 // with something useful that isn't too long.
3261 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3262 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3263 else if (NonTypeTemplateParmDecl *NTTP
3264 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3265 OS << NTTP->getType().getAsString(Policy);
3266 else
3267 OS << "template<...> class";
3268 }
3269
3270 OS << ">";
3271 return createCXString(OS.str());
3272 }
3273
3274 if (ClassTemplateSpecializationDecl *ClassSpec
3275 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3276 // If the type was explicitly written, use that.
3277 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3278 return createCXString(TSInfo->getType().getAsString(Policy));
3279
3280 llvm::SmallString<64> Str;
3281 llvm::raw_svector_ostream OS(Str);
3282 OS << ClassSpec->getNameAsString();
3283 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003284 ClassSpec->getTemplateArgs().data(),
3285 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003286 Policy);
3287 return createCXString(OS.str());
3288 }
3289
3290 return clang_getCursorSpelling(C);
3291}
3292
Ted Kremeneke68fff62010-02-17 00:41:32 +00003293CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003294 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003295 case CXCursor_FunctionDecl:
3296 return createCXString("FunctionDecl");
3297 case CXCursor_TypedefDecl:
3298 return createCXString("TypedefDecl");
3299 case CXCursor_EnumDecl:
3300 return createCXString("EnumDecl");
3301 case CXCursor_EnumConstantDecl:
3302 return createCXString("EnumConstantDecl");
3303 case CXCursor_StructDecl:
3304 return createCXString("StructDecl");
3305 case CXCursor_UnionDecl:
3306 return createCXString("UnionDecl");
3307 case CXCursor_ClassDecl:
3308 return createCXString("ClassDecl");
3309 case CXCursor_FieldDecl:
3310 return createCXString("FieldDecl");
3311 case CXCursor_VarDecl:
3312 return createCXString("VarDecl");
3313 case CXCursor_ParmDecl:
3314 return createCXString("ParmDecl");
3315 case CXCursor_ObjCInterfaceDecl:
3316 return createCXString("ObjCInterfaceDecl");
3317 case CXCursor_ObjCCategoryDecl:
3318 return createCXString("ObjCCategoryDecl");
3319 case CXCursor_ObjCProtocolDecl:
3320 return createCXString("ObjCProtocolDecl");
3321 case CXCursor_ObjCPropertyDecl:
3322 return createCXString("ObjCPropertyDecl");
3323 case CXCursor_ObjCIvarDecl:
3324 return createCXString("ObjCIvarDecl");
3325 case CXCursor_ObjCInstanceMethodDecl:
3326 return createCXString("ObjCInstanceMethodDecl");
3327 case CXCursor_ObjCClassMethodDecl:
3328 return createCXString("ObjCClassMethodDecl");
3329 case CXCursor_ObjCImplementationDecl:
3330 return createCXString("ObjCImplementationDecl");
3331 case CXCursor_ObjCCategoryImplDecl:
3332 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003333 case CXCursor_CXXMethod:
3334 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003335 case CXCursor_UnexposedDecl:
3336 return createCXString("UnexposedDecl");
3337 case CXCursor_ObjCSuperClassRef:
3338 return createCXString("ObjCSuperClassRef");
3339 case CXCursor_ObjCProtocolRef:
3340 return createCXString("ObjCProtocolRef");
3341 case CXCursor_ObjCClassRef:
3342 return createCXString("ObjCClassRef");
3343 case CXCursor_TypeRef:
3344 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003345 case CXCursor_TemplateRef:
3346 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003347 case CXCursor_NamespaceRef:
3348 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003349 case CXCursor_MemberRef:
3350 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003351 case CXCursor_LabelRef:
3352 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003353 case CXCursor_OverloadedDeclRef:
3354 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003355 case CXCursor_UnexposedExpr:
3356 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003357 case CXCursor_BlockExpr:
3358 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003359 case CXCursor_DeclRefExpr:
3360 return createCXString("DeclRefExpr");
3361 case CXCursor_MemberRefExpr:
3362 return createCXString("MemberRefExpr");
3363 case CXCursor_CallExpr:
3364 return createCXString("CallExpr");
3365 case CXCursor_ObjCMessageExpr:
3366 return createCXString("ObjCMessageExpr");
3367 case CXCursor_UnexposedStmt:
3368 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003369 case CXCursor_LabelStmt:
3370 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003371 case CXCursor_InvalidFile:
3372 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003373 case CXCursor_InvalidCode:
3374 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003375 case CXCursor_NoDeclFound:
3376 return createCXString("NoDeclFound");
3377 case CXCursor_NotImplemented:
3378 return createCXString("NotImplemented");
3379 case CXCursor_TranslationUnit:
3380 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003381 case CXCursor_UnexposedAttr:
3382 return createCXString("UnexposedAttr");
3383 case CXCursor_IBActionAttr:
3384 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003385 case CXCursor_IBOutletAttr:
3386 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003387 case CXCursor_IBOutletCollectionAttr:
3388 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003389 case CXCursor_CXXFinalAttr:
3390 return createCXString("attribute(final)");
3391 case CXCursor_CXXOverrideAttr:
3392 return createCXString("attribute(override)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003393 case CXCursor_PreprocessingDirective:
3394 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003395 case CXCursor_MacroDefinition:
3396 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003397 case CXCursor_MacroExpansion:
3398 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003399 case CXCursor_InclusionDirective:
3400 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003401 case CXCursor_Namespace:
3402 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003403 case CXCursor_LinkageSpec:
3404 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003405 case CXCursor_CXXBaseSpecifier:
3406 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003407 case CXCursor_Constructor:
3408 return createCXString("CXXConstructor");
3409 case CXCursor_Destructor:
3410 return createCXString("CXXDestructor");
3411 case CXCursor_ConversionFunction:
3412 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003413 case CXCursor_TemplateTypeParameter:
3414 return createCXString("TemplateTypeParameter");
3415 case CXCursor_NonTypeTemplateParameter:
3416 return createCXString("NonTypeTemplateParameter");
3417 case CXCursor_TemplateTemplateParameter:
3418 return createCXString("TemplateTemplateParameter");
3419 case CXCursor_FunctionTemplate:
3420 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003421 case CXCursor_ClassTemplate:
3422 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003423 case CXCursor_ClassTemplatePartialSpecialization:
3424 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003425 case CXCursor_NamespaceAlias:
3426 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003427 case CXCursor_UsingDirective:
3428 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003429 case CXCursor_UsingDeclaration:
3430 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003431 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003432 return createCXString("TypeAliasDecl");
3433 case CXCursor_ObjCSynthesizeDecl:
3434 return createCXString("ObjCSynthesizeDecl");
3435 case CXCursor_ObjCDynamicDecl:
3436 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003437 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003438
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003439 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003440 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003441}
Steve Naroff89922f82009-08-31 00:59:03 +00003442
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003443struct GetCursorData {
3444 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003445 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003446 CXCursor &BestCursor;
3447
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003448 GetCursorData(SourceManager &SM,
3449 SourceLocation tokenBegin, CXCursor &outputCursor)
3450 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3451 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3452 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003453};
3454
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003455static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3456 CXCursor parent,
3457 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003458 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3459 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003460
3461 // If we point inside a macro argument we should provide info of what the
3462 // token is so use the actual cursor, don't replace it with a macro expansion
3463 // cursor.
3464 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3465 return CXChildVisit_Recurse;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003466
3467 if (clang_isExpression(cursor.kind) &&
3468 clang_isDeclaration(BestCursor->kind)) {
3469 Decl *D = getCursorDecl(*BestCursor);
3470
3471 // Avoid having the cursor of an expression replace the declaration cursor
3472 // when the expression source range overlaps the declaration range.
3473 // This can happen for C++ constructor expressions whose range generally
3474 // include the variable declaration, e.g.:
3475 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3476 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3477 D->getLocation() == Data->TokenBeginLoc)
3478 return CXChildVisit_Break;
3479 }
3480
Douglas Gregor93798e22010-11-05 21:11:19 +00003481 // If our current best cursor is the construction of a temporary object,
3482 // don't replace that cursor with a type reference, because we want
3483 // clang_getCursor() to point at the constructor.
3484 if (clang_isExpression(BestCursor->kind) &&
3485 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3486 cursor.kind == CXCursor_TypeRef)
3487 return CXChildVisit_Recurse;
3488
Douglas Gregor85fe1562010-12-10 07:23:11 +00003489 // Don't override a preprocessing cursor with another preprocessing
3490 // cursor; we want the outermost preprocessing cursor.
3491 if (clang_isPreprocessing(cursor.kind) &&
3492 clang_isPreprocessing(BestCursor->kind))
3493 return CXChildVisit_Recurse;
3494
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003495 *BestCursor = cursor;
3496 return CXChildVisit_Recurse;
3497}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003498
Douglas Gregorb9790342010-01-22 21:44:22 +00003499CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3500 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003501 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003502
Ted Kremeneka60ed472010-11-16 08:15:36 +00003503 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003504 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3505
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003506 // Translate the given source location to make it point at the beginning of
3507 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003508 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003509
3510 // Guard against an invalid SourceLocation, or we may assert in one
3511 // of the following calls.
3512 if (SLoc.isInvalid())
3513 return clang_getNullCursor();
3514
Douglas Gregor40749ee2010-11-03 00:35:38 +00003515 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003516 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3517 CXXUnit->getASTContext().getLangOptions());
3518
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003519 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3520 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003521 // FIXME: Would be great to have a "hint" cursor, then walk from that
3522 // hint cursor upward until we find a cursor whose source range encloses
3523 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003524 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003525 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003526 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00003527 /*VisitPreprocessorLast=*/true,
3528 SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003529 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003530 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003531
3532 if (Logging) {
3533 CXFile SearchFile;
3534 unsigned SearchLine, SearchColumn;
3535 CXFile ResultFile;
3536 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003537 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3538 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003539 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3540
Chandler Carruth20174222011-08-31 16:53:37 +00003541 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3542 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3543 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003544 SearchFileName = clang_getFileName(SearchFile);
3545 ResultFileName = clang_getFileName(ResultFile);
3546 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003547 USR = clang_getCursorUSR(Result);
3548 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003549 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3550 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003551 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3552 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003553 clang_disposeString(SearchFileName);
3554 clang_disposeString(ResultFileName);
3555 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003556 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003557
3558 CXCursor Definition = clang_getCursorDefinition(Result);
3559 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3560 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3561 CXString DefinitionKindSpelling
3562 = clang_getCursorKindSpelling(Definition.kind);
3563 CXFile DefinitionFile;
3564 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003565 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3566 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003567 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3568 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3569 clang_getCString(DefinitionKindSpelling),
3570 clang_getCString(DefinitionFileName),
3571 DefinitionLine, DefinitionColumn);
3572 clang_disposeString(DefinitionFileName);
3573 clang_disposeString(DefinitionKindSpelling);
3574 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003575 }
3576
Ted Kremeneke68fff62010-02-17 00:41:32 +00003577 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003578}
3579
Ted Kremenek73885552009-11-17 19:28:59 +00003580CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003581 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003582}
3583
3584unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003585 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003586}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003587
Douglas Gregor9ce55842010-11-20 00:09:34 +00003588unsigned clang_hashCursor(CXCursor C) {
3589 unsigned Index = 0;
3590 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3591 Index = 1;
3592
3593 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3594 std::make_pair(C.kind, C.data[Index]));
3595}
3596
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003597unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003598 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3599}
3600
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003601unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003602 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3603}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003604
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003605unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003606 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3607}
3608
Douglas Gregor97b98722010-01-19 23:20:36 +00003609unsigned clang_isExpression(enum CXCursorKind K) {
3610 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3611}
3612
3613unsigned clang_isStatement(enum CXCursorKind K) {
3614 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3615}
3616
Douglas Gregor8be80e12011-07-06 03:00:34 +00003617unsigned clang_isAttribute(enum CXCursorKind K) {
3618 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3619}
3620
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003621unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3622 return K == CXCursor_TranslationUnit;
3623}
3624
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003625unsigned clang_isPreprocessing(enum CXCursorKind K) {
3626 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3627}
3628
Ted Kremenekad6eff62010-03-08 21:17:29 +00003629unsigned clang_isUnexposed(enum CXCursorKind K) {
3630 switch (K) {
3631 case CXCursor_UnexposedDecl:
3632 case CXCursor_UnexposedExpr:
3633 case CXCursor_UnexposedStmt:
3634 case CXCursor_UnexposedAttr:
3635 return true;
3636 default:
3637 return false;
3638 }
3639}
3640
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003641CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003642 return C.kind;
3643}
3644
Douglas Gregor98258af2010-01-18 22:46:11 +00003645CXSourceLocation clang_getCursorLocation(CXCursor C) {
3646 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003647 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003648 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003649 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3650 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003651 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003652 }
3653
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003654 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003655 std::pair<ObjCProtocolDecl *, SourceLocation> P
3656 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003657 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003658 }
3659
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003660 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003661 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3662 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003663 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003664 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003665
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003666 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003667 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003668 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003669 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003670
3671 case CXCursor_TemplateRef: {
3672 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3673 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3674 }
3675
Douglas Gregor69319002010-08-31 23:48:11 +00003676 case CXCursor_NamespaceRef: {
3677 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3678 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3679 }
3680
Douglas Gregora67e03f2010-09-09 21:42:20 +00003681 case CXCursor_MemberRef: {
3682 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3683 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3684 }
3685
Ted Kremenek3064ef92010-08-27 21:34:58 +00003686 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003687 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3688 if (!BaseSpec)
3689 return clang_getNullLocation();
3690
3691 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3692 return cxloc::translateSourceLocation(getCursorContext(C),
3693 TSInfo->getTypeLoc().getBeginLoc());
3694
3695 return cxloc::translateSourceLocation(getCursorContext(C),
3696 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003697 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003698
Douglas Gregor36897b02010-09-10 00:22:18 +00003699 case CXCursor_LabelRef: {
3700 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3701 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3702 }
3703
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003704 case CXCursor_OverloadedDeclRef:
3705 return cxloc::translateSourceLocation(getCursorContext(C),
3706 getCursorOverloadedDeclRef(C).second);
3707
Douglas Gregorf46034a2010-01-18 23:41:10 +00003708 default:
3709 // FIXME: Need a way to enumerate all non-reference cases.
3710 llvm_unreachable("Missed a reference kind");
3711 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003712 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003713
3714 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003715 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003716 getLocationFromExpr(getCursorExpr(C)));
3717
Douglas Gregor36897b02010-09-10 00:22:18 +00003718 if (clang_isStatement(C.kind))
3719 return cxloc::translateSourceLocation(getCursorContext(C),
3720 getCursorStmt(C)->getLocStart());
3721
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003722 if (C.kind == CXCursor_PreprocessingDirective) {
3723 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3724 return cxloc::translateSourceLocation(getCursorContext(C), L);
3725 }
Douglas Gregor48072312010-03-18 15:23:44 +00003726
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003727 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003728 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003729 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003730 return cxloc::translateSourceLocation(getCursorContext(C), L);
3731 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003732
3733 if (C.kind == CXCursor_MacroDefinition) {
3734 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3735 return cxloc::translateSourceLocation(getCursorContext(C), L);
3736 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003737
3738 if (C.kind == CXCursor_InclusionDirective) {
3739 SourceLocation L
3740 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3741 return cxloc::translateSourceLocation(getCursorContext(C), L);
3742 }
3743
Ted Kremenek9a700d22010-05-12 06:16:13 +00003744 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003745 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003746
Douglas Gregorf46034a2010-01-18 23:41:10 +00003747 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003748 SourceLocation Loc = D->getLocation();
3749 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3750 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003751 // FIXME: Multiple variables declared in a single declaration
3752 // currently lack the information needed to correctly determine their
3753 // ranges when accounting for the type-specifier. We use context
3754 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3755 // and if so, whether it is the first decl.
3756 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3757 if (!cxcursor::isFirstInDeclGroup(C))
3758 Loc = VD->getLocation();
3759 }
3760
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003761 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003762}
Douglas Gregora7bde202010-01-19 00:34:46 +00003763
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003764} // end extern "C"
3765
3766static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003767 if (clang_isReference(C.kind)) {
3768 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003769 case CXCursor_ObjCSuperClassRef:
3770 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003771
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003772 case CXCursor_ObjCProtocolRef:
3773 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003774
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003775 case CXCursor_ObjCClassRef:
3776 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003777
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003778 case CXCursor_TypeRef:
3779 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003780
3781 case CXCursor_TemplateRef:
3782 return getCursorTemplateRef(C).second;
3783
Douglas Gregor69319002010-08-31 23:48:11 +00003784 case CXCursor_NamespaceRef:
3785 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003786
3787 case CXCursor_MemberRef:
3788 return getCursorMemberRef(C).second;
3789
Ted Kremenek3064ef92010-08-27 21:34:58 +00003790 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003791 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003792
Douglas Gregor36897b02010-09-10 00:22:18 +00003793 case CXCursor_LabelRef:
3794 return getCursorLabelRef(C).second;
3795
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003796 case CXCursor_OverloadedDeclRef:
3797 return getCursorOverloadedDeclRef(C).second;
3798
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003799 default:
3800 // FIXME: Need a way to enumerate all non-reference cases.
3801 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003802 }
3803 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003804
3805 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003806 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003807
3808 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003809 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003810
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003811 if (clang_isAttribute(C.kind))
3812 return getCursorAttr(C)->getRange();
3813
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003814 if (C.kind == CXCursor_PreprocessingDirective)
3815 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003816
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003817 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003818 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003819
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003820 if (C.kind == CXCursor_MacroDefinition)
3821 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003822
3823 if (C.kind == CXCursor_InclusionDirective)
3824 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3825
Ted Kremenek007a7c92010-11-01 23:26:51 +00003826 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3827 Decl *D = cxcursor::getCursorDecl(C);
3828 SourceRange R = D->getSourceRange();
3829 // FIXME: Multiple variables declared in a single declaration
3830 // currently lack the information needed to correctly determine their
3831 // ranges when accounting for the type-specifier. We use context
3832 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3833 // and if so, whether it is the first decl.
3834 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3835 if (!cxcursor::isFirstInDeclGroup(C))
3836 R.setBegin(VD->getLocation());
3837 }
3838 return R;
3839 }
Douglas Gregor66537982010-11-17 17:14:07 +00003840 return SourceRange();
3841}
3842
3843/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3844/// the decl-specifier-seq for declarations.
3845static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3846 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3847 Decl *D = cxcursor::getCursorDecl(C);
3848 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003849
Douglas Gregor2494dd02011-03-01 01:34:45 +00003850 // Adjust the start of the location for declarations preceded by
3851 // declaration specifiers.
3852 SourceLocation StartLoc;
3853 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3854 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3855 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3856 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3857 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3858 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3859 }
3860
3861 if (StartLoc.isValid() && R.getBegin().isValid() &&
3862 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3863 R.setBegin(StartLoc);
3864
3865 // FIXME: Multiple variables declared in a single declaration
3866 // currently lack the information needed to correctly determine their
3867 // ranges when accounting for the type-specifier. We use context
3868 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3869 // and if so, whether it is the first decl.
3870 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3871 if (!cxcursor::isFirstInDeclGroup(C))
3872 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003873 }
3874
3875 return R;
3876 }
3877
3878 return getRawCursorExtent(C);
3879}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003880
3881extern "C" {
3882
3883CXSourceRange clang_getCursorExtent(CXCursor C) {
3884 SourceRange R = getRawCursorExtent(C);
3885 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003886 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003888 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003889}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003890
3891CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003892 if (clang_isInvalid(C.kind))
3893 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003896 if (clang_isDeclaration(C.kind)) {
3897 Decl *D = getCursorDecl(C);
3898 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003899 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003900 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003901 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003902 if (ObjCForwardProtocolDecl *Protocols
3903 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003904 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003905 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003906 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3907 return MakeCXCursor(Property, tu);
3908
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003909 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003910 }
3911
Douglas Gregor97b98722010-01-19 23:20:36 +00003912 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003913 Expr *E = getCursorExpr(C);
3914 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003915 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003916 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003917
3918 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003919 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003920
Douglas Gregor97b98722010-01-19 23:20:36 +00003921 return clang_getNullCursor();
3922 }
3923
Douglas Gregor36897b02010-09-10 00:22:18 +00003924 if (clang_isStatement(C.kind)) {
3925 Stmt *S = getCursorStmt(C);
3926 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003927 if (LabelDecl *label = Goto->getLabel())
3928 if (LabelStmt *labelS = label->getStmt())
3929 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003930
3931 return clang_getNullCursor();
3932 }
3933
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003934 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003935 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003936 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003937 }
3938
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003939 if (!clang_isReference(C.kind))
3940 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003941
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003942 switch (C.kind) {
3943 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003944 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003945
3946 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003947 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003948
3949 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003950 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003951
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003952 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003953 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003954
3955 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003956 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003957
Douglas Gregor69319002010-08-31 23:48:11 +00003958 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003959 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003960
Douglas Gregora67e03f2010-09-09 21:42:20 +00003961 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003962 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003963
Ted Kremenek3064ef92010-08-27 21:34:58 +00003964 case CXCursor_CXXBaseSpecifier: {
3965 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3966 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003967 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003968 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003969
Douglas Gregor36897b02010-09-10 00:22:18 +00003970 case CXCursor_LabelRef:
3971 // FIXME: We end up faking the "parent" declaration here because we
3972 // don't want to make CXCursor larger.
3973 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003974 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3975 .getTranslationUnitDecl(),
3976 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003977
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003978 case CXCursor_OverloadedDeclRef:
3979 return C;
3980
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003981 default:
3982 // We would prefer to enumerate all non-reference cursor kinds here.
3983 llvm_unreachable("Unhandled reference cursor kind");
3984 break;
3985 }
3986 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003987
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003988 return clang_getNullCursor();
3989}
3990
Douglas Gregorb6998662010-01-19 19:34:47 +00003991CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003992 if (clang_isInvalid(C.kind))
3993 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003994
Ted Kremeneka60ed472010-11-16 08:15:36 +00003995 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003996
Douglas Gregorb6998662010-01-19 19:34:47 +00003997 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003998 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003999 C = clang_getCursorReferenced(C);
4000 WasReference = true;
4001 }
4002
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004003 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004004 return clang_getCursorReferenced(C);
4005
Douglas Gregorb6998662010-01-19 19:34:47 +00004006 if (!clang_isDeclaration(C.kind))
4007 return clang_getNullCursor();
4008
4009 Decl *D = getCursorDecl(C);
4010 if (!D)
4011 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004012
Douglas Gregorb6998662010-01-19 19:34:47 +00004013 switch (D->getKind()) {
4014 // Declaration kinds that don't really separate the notions of
4015 // declaration and definition.
4016 case Decl::Namespace:
4017 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004018 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004019 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004020 case Decl::TemplateTypeParm:
4021 case Decl::EnumConstant:
4022 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004023 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004024 case Decl::ObjCIvar:
4025 case Decl::ObjCAtDefsField:
4026 case Decl::ImplicitParam:
4027 case Decl::ParmVar:
4028 case Decl::NonTypeTemplateParm:
4029 case Decl::TemplateTemplateParm:
4030 case Decl::ObjCCategoryImpl:
4031 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004032 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004033 case Decl::LinkageSpec:
4034 case Decl::ObjCPropertyImpl:
4035 case Decl::FileScopeAsm:
4036 case Decl::StaticAssert:
4037 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004038 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004039 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004040 return C;
4041
4042 // Declaration kinds that don't make any sense here, but are
4043 // nonetheless harmless.
4044 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004045 break;
4046
4047 // Declaration kinds for which the definition is not resolvable.
4048 case Decl::UnresolvedUsingTypename:
4049 case Decl::UnresolvedUsingValue:
4050 break;
4051
4052 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004053 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004054 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004055
4056 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004057 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004058
4059 case Decl::Enum:
4060 case Decl::Record:
4061 case Decl::CXXRecord:
4062 case Decl::ClassTemplateSpecialization:
4063 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004064 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004065 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004066 return clang_getNullCursor();
4067
4068 case Decl::Function:
4069 case Decl::CXXMethod:
4070 case Decl::CXXConstructor:
4071 case Decl::CXXDestructor:
4072 case Decl::CXXConversion: {
4073 const FunctionDecl *Def = 0;
4074 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004075 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004076 return clang_getNullCursor();
4077 }
4078
4079 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004080 // Ask the variable if it has a definition.
4081 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004083 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004084 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004085
Douglas Gregorb6998662010-01-19 19:34:47 +00004086 case Decl::FunctionTemplate: {
4087 const FunctionDecl *Def = 0;
4088 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004089 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004090 return clang_getNullCursor();
4091 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004092
Douglas Gregorb6998662010-01-19 19:34:47 +00004093 case Decl::ClassTemplate: {
4094 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004095 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004096 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004097 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004098 return clang_getNullCursor();
4099 }
4100
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004101 case Decl::Using:
4102 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004103 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004104
4105 case Decl::UsingShadow:
4106 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004107 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004108 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004109
4110 case Decl::ObjCMethod: {
4111 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4112 if (Method->isThisDeclarationADefinition())
4113 return C;
4114
4115 // Dig out the method definition in the associated
4116 // @implementation, if we have it.
4117 // FIXME: The ASTs should make finding the definition easier.
4118 if (ObjCInterfaceDecl *Class
4119 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4120 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4121 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4122 Method->isInstanceMethod()))
4123 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004124 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004125
4126 return clang_getNullCursor();
4127 }
4128
4129 case Decl::ObjCCategory:
4130 if (ObjCCategoryImplDecl *Impl
4131 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004132 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004133 return clang_getNullCursor();
4134
4135 case Decl::ObjCProtocol:
4136 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4137 return C;
4138 return clang_getNullCursor();
4139
4140 case Decl::ObjCInterface:
4141 // There are two notions of a "definition" for an Objective-C
4142 // class: the interface and its implementation. When we resolved a
4143 // reference to an Objective-C class, produce the @interface as
4144 // the definition; when we were provided with the interface,
4145 // produce the @implementation as the definition.
4146 if (WasReference) {
4147 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4148 return C;
4149 } else if (ObjCImplementationDecl *Impl
4150 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004151 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004152 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004153
Douglas Gregorb6998662010-01-19 19:34:47 +00004154 case Decl::ObjCProperty:
4155 // FIXME: We don't really know where to find the
4156 // ObjCPropertyImplDecls that implement this property.
4157 return clang_getNullCursor();
4158
4159 case Decl::ObjCCompatibleAlias:
4160 if (ObjCInterfaceDecl *Class
4161 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4162 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004163 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004164
Douglas Gregorb6998662010-01-19 19:34:47 +00004165 return clang_getNullCursor();
4166
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004167 case Decl::ObjCForwardProtocol:
4168 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004169 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004170
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004171 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004172 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004173 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004174
4175 case Decl::Friend:
4176 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004177 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004178 return clang_getNullCursor();
4179
4180 case Decl::FriendTemplate:
4181 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004182 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004183 return clang_getNullCursor();
4184 }
4185
4186 return clang_getNullCursor();
4187}
4188
4189unsigned clang_isCursorDefinition(CXCursor C) {
4190 if (!clang_isDeclaration(C.kind))
4191 return 0;
4192
4193 return clang_getCursorDefinition(C) == C;
4194}
4195
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004196CXCursor clang_getCanonicalCursor(CXCursor C) {
4197 if (!clang_isDeclaration(C.kind))
4198 return C;
4199
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004200 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004201 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4202 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4203 return MakeCXCursor(CatD, getCursorTU(C));
4204
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004205 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4206 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4207 return MakeCXCursor(IFD, getCursorTU(C));
4208
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004209 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004210 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004211
4212 return C;
4213}
4214
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004215unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004216 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004217 return 0;
4218
4219 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4220 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4221 return E->getNumDecls();
4222
4223 if (OverloadedTemplateStorage *S
4224 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4225 return S->size();
4226
4227 Decl *D = Storage.get<Decl*>();
4228 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004229 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004230 if (isa<ObjCClassDecl>(D))
4231 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004232 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4233 return Protocols->protocol_size();
4234
4235 return 0;
4236}
4237
4238CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004239 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004240 return clang_getNullCursor();
4241
4242 if (index >= clang_getNumOverloadedDecls(cursor))
4243 return clang_getNullCursor();
4244
Ted Kremeneka60ed472010-11-16 08:15:36 +00004245 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004246 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4247 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004248 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004249
4250 if (OverloadedTemplateStorage *S
4251 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004252 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004253
4254 Decl *D = Storage.get<Decl*>();
4255 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4256 // FIXME: This is, unfortunately, linear time.
4257 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4258 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004259 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004260 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004261 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004262 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004263 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004264 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004265
4266 return clang_getNullCursor();
4267}
4268
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004269void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004270 const char **startBuf,
4271 const char **endBuf,
4272 unsigned *startLine,
4273 unsigned *startColumn,
4274 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004275 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004276 assert(getCursorDecl(C) && "CXCursor has null decl");
4277 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004278 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4279 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004280
Steve Naroff4ade6d62009-09-23 17:52:52 +00004281 SourceManager &SM = FD->getASTContext().getSourceManager();
4282 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4283 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4284 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4285 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4286 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4287 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4288}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004289
Douglas Gregor430d7a12011-07-25 17:48:11 +00004290
4291CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4292 unsigned PieceIndex) {
4293 RefNamePieces Pieces;
4294
4295 switch (C.kind) {
4296 case CXCursor_MemberRefExpr:
4297 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4298 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4299 E->getQualifierLoc().getSourceRange());
4300 break;
4301
4302 case CXCursor_DeclRefExpr:
4303 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4304 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4305 E->getQualifierLoc().getSourceRange(),
4306 E->getExplicitTemplateArgsOpt());
4307 break;
4308
4309 case CXCursor_CallExpr:
4310 if (CXXOperatorCallExpr *OCE =
4311 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4312 Expr *Callee = OCE->getCallee();
4313 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4314 Callee = ICE->getSubExpr();
4315
4316 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4317 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4318 DRE->getQualifierLoc().getSourceRange());
4319 }
4320 break;
4321
4322 default:
4323 break;
4324 }
4325
4326 if (Pieces.empty()) {
4327 if (PieceIndex == 0)
4328 return clang_getCursorExtent(C);
4329 } else if (PieceIndex < Pieces.size()) {
4330 SourceRange R = Pieces[PieceIndex];
4331 if (R.isValid())
4332 return cxloc::translateSourceRange(getCursorContext(C), R);
4333 }
4334
4335 return clang_getNullRange();
4336}
4337
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004338void clang_enableStackTraces(void) {
4339 llvm::sys::PrintStackTraceOnErrorSignal();
4340}
4341
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004342void clang_executeOnThread(void (*fn)(void*), void *user_data,
4343 unsigned stack_size) {
4344 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4345}
4346
Ted Kremenekfb480492010-01-13 21:46:36 +00004347} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004348
Ted Kremenekfb480492010-01-13 21:46:36 +00004349//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004350// Token-based Operations.
4351//===----------------------------------------------------------------------===//
4352
4353/* CXToken layout:
4354 * int_data[0]: a CXTokenKind
4355 * int_data[1]: starting token location
4356 * int_data[2]: token length
4357 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004358 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004359 * otherwise unused.
4360 */
4361extern "C" {
4362
4363CXTokenKind clang_getTokenKind(CXToken CXTok) {
4364 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4365}
4366
4367CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4368 switch (clang_getTokenKind(CXTok)) {
4369 case CXToken_Identifier:
4370 case CXToken_Keyword:
4371 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004372 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4373 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004374
4375 case CXToken_Literal: {
4376 // We have stashed the starting pointer in the ptr_data field. Use it.
4377 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004378 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004379 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004380
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004381 case CXToken_Punctuation:
4382 case CXToken_Comment:
4383 break;
4384 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004385
4386 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004387 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004388 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004389 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004390 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004391
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004392 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4393 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004394 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004395 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004396 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004397 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4398 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004399 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004400
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004401 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004402}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004403
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004404CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004405 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004406 if (!CXXUnit)
4407 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004408
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004409 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4410 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4411}
4412
4413CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004414 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004415 if (!CXXUnit)
4416 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004417
4418 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004419 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4420}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004421
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004422void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4423 CXToken **Tokens, unsigned *NumTokens) {
4424 if (Tokens)
4425 *Tokens = 0;
4426 if (NumTokens)
4427 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004428
Ted Kremeneka60ed472010-11-16 08:15:36 +00004429 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004430 if (!CXXUnit || !Tokens || !NumTokens)
4431 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004432
Douglas Gregorbdf60622010-03-05 21:16:25 +00004433 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4434
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004435 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004436 if (R.isInvalid())
4437 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004438
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004439 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4440 std::pair<FileID, unsigned> BeginLocInfo
4441 = SourceMgr.getDecomposedLoc(R.getBegin());
4442 std::pair<FileID, unsigned> EndLocInfo
4443 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004444
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004445 // Cannot tokenize across files.
4446 if (BeginLocInfo.first != EndLocInfo.first)
4447 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004448
4449 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004450 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004451 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004452 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004453 if (Invalid)
4454 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004455
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004456 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4457 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004458 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004459 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004460
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004461 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004462 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004463 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004464 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004465 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004466 do {
4467 // Lex the next token
4468 Lex.LexFromRawLexer(Tok);
4469 if (Tok.is(tok::eof))
4470 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004471
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004472 // Initialize the CXToken.
4473 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004474
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004475 // - Common fields
4476 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4477 CXTok.int_data[2] = Tok.getLength();
4478 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004479
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004480 // - Kind-specific fields
4481 if (Tok.isLiteral()) {
4482 CXTok.int_data[0] = CXToken_Literal;
4483 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004484 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004485 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004486 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004487 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004488
David Chisnall096428b2010-10-13 21:44:48 +00004489 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004490 CXTok.int_data[0] = CXToken_Keyword;
4491 }
4492 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004493 CXTok.int_data[0] = Tok.is(tok::identifier)
4494 ? CXToken_Identifier
4495 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004496 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004497 CXTok.ptr_data = II;
4498 } else if (Tok.is(tok::comment)) {
4499 CXTok.int_data[0] = CXToken_Comment;
4500 CXTok.ptr_data = 0;
4501 } else {
4502 CXTok.int_data[0] = CXToken_Punctuation;
4503 CXTok.ptr_data = 0;
4504 }
4505 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004506 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004507 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004508
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004509 if (CXTokens.empty())
4510 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004511
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004512 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4513 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4514 *NumTokens = CXTokens.size();
4515}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004516
Ted Kremenek6db61092010-05-05 00:55:15 +00004517void clang_disposeTokens(CXTranslationUnit TU,
4518 CXToken *Tokens, unsigned NumTokens) {
4519 free(Tokens);
4520}
4521
4522} // end: extern "C"
4523
4524//===----------------------------------------------------------------------===//
4525// Token annotation APIs.
4526//===----------------------------------------------------------------------===//
4527
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004528typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004529static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4530 CXCursor parent,
4531 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004532namespace {
4533class AnnotateTokensWorker {
4534 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004535 CXToken *Tokens;
4536 CXCursor *Cursors;
4537 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004538 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004539 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004540 CursorVisitor AnnotateVis;
4541 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004542 bool HasContextSensitiveKeywords;
4543
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004544 bool MoreTokens() const { return TokIdx < NumTokens; }
4545 unsigned NextToken() const { return TokIdx; }
4546 void AdvanceToken() { ++TokIdx; }
4547 SourceLocation GetTokenLoc(unsigned tokI) {
4548 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4549 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004550 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004551 return Tokens[tokI].int_data[3] != 0;
4552 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004553 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004554 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4555 }
4556
4557 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004558 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4559 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004560
Ted Kremenek6db61092010-05-05 00:55:15 +00004561public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004562 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004563 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004564 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004565 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004566 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004567 AnnotateVis(tu,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00004568 AnnotateTokensVisitor, this, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004569 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4570 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004571
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004572 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004573 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004574 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004575 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004576 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004577 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004578
4579 /// \brief Determine whether the annotator saw any cursors that have
4580 /// context-sensitive keywords.
4581 bool hasContextSensitiveKeywords() const {
4582 return HasContextSensitiveKeywords;
4583 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004584};
4585}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004586
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004587void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4588 // Walk the AST within the region of interest, annotating tokens
4589 // along the way.
4590 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004591
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004592 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4593 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004594 if (Pos != Annotated.end() &&
4595 (clang_isInvalid(Cursors[I].kind) ||
4596 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004597 Cursors[I] = Pos->second;
4598 }
4599
4600 // Finish up annotating any tokens left.
4601 if (!MoreTokens())
4602 return;
4603
4604 const CXCursor &C = clang_getNullCursor();
4605 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4606 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4607 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004608 }
4609}
4610
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004611/// \brief It annotates and advances tokens with a cursor until the comparison
4612//// between the cursor location and the source range is the same as
4613/// \arg compResult.
4614///
4615/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4616/// Pass RangeOverlap to annotate tokens inside a range.
4617void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4618 RangeComparisonResult compResult,
4619 SourceRange range) {
4620 while (MoreTokens()) {
4621 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004622 if (isFunctionMacroToken(I))
4623 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004624
4625 SourceLocation TokLoc = GetTokenLoc(I);
4626 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4627 Cursors[I] = updateC;
4628 AdvanceToken();
4629 continue;
4630 }
4631 break;
4632 }
4633}
4634
4635/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004636void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4637 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004638 RangeComparisonResult compResult,
4639 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004640 assert(MoreTokens());
4641 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004642 "Should be called only for macro arg tokens");
4643
4644 // This works differently than annotateAndAdvanceTokens; because expanded
4645 // macro arguments can have arbitrary translation-unit source order, we do not
4646 // advance the token index one by one until a token fails the range test.
4647 // We only advance once past all of the macro arg tokens if all of them
4648 // pass the range test. If one of them fails we keep the token index pointing
4649 // at the start of the macro arg tokens so that the failing token will be
4650 // annotated by a subsequent annotation try.
4651
4652 bool atLeastOneCompFail = false;
4653
4654 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004655 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4656 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004657 if (TokLoc.isFileID())
4658 continue; // not macro arg token, it's parens or comma.
4659 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4660 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4661 Cursors[I] = updateC;
4662 } else
4663 atLeastOneCompFail = true;
4664 }
4665
4666 if (!atLeastOneCompFail)
4667 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4668}
4669
Ted Kremenek6db61092010-05-05 00:55:15 +00004670enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004671AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004672 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004673 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004674 if (cursorRange.isInvalid())
4675 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004676
4677 if (!HasContextSensitiveKeywords) {
4678 // Objective-C properties can have context-sensitive keywords.
4679 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4680 if (ObjCPropertyDecl *Property
4681 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4682 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4683 }
4684 // Objective-C methods can have context-sensitive keywords.
4685 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4686 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4687 if (ObjCMethodDecl *Method
4688 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4689 if (Method->getObjCDeclQualifier())
4690 HasContextSensitiveKeywords = true;
4691 else {
4692 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4693 PEnd = Method->param_end();
4694 P != PEnd; ++P) {
4695 if ((*P)->getObjCDeclQualifier()) {
4696 HasContextSensitiveKeywords = true;
4697 break;
4698 }
4699 }
4700 }
4701 }
4702 }
4703 // C++ methods can have context-sensitive keywords.
4704 else if (cursor.kind == CXCursor_CXXMethod) {
4705 if (CXXMethodDecl *Method
4706 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4707 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4708 HasContextSensitiveKeywords = true;
4709 }
4710 }
4711 // C++ classes can have context-sensitive keywords.
4712 else if (cursor.kind == CXCursor_StructDecl ||
4713 cursor.kind == CXCursor_ClassDecl ||
4714 cursor.kind == CXCursor_ClassTemplate ||
4715 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4716 if (Decl *D = getCursorDecl(cursor))
4717 if (D->hasAttr<FinalAttr>())
4718 HasContextSensitiveKeywords = true;
4719 }
4720 }
4721
Douglas Gregor4419b672010-10-21 06:10:04 +00004722 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004723 // For macro expansions, just note where the beginning of the macro
4724 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004725 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004726 Annotated[Loc.int_data] = cursor;
4727 return CXChildVisit_Recurse;
4728 }
4729
Douglas Gregor4419b672010-10-21 06:10:04 +00004730 // Items in the preprocessing record are kept separate from items in
4731 // declarations, so we keep a separate token index.
4732 unsigned SavedTokIdx = TokIdx;
4733 TokIdx = PreprocessingTokIdx;
4734
4735 // Skip tokens up until we catch up to the beginning of the preprocessing
4736 // entry.
4737 while (MoreTokens()) {
4738 const unsigned I = NextToken();
4739 SourceLocation TokLoc = GetTokenLoc(I);
4740 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4741 case RangeBefore:
4742 AdvanceToken();
4743 continue;
4744 case RangeAfter:
4745 case RangeOverlap:
4746 break;
4747 }
4748 break;
4749 }
4750
4751 // Look at all of the tokens within this range.
4752 while (MoreTokens()) {
4753 const unsigned I = NextToken();
4754 SourceLocation TokLoc = GetTokenLoc(I);
4755 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4756 case RangeBefore:
4757 assert(0 && "Infeasible");
4758 case RangeAfter:
4759 break;
4760 case RangeOverlap:
4761 Cursors[I] = cursor;
4762 AdvanceToken();
4763 continue;
4764 }
4765 break;
4766 }
4767
4768 // Save the preprocessing token index; restore the non-preprocessing
4769 // token index.
4770 PreprocessingTokIdx = TokIdx;
4771 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004772 return CXChildVisit_Recurse;
4773 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004774
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004775 if (cursorRange.isInvalid())
4776 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004777
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004778 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4779
Ted Kremeneka333c662010-05-12 05:29:33 +00004780 // Adjust the annotated range based specific declarations.
4781 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4782 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004783 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004784
4785 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004786 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004787 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4788 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4789 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4790 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4791 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004792 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004793
4794 if (StartLoc.isValid() && L.isValid() &&
4795 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4796 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004797 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004798
Ted Kremenek3f404602010-08-14 01:14:06 +00004799 // If the location of the cursor occurs within a macro instantiation, record
4800 // the spelling location of the cursor in our annotation map. We can then
4801 // paper over the token labelings during a post-processing step to try and
4802 // get cursor mappings for tokens that are the *arguments* of a macro
4803 // instantiation.
4804 if (L.isMacroID()) {
4805 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4806 // Only invalidate the old annotation if it isn't part of a preprocessing
4807 // directive. Here we assume that the default construction of CXCursor
4808 // results in CXCursor.kind being an initialized value (i.e., 0). If
4809 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004810
Ted Kremenek3f404602010-08-14 01:14:06 +00004811 CXCursor &oldC = Annotated[rawEncoding];
4812 if (!clang_isPreprocessing(oldC.kind))
4813 oldC = cursor;
4814 }
4815
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004816 const enum CXCursorKind K = clang_getCursorKind(parent);
4817 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004818 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4819 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004820
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004821 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004822
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004823 // Avoid having the cursor of an expression "overwrite" the annotation of the
4824 // variable declaration that it belongs to.
4825 // This can happen for C++ constructor expressions whose range generally
4826 // include the variable declaration, e.g.:
4827 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4828 if (clang_isExpression(cursorK)) {
4829 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004830 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004831 const unsigned I = NextToken();
4832 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4833 E->getLocStart() == D->getLocation() &&
4834 E->getLocStart() == GetTokenLoc(I)) {
4835 Cursors[I] = updateC;
4836 AdvanceToken();
4837 }
4838 }
4839 }
4840
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004841 // Visit children to get their cursor information.
4842 const unsigned BeforeChildren = NextToken();
4843 VisitChildren(cursor);
4844 const unsigned AfterChildren = NextToken();
4845
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004846 // Scan the tokens that are at the end of the cursor, but are not captured
4847 // but the child cursors.
4848 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004849
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004850 // Scan the tokens that are at the beginning of the cursor, but are not
4851 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004852 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4853 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4854 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004855
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004856 Cursors[I] = cursor;
4857 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004858
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004859 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004860}
4861
Ted Kremenek6db61092010-05-05 00:55:15 +00004862static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4863 CXCursor parent,
4864 CXClientData client_data) {
4865 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4866}
4867
Ted Kremenek6628a612011-03-18 22:51:30 +00004868namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004869
4870/// \brief Uses the macro expansions in the preprocessing record to find
4871/// and mark tokens that are macro arguments. This info is used by the
4872/// AnnotateTokensWorker.
4873class MarkMacroArgTokensVisitor {
4874 SourceManager &SM;
4875 CXToken *Tokens;
4876 unsigned NumTokens;
4877 unsigned CurIdx;
4878
4879public:
4880 MarkMacroArgTokensVisitor(SourceManager &SM,
4881 CXToken *tokens, unsigned numTokens)
4882 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4883
4884 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4885 if (cursor.kind != CXCursor_MacroExpansion)
4886 return CXChildVisit_Continue;
4887
4888 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4889 if (macroRange.getBegin() == macroRange.getEnd())
4890 return CXChildVisit_Continue; // it's not a function macro.
4891
4892 for (; CurIdx < NumTokens; ++CurIdx) {
4893 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4894 macroRange.getBegin()))
4895 break;
4896 }
4897
4898 if (CurIdx == NumTokens)
4899 return CXChildVisit_Break;
4900
4901 for (; CurIdx < NumTokens; ++CurIdx) {
4902 SourceLocation tokLoc = getTokenLoc(CurIdx);
4903 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4904 break;
4905
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004906 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004907 }
4908
4909 if (CurIdx == NumTokens)
4910 return CXChildVisit_Break;
4911
4912 return CXChildVisit_Continue;
4913 }
4914
4915private:
4916 SourceLocation getTokenLoc(unsigned tokI) {
4917 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4918 }
4919
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004920 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004921 // The third field is reserved and currently not used. Use it here
4922 // to mark macro arg expanded tokens with their expanded locations.
4923 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4924 }
4925};
4926
4927} // end anonymous namespace
4928
4929static CXChildVisitResult
4930MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4931 CXClientData client_data) {
4932 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4933 parent);
4934}
4935
4936namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004937 struct clang_annotateTokens_Data {
4938 CXTranslationUnit TU;
4939 ASTUnit *CXXUnit;
4940 CXToken *Tokens;
4941 unsigned NumTokens;
4942 CXCursor *Cursors;
4943 };
4944}
4945
Ted Kremenekab979612010-11-11 08:05:23 +00004946// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004947static void clang_annotateTokensImpl(void *UserData) {
4948 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4949 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4950 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4951 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4952 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4953
4954 // Determine the region of interest, which contains all of the tokens.
4955 SourceRange RegionOfInterest;
4956 RegionOfInterest.setBegin(
4957 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4958 RegionOfInterest.setEnd(
4959 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4960 Tokens[NumTokens-1])));
4961
4962 // A mapping from the source locations found when re-lexing or traversing the
4963 // region of interest to the corresponding cursors.
4964 AnnotateTokensData Annotated;
4965
4966 // Relex the tokens within the source range to look for preprocessing
4967 // directives.
4968 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4969 std::pair<FileID, unsigned> BeginLocInfo
4970 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4971 std::pair<FileID, unsigned> EndLocInfo
4972 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4973
Chris Lattner5f9e2722011-07-23 10:55:15 +00004974 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00004975 bool Invalid = false;
4976 if (BeginLocInfo.first == EndLocInfo.first &&
4977 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4978 !Invalid) {
4979 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4980 CXXUnit->getASTContext().getLangOptions(),
4981 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4982 Buffer.end());
4983 Lex.SetCommentRetentionState(true);
4984
4985 // Lex tokens in raw mode until we hit the end of the range, to avoid
4986 // entering #includes or expanding macros.
4987 while (true) {
4988 Token Tok;
4989 Lex.LexFromRawLexer(Tok);
4990
4991 reprocess:
4992 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4993 // We have found a preprocessing directive. Gobble it up so that we
4994 // don't see it while preprocessing these tokens later, but keep track
4995 // of all of the token locations inside this preprocessing directive so
4996 // that we can annotate them appropriately.
4997 //
4998 // FIXME: Some simple tests here could identify macro definitions and
4999 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005000 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00005001 do {
5002 Locations.push_back(Tok.getLocation());
5003 Lex.LexFromRawLexer(Tok);
5004 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5005
5006 using namespace cxcursor;
5007 CXCursor Cursor
5008 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5009 Locations.back()),
5010 TU);
5011 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5012 Annotated[Locations[I].getRawEncoding()] = Cursor;
5013 }
5014
5015 if (Tok.isAtStartOfLine())
5016 goto reprocess;
5017
5018 continue;
5019 }
5020
5021 if (Tok.is(tok::eof))
5022 break;
5023 }
5024 }
5025
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005026 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5027 // Search and mark tokens that are macro argument expansions.
5028 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5029 Tokens, NumTokens);
5030 CursorVisitor MacroArgMarker(TU,
5031 MarkMacroArgTokensVisitorDelegate, &Visitor,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00005032 true, RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005033 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5034 }
5035
Ted Kremenek6628a612011-03-18 22:51:30 +00005036 // Annotate all of the source locations in the region of interest that map to
5037 // a specific cursor.
5038 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5039 TU, RegionOfInterest);
5040
5041 // FIXME: We use a ridiculous stack size here because the data-recursion
5042 // algorithm uses a large stack frame than the non-data recursive version,
5043 // and AnnotationTokensWorker currently transforms the data-recursion
5044 // algorithm back into a traditional recursion by explicitly calling
5045 // VisitChildren(). We will need to remove this explicit recursive call.
5046 W.AnnotateTokens();
5047
5048 // If we ran into any entities that involve context-sensitive keywords,
5049 // take another pass through the tokens to mark them as such.
5050 if (W.hasContextSensitiveKeywords()) {
5051 for (unsigned I = 0; I != NumTokens; ++I) {
5052 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5053 continue;
5054
5055 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5056 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5057 if (ObjCPropertyDecl *Property
5058 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5059 if (Property->getPropertyAttributesAsWritten() != 0 &&
5060 llvm::StringSwitch<bool>(II->getName())
5061 .Case("readonly", true)
5062 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005063 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005064 .Case("readwrite", true)
5065 .Case("retain", true)
5066 .Case("copy", true)
5067 .Case("nonatomic", true)
5068 .Case("atomic", true)
5069 .Case("getter", true)
5070 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005071 .Case("strong", true)
5072 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005073 .Default(false))
5074 Tokens[I].int_data[0] = CXToken_Keyword;
5075 }
5076 continue;
5077 }
5078
5079 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5080 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5081 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5082 if (llvm::StringSwitch<bool>(II->getName())
5083 .Case("in", true)
5084 .Case("out", true)
5085 .Case("inout", true)
5086 .Case("oneway", true)
5087 .Case("bycopy", true)
5088 .Case("byref", true)
5089 .Default(false))
5090 Tokens[I].int_data[0] = CXToken_Keyword;
5091 continue;
5092 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005093
5094 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5095 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5096 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005097 continue;
5098 }
5099 }
5100 }
Ted Kremenekab979612010-11-11 08:05:23 +00005101}
5102
Ted Kremenek6db61092010-05-05 00:55:15 +00005103extern "C" {
5104
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005105void clang_annotateTokens(CXTranslationUnit TU,
5106 CXToken *Tokens, unsigned NumTokens,
5107 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005108
5109 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005110 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005111
Douglas Gregor4419b672010-10-21 06:10:04 +00005112 // Any token we don't specifically annotate will have a NULL cursor.
5113 CXCursor C = clang_getNullCursor();
5114 for (unsigned I = 0; I != NumTokens; ++I)
5115 Cursors[I] = C;
5116
Ted Kremeneka60ed472010-11-16 08:15:36 +00005117 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005118 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005119 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005120
Douglas Gregorbdf60622010-03-05 21:16:25 +00005121 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005122
5123 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005124 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005125 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005126 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005127 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5128 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005129}
Ted Kremenek6628a612011-03-18 22:51:30 +00005130
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005131} // end: extern "C"
5132
5133//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005134// Operations for querying linkage of a cursor.
5135//===----------------------------------------------------------------------===//
5136
5137extern "C" {
5138CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005139 if (!clang_isDeclaration(cursor.kind))
5140 return CXLinkage_Invalid;
5141
Ted Kremenek16b42592010-03-03 06:36:57 +00005142 Decl *D = cxcursor::getCursorDecl(cursor);
5143 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5144 switch (ND->getLinkage()) {
5145 case NoLinkage: return CXLinkage_NoLinkage;
5146 case InternalLinkage: return CXLinkage_Internal;
5147 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5148 case ExternalLinkage: return CXLinkage_External;
5149 };
5150
5151 return CXLinkage_Invalid;
5152}
5153} // end: extern "C"
5154
5155//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005156// Operations for querying language of a cursor.
5157//===----------------------------------------------------------------------===//
5158
5159static CXLanguageKind getDeclLanguage(const Decl *D) {
5160 switch (D->getKind()) {
5161 default:
5162 break;
5163 case Decl::ImplicitParam:
5164 case Decl::ObjCAtDefsField:
5165 case Decl::ObjCCategory:
5166 case Decl::ObjCCategoryImpl:
5167 case Decl::ObjCClass:
5168 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005169 case Decl::ObjCForwardProtocol:
5170 case Decl::ObjCImplementation:
5171 case Decl::ObjCInterface:
5172 case Decl::ObjCIvar:
5173 case Decl::ObjCMethod:
5174 case Decl::ObjCProperty:
5175 case Decl::ObjCPropertyImpl:
5176 case Decl::ObjCProtocol:
5177 return CXLanguage_ObjC;
5178 case Decl::CXXConstructor:
5179 case Decl::CXXConversion:
5180 case Decl::CXXDestructor:
5181 case Decl::CXXMethod:
5182 case Decl::CXXRecord:
5183 case Decl::ClassTemplate:
5184 case Decl::ClassTemplatePartialSpecialization:
5185 case Decl::ClassTemplateSpecialization:
5186 case Decl::Friend:
5187 case Decl::FriendTemplate:
5188 case Decl::FunctionTemplate:
5189 case Decl::LinkageSpec:
5190 case Decl::Namespace:
5191 case Decl::NamespaceAlias:
5192 case Decl::NonTypeTemplateParm:
5193 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005194 case Decl::TemplateTemplateParm:
5195 case Decl::TemplateTypeParm:
5196 case Decl::UnresolvedUsingTypename:
5197 case Decl::UnresolvedUsingValue:
5198 case Decl::Using:
5199 case Decl::UsingDirective:
5200 case Decl::UsingShadow:
5201 return CXLanguage_CPlusPlus;
5202 }
5203
5204 return CXLanguage_C;
5205}
5206
5207extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005208
5209enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5210 if (clang_isDeclaration(cursor.kind))
5211 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005212 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005213 return CXAvailability_Available;
5214
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005215 switch (D->getAvailability()) {
5216 case AR_Available:
5217 case AR_NotYetIntroduced:
5218 return CXAvailability_Available;
5219
5220 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005221 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005222
5223 case AR_Unavailable:
5224 return CXAvailability_NotAvailable;
5225 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005226 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005227
Douglas Gregor58ddb602010-08-23 23:00:57 +00005228 return CXAvailability_Available;
5229}
5230
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005231CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5232 if (clang_isDeclaration(cursor.kind))
5233 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5234
5235 return CXLanguage_Invalid;
5236}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005237
5238 /// \brief If the given cursor is the "templated" declaration
5239 /// descibing a class or function template, return the class or
5240 /// function template.
5241static Decl *maybeGetTemplateCursor(Decl *D) {
5242 if (!D)
5243 return 0;
5244
5245 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5246 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5247 return FunTmpl;
5248
5249 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5250 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5251 return ClassTmpl;
5252
5253 return D;
5254}
5255
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005256CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5257 if (clang_isDeclaration(cursor.kind)) {
5258 if (Decl *D = getCursorDecl(cursor)) {
5259 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005260 if (!DC)
5261 return clang_getNullCursor();
5262
5263 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5264 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005265 }
5266 }
5267
5268 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5269 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005270 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005271 }
5272
5273 return clang_getNullCursor();
5274}
5275
5276CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5277 if (clang_isDeclaration(cursor.kind)) {
5278 if (Decl *D = getCursorDecl(cursor)) {
5279 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005280 if (!DC)
5281 return clang_getNullCursor();
5282
5283 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5284 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005285 }
5286 }
5287
5288 // FIXME: Note that we can't easily compute the lexical context of a
5289 // statement or expression, so we return nothing.
5290 return clang_getNullCursor();
5291}
5292
Douglas Gregor9f592342010-10-01 20:25:15 +00005293static void CollectOverriddenMethods(DeclContext *Ctx,
5294 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005295 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005296 if (!Ctx)
5297 return;
5298
5299 // If we have a class or category implementation, jump straight to the
5300 // interface.
5301 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5302 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5303
5304 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5305 if (!Container)
5306 return;
5307
5308 // Check whether we have a matching method at this level.
5309 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5310 Method->isInstanceMethod()))
5311 if (Method != Overridden) {
5312 // We found an override at this level; there is no need to look
5313 // into other protocols or categories.
5314 Methods.push_back(Overridden);
5315 return;
5316 }
5317
5318 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5319 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5320 PEnd = Protocol->protocol_end();
5321 P != PEnd; ++P)
5322 CollectOverriddenMethods(*P, Method, Methods);
5323 }
5324
5325 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5326 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5327 PEnd = Category->protocol_end();
5328 P != PEnd; ++P)
5329 CollectOverriddenMethods(*P, Method, Methods);
5330 }
5331
5332 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5333 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5334 PEnd = Interface->protocol_end();
5335 P != PEnd; ++P)
5336 CollectOverriddenMethods(*P, Method, Methods);
5337
5338 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5339 Category; Category = Category->getNextClassCategory())
5340 CollectOverriddenMethods(Category, Method, Methods);
5341
5342 // We only look into the superclass if we haven't found anything yet.
5343 if (Methods.empty())
5344 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5345 return CollectOverriddenMethods(Super, Method, Methods);
5346 }
5347}
5348
5349void clang_getOverriddenCursors(CXCursor cursor,
5350 CXCursor **overridden,
5351 unsigned *num_overridden) {
5352 if (overridden)
5353 *overridden = 0;
5354 if (num_overridden)
5355 *num_overridden = 0;
5356 if (!overridden || !num_overridden)
5357 return;
5358
5359 if (!clang_isDeclaration(cursor.kind))
5360 return;
5361
5362 Decl *D = getCursorDecl(cursor);
5363 if (!D)
5364 return;
5365
5366 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005367 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005368 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5369 *num_overridden = CXXMethod->size_overridden_methods();
5370 if (!*num_overridden)
5371 return;
5372
5373 *overridden = new CXCursor [*num_overridden];
5374 unsigned I = 0;
5375 for (CXXMethodDecl::method_iterator
5376 M = CXXMethod->begin_overridden_methods(),
5377 MEnd = CXXMethod->end_overridden_methods();
5378 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005379 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005380 return;
5381 }
5382
5383 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5384 if (!Method)
5385 return;
5386
5387 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005388 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005389 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5390
5391 if (Methods.empty())
5392 return;
5393
5394 *num_overridden = Methods.size();
5395 *overridden = new CXCursor [Methods.size()];
5396 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005397 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005398}
5399
5400void clang_disposeOverriddenCursors(CXCursor *overridden) {
5401 delete [] overridden;
5402}
5403
Douglas Gregorecdcb882010-10-20 22:00:55 +00005404CXFile clang_getIncludedFile(CXCursor cursor) {
5405 if (cursor.kind != CXCursor_InclusionDirective)
5406 return 0;
5407
5408 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5409 return (void *)ID->getFile();
5410}
5411
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005412} // end: extern "C"
5413
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005414
5415//===----------------------------------------------------------------------===//
5416// C++ AST instrospection.
5417//===----------------------------------------------------------------------===//
5418
5419extern "C" {
5420unsigned clang_CXXMethod_isStatic(CXCursor C) {
5421 if (!clang_isDeclaration(C.kind))
5422 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005423
5424 CXXMethodDecl *Method = 0;
5425 Decl *D = cxcursor::getCursorDecl(C);
5426 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5427 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5428 else
5429 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5430 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005431}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005432
Douglas Gregor211924b2011-05-12 15:17:24 +00005433unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5434 if (!clang_isDeclaration(C.kind))
5435 return 0;
5436
5437 CXXMethodDecl *Method = 0;
5438 Decl *D = cxcursor::getCursorDecl(C);
5439 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5440 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5441 else
5442 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5443 return (Method && Method->isVirtual()) ? 1 : 0;
5444}
5445
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005446} // end: extern "C"
5447
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005448//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005449// Attribute introspection.
5450//===----------------------------------------------------------------------===//
5451
5452extern "C" {
5453CXType clang_getIBOutletCollectionType(CXCursor C) {
5454 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005455 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005456
5457 IBOutletCollectionAttr *A =
5458 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5459
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005460 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005461}
5462} // end: extern "C"
5463
5464//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005465// Inspecting memory usage.
5466//===----------------------------------------------------------------------===//
5467
Ted Kremenekf7870022011-04-20 16:41:07 +00005468typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005469
Ted Kremenekf7870022011-04-20 16:41:07 +00005470static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5471 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005472 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005473 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005474 entries.push_back(entry);
5475}
5476
5477extern "C" {
5478
Ted Kremenekf7870022011-04-20 16:41:07 +00005479const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005480 const char *str = "";
5481 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005482 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005483 str = "ASTContext: expressions, declarations, and types";
5484 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005485 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005486 str = "ASTContext: identifiers";
5487 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005488 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005489 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005490 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005491 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005492 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005493 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005494 case CXTUResourceUsage_SourceManagerContentCache:
5495 str = "SourceManager: content cache allocator";
5496 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005497 case CXTUResourceUsage_AST_SideTables:
5498 str = "ASTContext: side tables";
5499 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005500 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5501 str = "SourceManager: malloc'ed memory buffers";
5502 break;
5503 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5504 str = "SourceManager: mmap'ed memory buffers";
5505 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005506 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5507 str = "ExternalASTSource: malloc'ed memory buffers";
5508 break;
5509 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5510 str = "ExternalASTSource: mmap'ed memory buffers";
5511 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005512 case CXTUResourceUsage_Preprocessor:
5513 str = "Preprocessor: malloc'ed memory";
5514 break;
5515 case CXTUResourceUsage_PreprocessingRecord:
5516 str = "Preprocessor: PreprocessingRecord";
5517 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005518 case CXTUResourceUsage_SourceManager_DataStructures:
5519 str = "SourceManager: data structures and tables";
5520 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005521 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5522 str = "Preprocessor: header search tables";
5523 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005524 }
5525 return str;
5526}
5527
Ted Kremenekf7870022011-04-20 16:41:07 +00005528CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005529 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005530 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005531 return usage;
5532 }
5533
5534 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5535 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5536 ASTContext &astContext = astUnit->getASTContext();
5537
5538 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005539 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005540 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005541
5542 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005543 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005544 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5545
5546 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005547 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005548 (unsigned long) astContext.Selectors.getTotalMemory());
5549
Ted Kremenekba29bd22011-04-28 04:53:38 +00005550 // How much memory is used by ASTContext's side tables?
5551 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5552 (unsigned long) astContext.getSideTableAllocatedMemory());
5553
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005554 // How much memory is used for caching global code completion results?
5555 unsigned long completionBytes = 0;
5556 if (GlobalCodeCompletionAllocator *completionAllocator =
5557 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005558 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005559 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005560 createCXTUResourceUsageEntry(*entries,
5561 CXTUResourceUsage_GlobalCompletionResults,
5562 completionBytes);
5563
5564 // How much memory is being used by SourceManager's content cache?
5565 createCXTUResourceUsageEntry(*entries,
5566 CXTUResourceUsage_SourceManagerContentCache,
5567 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005568
5569 // How much memory is being used by the MemoryBuffer's in SourceManager?
5570 const SourceManager::MemoryBufferSizes &srcBufs =
5571 astUnit->getSourceManager().getMemoryBufferSizes();
5572
5573 createCXTUResourceUsageEntry(*entries,
5574 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5575 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005576 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005577 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5578 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005579 createCXTUResourceUsageEntry(*entries,
5580 CXTUResourceUsage_SourceManager_DataStructures,
5581 (unsigned long) astContext.getSourceManager()
5582 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005583
5584 // How much memory is being used by the ExternalASTSource?
5585 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5586 const ExternalASTSource::MemoryBufferSizes &sizes =
5587 esrc->getMemoryBufferSizes();
5588
5589 createCXTUResourceUsageEntry(*entries,
5590 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5591 (unsigned long) sizes.malloc_bytes);
5592 createCXTUResourceUsageEntry(*entries,
5593 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5594 (unsigned long) sizes.mmap_bytes);
5595 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005596
5597 // How much memory is being used by the Preprocessor?
5598 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005599 createCXTUResourceUsageEntry(*entries,
5600 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005601 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005602
5603 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5604 createCXTUResourceUsageEntry(*entries,
5605 CXTUResourceUsage_PreprocessingRecord,
5606 pRec->getTotalMemory());
5607 }
5608
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005609 createCXTUResourceUsageEntry(*entries,
5610 CXTUResourceUsage_Preprocessor_HeaderSearch,
5611 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005612
Ted Kremenekf7870022011-04-20 16:41:07 +00005613 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005614 (unsigned) entries->size(),
5615 entries->size() ? &(*entries)[0] : 0 };
5616 entries.take();
5617 return usage;
5618}
5619
Ted Kremenekf7870022011-04-20 16:41:07 +00005620void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005621 if (usage.data)
5622 delete (MemUsageEntries*) usage.data;
5623}
5624
5625} // end extern "C"
5626
Douglas Gregor6df78732011-05-05 20:27:22 +00005627void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5628 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5629 for (unsigned I = 0; I != Usage.numEntries; ++I)
5630 fprintf(stderr, " %s: %lu\n",
5631 clang_getTUResourceUsageName(Usage.entries[I].kind),
5632 Usage.entries[I].amount);
5633
5634 clang_disposeCXTUResourceUsage(Usage);
5635}
5636
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005637//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005638// Misc. utility functions.
5639//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005640
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005641/// Default to using an 8 MB stack size on "safety" threads.
5642static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005643
5644namespace clang {
5645
5646bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005647 void (*Fn)(void*), void *UserData,
5648 unsigned Size) {
5649 if (!Size)
5650 Size = GetSafetyThreadStackSize();
5651 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005652 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5653 return CRC.RunSafely(Fn, UserData);
5654}
5655
5656unsigned GetSafetyThreadStackSize() {
5657 return SafetyStackThreadSize;
5658}
5659
5660void SetSafetyThreadStackSize(unsigned Value) {
5661 SafetyStackThreadSize = Value;
5662}
5663
5664}
5665
Ted Kremenek04bb7162010-01-22 22:44:15 +00005666extern "C" {
5667
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005668CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005669 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005670}
5671
5672} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005673