blob: 51749d7849b6b2b14184f92498acd0c7c376da02 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000033#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000034#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000035#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000036#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000037#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000038#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000039#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000040#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000041#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000042#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000043#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000044#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000045#include "llvm/Support/Mutex.h"
46#include "llvm/Support/Program.h"
47#include "llvm/Support/Signals.h"
48#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000049#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000050
Steve Naroff50398192009-08-28 15:28:48 +000051using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000052using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000053using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000054
Ted Kremeneka60ed472010-11-16 08:15:36 +000055static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
56 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
61 return D;
62}
63
Douglas Gregor33e9abd2010-01-22 19:49:59 +000064/// \brief The result of comparing two source ranges.
65enum RangeComparisonResult {
66 /// \brief Either the ranges overlap or one of the ranges is invalid.
67 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000068
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 /// \brief The first range ends before the second range starts.
70 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000071
Douglas Gregor33e9abd2010-01-22 19:49:59 +000072 /// \brief The first range starts after the second range ends.
73 RangeAfter
74};
75
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000078static RangeComparisonResult RangeCompare(SourceManager &SM,
79 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000080 SourceRange R2) {
81 assert(R1.isValid() && "First range is invalid?");
82 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000083 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000084 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000085 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000086 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000087 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000088 return RangeAfter;
89 return RangeOverlap;
90}
91
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000092/// \brief Determine if a source location falls within, before, or after a
93/// a given source range.
94static RangeComparisonResult LocationCompare(SourceManager &SM,
95 SourceLocation L, SourceRange R) {
96 assert(R.isValid() && "First range is invalid?");
97 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000098 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000099 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000100 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
101 return RangeBefore;
102 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
103 return RangeAfter;
104 return RangeOverlap;
105}
106
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107/// \brief Translate a Clang source range into a CIndex source range.
108///
109/// Clang internally represents ranges where the end location points to the
110/// start of the token at the end. However, for external clients it is more
111/// useful to have a CXSourceRange be a proper half-open interval. This routine
112/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000113CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000117 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000119 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000120 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000121 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000122 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000123 EndLoc = EndLoc.getFileLocWithOffset(Length);
124 }
125
126 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
127 R.getBegin().getRawEncoding(),
128 EndLoc.getRawEncoding() };
129 return Result;
130}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000131
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000133// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000134//===----------------------------------------------------------------------===//
135
Steve Naroff89922f82009-08-31 00:59:03 +0000136namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000137
138class VisitorJob {
139public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000140 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000141 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000142 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000143 ExplicitTemplateArgsVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000144 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000145 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000146 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000148 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000149 CXCursor parent;
150 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000151 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
152 : parent(C), K(k) {
153 data[0] = d1;
154 data[1] = d2;
155 data[2] = d3;
156 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000157public:
158 Kind getKind() const { return K; }
159 const CXCursor &getParent() const { return parent; }
160 static bool classof(VisitorJob *VJ) { return true; }
161};
162
Chris Lattner5f9e2722011-07-23 10:55:15 +0000163typedef SmallVector<VisitorJob, 10> VisitorWorkList;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000164
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000167 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000168{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000169 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000170 CXTranslationUnit TU;
171 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176 /// \brief The declaration that serves at the parent of any statement or
177 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000178 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000183 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000186 /// \brief Whether we should visit the preprocessing record entries last,
187 /// after visiting other declarations.
188 bool VisitPreprocessorLast;
189
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 /// \brief When valid, a source range to which the cursor should restrict
191 /// its search.
192 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000194 // FIXME: Eventually remove. This part of a hack to support proper
195 // iteration over all Decls contained lexically within an ObjC container.
196 DeclContext::decl_iterator *DI_current;
197 DeclContext::decl_iterator DE_current;
198
Ted Kremenekd1ded662010-11-15 23:31:32 +0000199 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000200 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
201 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
206 /// \brief Determine whether this particular source range comes before, comes
207 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000209 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
211
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000212 class SetParentRAII {
213 CXCursor &Parent;
214 Decl *&StmtParent;
215 CXCursor OldParent;
216
217 public:
218 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
219 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
220 {
221 Parent = NewParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225
226 ~SetParentRAII() {
227 Parent = OldParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231 };
232
Steve Naroff89922f82009-08-31 00:59:03 +0000233public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000234 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
235 CXClientData ClientData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000236 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000238 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
239 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor08e0bc12011-09-10 00:09:20 +0000240 VisitPreprocessorLast(VisitPreprocessorLast),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000241 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 {
243 Parent.kind = CXCursor_NoDeclFound;
244 Parent.data[0] = 0;
245 Parent.data[1] = 0;
246 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000249
Ted Kremenekd1ded662010-11-15 23:31:32 +0000250 ~CursorVisitor() {
251 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000252 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000253 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
254 delete *I;
255 }
256 }
257
Ted Kremeneka60ed472010-11-16 08:15:36 +0000258 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
259 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000260
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000261 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000262
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000263 bool visitPreprocessedEntitiesInRegion();
264
265 template<typename InputIterator>
266 bool visitPreprocessedEntitiesInRegion(InputIterator First,
267 InputIterator Last);
268
269 template<typename InputIterator>
270 bool visitPreprocessedEntities(InputIterator First, InputIterator Last);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000271
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000273
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000274 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000275 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000276 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000277 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000278 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000279 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000280 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000281 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
282 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000283 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000284 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000285 bool VisitClassTemplatePartialSpecializationDecl(
286 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000287 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitEnumConstantDecl(EnumConstantDecl *D);
289 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
290 bool VisitFunctionDecl(FunctionDecl *ND);
291 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000292 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000293 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000294 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000295 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000296 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
298 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
299 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
300 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000301 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000302 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
303 bool VisitObjCImplDecl(ObjCImplDecl *D);
304 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
305 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000306 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
307 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
308 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000309 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000310 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000311 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000312 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000313 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000314 bool VisitUsingDecl(UsingDecl *D);
315 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
316 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000317
Douglas Gregor01829d32010-08-31 14:41:23 +0000318 // Name visitor
319 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000320 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000321 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000322
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000323 // Template visitors
324 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000325 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000326 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
327
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000328 // Type visitors
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000329#define ABSTRACT_TYPELOC(CLASS, PARENT)
330#define TYPELOC(CLASS, PARENT) \
331 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
332#include "clang/AST/TypeLocNodes.def"
333
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000334 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000335 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000336 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
337
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000338 // Data-recursive visitor functions.
339 bool IsInRegionOfInterest(CXCursor C);
340 bool RunVisitorWorkList(VisitorWorkList &WL);
341 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000342 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000343};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Ted Kremenekab188932010-01-05 19:32:54 +0000345} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000346
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000347static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000348static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
349
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000350
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000351RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000352 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000353}
354
Douglas Gregorb1373d02010-01-20 20:59:29 +0000355/// \brief Visit the given cursor and, if requested by the visitor,
356/// its children.
357///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000358/// \param Cursor the cursor to visit.
359///
360/// \param CheckRegionOfInterest if true, then the caller already checked that
361/// this cursor is within the region of interest.
362///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \returns true if the visitation should be aborted, false if it
364/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000366 if (clang_isInvalid(Cursor.kind))
367 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000368
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369 if (clang_isDeclaration(Cursor.kind)) {
370 Decl *D = getCursorDecl(Cursor);
371 assert(D && "Invalid declaration cursor");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 if (D->isImplicit())
373 return false;
374 }
375
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000376 // If we have a range of interest, and this cursor doesn't intersect with it,
377 // we're done.
378 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000379 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000380 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381 return false;
382 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000383
Douglas Gregorb1373d02010-01-20 20:59:29 +0000384 switch (Visitor(Cursor, Parent, ClientData)) {
385 case CXChildVisit_Break:
386 return true;
387
388 case CXChildVisit_Continue:
389 return false;
390
391 case CXChildVisit_Recurse:
392 return VisitChildren(Cursor);
393 }
394
Douglas Gregorfd643772010-01-25 16:45:46 +0000395 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396}
397
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000398bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000399 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000400 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000401
402 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000403 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
404
405 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
406 // If we would only look at local declarations but we have a region of
407 // interest, check whether that region of interest is in the main file.
408 // If not, we should traverse all declarations.
409 // FIXME: My kingdom for a proper binary search approach to finding
410 // cursors!
411 std::pair<FileID, unsigned> Location
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000412 = AU->getSourceManager().getDecomposedExpansionLoc(
Douglas Gregor32038bb2010-12-21 19:07:48 +0000413 RegionOfInterest.getBegin());
414 if (Location.first != AU->getSourceManager().getMainFileID())
415 OnlyLocalDecls = false;
416 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000417
Douglas Gregor89d99802010-11-30 06:16:57 +0000418 PreprocessingRecord::iterator StartEntity, EndEntity;
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000419 if (OnlyLocalDecls && AU->pp_entity_begin() != AU->pp_entity_end())
420 return visitPreprocessedEntitiesInRegion(AU->pp_entity_begin(),
421 AU->pp_entity_end());
422 else
423 return visitPreprocessedEntitiesInRegion(PPRec.begin(), PPRec.end());
424}
425
426template<typename InputIterator>
427bool CursorVisitor::visitPreprocessedEntitiesInRegion(InputIterator First,
428 InputIterator Last) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429 // There is no region of interest; we have to walk everything.
430 if (RegionOfInterest.isInvalid())
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000431 return visitPreprocessedEntities(First, Last);
432
Douglas Gregor788f5a12010-03-20 00:41:21 +0000433 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000434 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000435 std::pair<FileID, unsigned> Begin
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000436 = SM.getDecomposedExpansionLoc(RegionOfInterest.getBegin());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000437 std::pair<FileID, unsigned> End
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000438 = SM.getDecomposedExpansionLoc(RegionOfInterest.getEnd());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000439
440 // The region of interest spans files; we have to walk everything.
441 if (Begin.first != End.first)
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000442 return visitPreprocessedEntities(First, Last);
443
Douglas Gregor788f5a12010-03-20 00:41:21 +0000444 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000445 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000446 if (ByFileMap.empty()) {
447 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000448 for (; First != Last; ++First) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000449 std::pair<FileID, unsigned> P
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000450 = SM.getDecomposedExpansionLoc((*First)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000451
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000452 ByFileMap[P.first].push_back(*First);
453 }
454 }
455
456 return visitPreprocessedEntities(ByFileMap[Begin.first].begin(),
457 ByFileMap[Begin.first].end());
458}
459
460template<typename InputIterator>
461bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
462 InputIterator Last) {
463 for (; First != Last; ++First) {
464 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
465 if (Visit(MakeMacroExpansionCursor(ME, TU)))
466 return true;
467
468 continue;
469 }
470
471 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
472 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
473 return true;
474
475 continue;
476 }
477
478 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
479 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
480 return true;
481
482 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000483 }
484 }
485
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000486 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000487}
488
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000490///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000491/// \returns true if the visitation should be aborted, false if it
492/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000493bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000494 if (clang_isReference(Cursor.kind) &&
495 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000496 // By definition, references have no children.
497 return false;
498 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000499
500 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000502 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504 if (clang_isDeclaration(Cursor.kind)) {
505 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000506 if (!D)
507 return false;
508
Ted Kremenek539311e2010-02-18 18:47:01 +0000509 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000510 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000512 if (clang_isStatement(Cursor.kind)) {
513 if (Stmt *S = getCursorStmt(Cursor))
514 return Visit(S);
515
516 return false;
517 }
518
519 if (clang_isExpression(Cursor.kind)) {
520 if (Expr *E = getCursorExpr(Cursor))
521 return Visit(E);
522
523 return false;
524 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000525
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000527 CXTranslationUnit tu = getCursorTU(Cursor);
528 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000529
530 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
531 for (unsigned I = 0; I != 2; ++I) {
532 if (VisitOrder[I]) {
533 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
534 RegionOfInterest.isInvalid()) {
535 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
536 TLEnd = CXXUnit->top_level_end();
537 TL != TLEnd; ++TL) {
538 if (Visit(MakeCXCursor(*TL, tu), true))
539 return true;
540 }
541 } else if (VisitDeclContext(
542 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000543 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000544 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000545 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000546
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000547 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000548 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
549 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000550 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000551
Douglas Gregor7b691f332010-01-20 21:13:59 +0000552 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000554
Douglas Gregorc314aa42011-03-02 19:17:03 +0000555 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
556 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
557 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
558 return Visit(BaseTSInfo->getTypeLoc());
559 }
560 }
561 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000562
563 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
564 IBOutletCollectionAttr *A =
565 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
566 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
567 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
568 A->getInterfaceLoc(), TU));
569 }
570
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 return false;
573}
574
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000575bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000576 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
577 if (Visit(TSInfo->getTypeLoc()))
578 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000579
Ted Kremenek664cffd2010-07-22 11:30:19 +0000580 if (Stmt *Body = B->getBody())
581 return Visit(MakeCXCursor(Body, StmtParent, TU));
582
583 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000584}
585
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000586llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
587 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000588 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000589 if (Range.isInvalid())
590 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000591
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000592 switch (CompareRegionOfInterest(Range)) {
593 case RangeBefore:
594 // This declaration comes before the region of interest; skip it.
595 return llvm::Optional<bool>();
596
597 case RangeAfter:
598 // This declaration comes after the region of interest; we're done.
599 return false;
600
601 case RangeOverlap:
602 // This declaration overlaps the region of interest; visit it.
603 break;
604 }
605 }
606 return true;
607}
608
609bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
610 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
611
612 // FIXME: Eventually remove. This part of a hack to support proper
613 // iteration over all Decls contained lexically within an ObjC container.
614 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
615 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
616
617 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000618 Decl *D = *I;
619 if (D->getLexicalDeclContext() != DC)
620 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000621 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000622 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
623 if (!V.hasValue())
624 continue;
625 if (!V.getValue())
626 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000627 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000628 return true;
629 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000630 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000631}
632
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
634 llvm_unreachable("Translation units are visited directly by Visit()");
635 return false;
636}
637
Richard Smith162e1c12011-04-15 14:24:37 +0000638bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
639 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
640 return Visit(TSInfo->getTypeLoc());
641
642 return false;
643}
644
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000645bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
646 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
647 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000648
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000649 return false;
650}
651
652bool CursorVisitor::VisitTagDecl(TagDecl *D) {
653 return VisitDeclContext(D);
654}
655
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000656bool CursorVisitor::VisitClassTemplateSpecializationDecl(
657 ClassTemplateSpecializationDecl *D) {
658 bool ShouldVisitBody = false;
659 switch (D->getSpecializationKind()) {
660 case TSK_Undeclared:
661 case TSK_ImplicitInstantiation:
662 // Nothing to visit
663 return false;
664
665 case TSK_ExplicitInstantiationDeclaration:
666 case TSK_ExplicitInstantiationDefinition:
667 break;
668
669 case TSK_ExplicitSpecialization:
670 ShouldVisitBody = true;
671 break;
672 }
673
674 // Visit the template arguments used in the specialization.
675 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
676 TypeLoc TL = SpecType->getTypeLoc();
677 if (TemplateSpecializationTypeLoc *TSTLoc
678 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
679 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
680 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
681 return true;
682 }
683 }
684
685 if (ShouldVisitBody && VisitCXXRecordDecl(D))
686 return true;
687
688 return false;
689}
690
Douglas Gregor74dbe642010-08-31 19:31:58 +0000691bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
692 ClassTemplatePartialSpecializationDecl *D) {
693 // FIXME: Visit the "outer" template parameter lists on the TagDecl
694 // before visiting these template parameters.
695 if (VisitTemplateParameters(D->getTemplateParameters()))
696 return true;
697
698 // Visit the partial specialization arguments.
699 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
700 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
701 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
702 return true;
703
704 return VisitCXXRecordDecl(D);
705}
706
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000707bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000708 // Visit the default argument.
709 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
710 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
711 if (Visit(DefArg->getTypeLoc()))
712 return true;
713
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000714 return false;
715}
716
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000717bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
718 if (Expr *Init = D->getInitExpr())
719 return Visit(MakeCXCursor(Init, StmtParent, TU));
720 return false;
721}
722
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000723bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
724 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
725 if (Visit(TSInfo->getTypeLoc()))
726 return true;
727
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000728 // Visit the nested-name-specifier, if present.
729 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
730 if (VisitNestedNameSpecifierLoc(QualifierLoc))
731 return true;
732
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000733 return false;
734}
735
Douglas Gregora67e03f2010-09-09 21:42:20 +0000736/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000737static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
738 CXXCtorInitializer const * const *X
739 = static_cast<CXXCtorInitializer const * const *>(Xp);
740 CXXCtorInitializer const * const *Y
741 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000742
743 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
744 return -1;
745 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
746 return 1;
747 else
748 return 0;
749}
750
Douglas Gregorb1373d02010-01-20 20:59:29 +0000751bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000752 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
753 // Visit the function declaration's syntactic components in the order
754 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000755 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000756 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
757
758 // If we have a function declared directly (without the use of a typedef),
759 // visit just the return type. Otherwise, just visit the function's type
760 // now.
761 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
762 (!FTL && Visit(TL)))
763 return true;
764
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000765 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000766 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
767 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000768 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000769
770 // Visit the declaration name.
771 if (VisitDeclarationNameInfo(ND->getNameInfo()))
772 return true;
773
774 // FIXME: Visit explicitly-specified template arguments!
775
776 // Visit the function parameters, if we have a function type.
777 if (FTL && VisitFunctionTypeLoc(*FTL, true))
778 return true;
779
780 // FIXME: Attributes?
781 }
782
Sean Hunt10620eb2011-05-06 20:44:56 +0000783 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000784 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
785 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000786 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000787 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
788 IEnd = Constructor->init_end();
789 I != IEnd; ++I) {
790 if (!(*I)->isWritten())
791 continue;
792
793 WrittenInits.push_back(*I);
794 }
795
796 // Sort the initializers in source order
797 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000798 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000799
800 // Visit the initializers in source order
801 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000802 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000803 if (Init->isAnyMemberInitializer()) {
804 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000805 Init->getMemberLocation(), TU)))
806 return true;
807 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
808 if (Visit(BaseInfo->getTypeLoc()))
809 return true;
810 }
811
812 // Visit the initializer value.
813 if (Expr *Initializer = Init->getInit())
814 if (Visit(MakeCXCursor(Initializer, ND, TU)))
815 return true;
816 }
817 }
818
819 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
820 return true;
821 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000822
Douglas Gregorb1373d02010-01-20 20:59:29 +0000823 return false;
824}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000825
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000826bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
827 if (VisitDeclaratorDecl(D))
828 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000829
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000830 if (Expr *BitWidth = D->getBitWidth())
831 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000833 return false;
834}
835
836bool CursorVisitor::VisitVarDecl(VarDecl *D) {
837 if (VisitDeclaratorDecl(D))
838 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 if (Expr *Init = D->getInit())
841 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 return false;
844}
845
Douglas Gregor84b51d72010-09-01 20:16:53 +0000846bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
847 if (VisitDeclaratorDecl(D))
848 return true;
849
850 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
851 if (Expr *DefArg = D->getDefaultArgument())
852 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
853
854 return false;
855}
856
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000857bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
858 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
859 // before visiting these template parameters.
860 if (VisitTemplateParameters(D->getTemplateParameters()))
861 return true;
862
863 return VisitFunctionDecl(D->getTemplatedDecl());
864}
865
Douglas Gregor39d6f072010-08-31 19:02:00 +0000866bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
867 // FIXME: Visit the "outer" template parameter lists on the TagDecl
868 // before visiting these template parameters.
869 if (VisitTemplateParameters(D->getTemplateParameters()))
870 return true;
871
872 return VisitCXXRecordDecl(D->getTemplatedDecl());
873}
874
Douglas Gregor84b51d72010-09-01 20:16:53 +0000875bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
876 if (VisitTemplateParameters(D->getTemplateParameters()))
877 return true;
878
879 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
880 VisitTemplateArgumentLoc(D->getDefaultArgument()))
881 return true;
882
883 return false;
884}
885
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000886bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000887 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
888 if (Visit(TSInfo->getTypeLoc()))
889 return true;
890
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000891 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000892 PEnd = ND->param_end();
893 P != PEnd; ++P) {
894 if (Visit(MakeCXCursor(*P, TU)))
895 return true;
896 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000897
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000898 if (ND->isThisDeclarationADefinition() &&
899 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
900 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000901
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000902 return false;
903}
904
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000905namespace {
906 struct ContainerDeclsSort {
907 SourceManager &SM;
908 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
909 bool operator()(Decl *A, Decl *B) {
910 SourceLocation L_A = A->getLocStart();
911 SourceLocation L_B = B->getLocStart();
912 assert(L_A.isValid() && L_B.isValid());
913 return SM.isBeforeInTranslationUnit(L_A, L_B);
914 }
915 };
916}
917
Douglas Gregora59e3902010-01-21 23:27:09 +0000918bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000919 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
920 // an @implementation can lexically contain Decls that are not properly
921 // nested in the AST. When we identify such cases, we need to retrofit
922 // this nesting here.
923 if (!DI_current)
924 return VisitDeclContext(D);
925
926 // Scan the Decls that immediately come after the container
927 // in the current DeclContext. If any fall within the
928 // container's lexical region, stash them into a vector
929 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000930 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000931 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000932 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000933 if (EndLoc.isValid()) {
934 DeclContext::decl_iterator next = *DI_current;
935 while (++next != DE_current) {
936 Decl *D_next = *next;
937 if (!D_next)
938 break;
939 SourceLocation L = D_next->getLocStart();
940 if (!L.isValid())
941 break;
942 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
943 *DI_current = next;
944 DeclsInContainer.push_back(D_next);
945 continue;
946 }
947 break;
948 }
949 }
950
951 // The common case.
952 if (DeclsInContainer.empty())
953 return VisitDeclContext(D);
954
955 // Get all the Decls in the DeclContext, and sort them with the
956 // additional ones we've collected. Then visit them.
957 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
958 I!=E; ++I) {
959 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000960 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
961 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000962 continue;
963 DeclsInContainer.push_back(subDecl);
964 }
965
966 // Now sort the Decls so that they appear in lexical order.
967 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
968 ContainerDeclsSort(SM));
969
970 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000971 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000972 E = DeclsInContainer.end(); I != E; ++I) {
973 CXCursor Cursor = MakeCXCursor(*I, TU);
974 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
975 if (!V.hasValue())
976 continue;
977 if (!V.getValue())
978 return false;
979 if (Visit(Cursor, true))
980 return true;
981 }
982 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000983}
984
Douglas Gregorb1373d02010-01-20 20:59:29 +0000985bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000986 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
987 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000990 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
991 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
992 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000993 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000994 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995
Douglas Gregora59e3902010-01-21 23:27:09 +0000996 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000997}
998
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000999bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1000 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1001 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1002 E = PID->protocol_end(); I != E; ++I, ++PL)
1003 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1004 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001005
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001006 return VisitObjCContainerDecl(PID);
1007}
1008
Ted Kremenek23173d72010-05-18 21:09:07 +00001009bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001010 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001011 return true;
1012
Ted Kremenek23173d72010-05-18 21:09:07 +00001013 // FIXME: This implements a workaround with @property declarations also being
1014 // installed in the DeclContext for the @interface. Eventually this code
1015 // should be removed.
1016 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1017 if (!CDecl || !CDecl->IsClassExtension())
1018 return false;
1019
1020 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1021 if (!ID)
1022 return false;
1023
1024 IdentifierInfo *PropertyId = PD->getIdentifier();
1025 ObjCPropertyDecl *prevDecl =
1026 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1027
1028 if (!prevDecl)
1029 return false;
1030
1031 // Visit synthesized methods since they will be skipped when visiting
1032 // the @interface.
1033 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001034 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001035 if (Visit(MakeCXCursor(MD, TU)))
1036 return true;
1037
1038 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001039 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001040 if (Visit(MakeCXCursor(MD, TU)))
1041 return true;
1042
1043 return false;
1044}
1045
Douglas Gregorb1373d02010-01-20 20:59:29 +00001046bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001047 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001048 if (D->getSuperClass() &&
1049 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001050 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001051 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001052 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001053
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001054 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1055 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1056 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001057 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001058 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001059
Douglas Gregora59e3902010-01-21 23:27:09 +00001060 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001061}
1062
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1064 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001065}
1066
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001067bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001068 // 'ID' could be null when dealing with invalid code.
1069 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1070 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1071 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001072
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001073 return VisitObjCImplDecl(D);
1074}
1075
1076bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1077#if 0
1078 // Issue callbacks for super class.
1079 // FIXME: No source location information!
1080 if (D->getSuperClass() &&
1081 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001082 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001083 TU)))
1084 return true;
1085#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001086
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001087 return VisitObjCImplDecl(D);
1088}
1089
1090bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1091 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1092 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1093 E = D->protocol_end();
1094 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001095 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001096 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001097
1098 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001099}
1100
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001101bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001102 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1103 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001104 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001105 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001106}
1107
Douglas Gregora4ffd852010-11-17 01:03:52 +00001108bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1109 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1110 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1111
1112 return false;
1113}
1114
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001115bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1116 return VisitDeclContext(D);
1117}
1118
Douglas Gregor69319002010-08-31 23:48:11 +00001119bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001121 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1122 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001123 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001124
1125 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1126 D->getTargetNameLoc(), TU));
1127}
1128
Douglas Gregor7e242562010-09-01 19:52:22 +00001129bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001130 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001131 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1132 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001134 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001135
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001136 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1137 return true;
1138
Douglas Gregor7e242562010-09-01 19:52:22 +00001139 return VisitDeclarationNameInfo(D->getNameInfo());
1140}
1141
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001142bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001143 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001144 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1145 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001146 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001147
1148 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1149 D->getIdentLocation(), TU));
1150}
1151
Douglas Gregor7e242562010-09-01 19:52:22 +00001152bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001153 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001154 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1155 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001156 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001157 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001158
Douglas Gregor7e242562010-09-01 19:52:22 +00001159 return VisitDeclarationNameInfo(D->getNameInfo());
1160}
1161
1162bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1163 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001164 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001165 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1166 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001167 return true;
1168
Douglas Gregor7e242562010-09-01 19:52:22 +00001169 return false;
1170}
1171
Douglas Gregor01829d32010-08-31 14:41:23 +00001172bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1173 switch (Name.getName().getNameKind()) {
1174 case clang::DeclarationName::Identifier:
1175 case clang::DeclarationName::CXXLiteralOperatorName:
1176 case clang::DeclarationName::CXXOperatorName:
1177 case clang::DeclarationName::CXXUsingDirective:
1178 return false;
1179
1180 case clang::DeclarationName::CXXConstructorName:
1181 case clang::DeclarationName::CXXDestructorName:
1182 case clang::DeclarationName::CXXConversionFunctionName:
1183 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1184 return Visit(TSInfo->getTypeLoc());
1185 return false;
1186
1187 case clang::DeclarationName::ObjCZeroArgSelector:
1188 case clang::DeclarationName::ObjCOneArgSelector:
1189 case clang::DeclarationName::ObjCMultiArgSelector:
1190 // FIXME: Per-identifier location info?
1191 return false;
1192 }
1193
1194 return false;
1195}
1196
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001197bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1198 SourceRange Range) {
1199 // FIXME: This whole routine is a hack to work around the lack of proper
1200 // source information in nested-name-specifiers (PR5791). Since we do have
1201 // a beginning source location, we can visit the first component of the
1202 // nested-name-specifier, if it's a single-token component.
1203 if (!NNS)
1204 return false;
1205
1206 // Get the first component in the nested-name-specifier.
1207 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1208 NNS = Prefix;
1209
1210 switch (NNS->getKind()) {
1211 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001212 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1213 TU));
1214
Douglas Gregor14aba762011-02-24 02:36:08 +00001215 case NestedNameSpecifier::NamespaceAlias:
1216 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1217 Range.getBegin(), TU));
1218
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001219 case NestedNameSpecifier::TypeSpec: {
1220 // If the type has a form where we know that the beginning of the source
1221 // range matches up with a reference cursor. Visit the appropriate reference
1222 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001223 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001224 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1225 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1226 if (const TagType *Tag = dyn_cast<TagType>(T))
1227 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1228 if (const TemplateSpecializationType *TST
1229 = dyn_cast<TemplateSpecializationType>(T))
1230 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1231 break;
1232 }
1233
1234 case NestedNameSpecifier::TypeSpecWithTemplate:
1235 case NestedNameSpecifier::Global:
1236 case NestedNameSpecifier::Identifier:
1237 break;
1238 }
1239
1240 return false;
1241}
1242
Douglas Gregordc355712011-02-25 00:36:19 +00001243bool
1244CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001245 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001246 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1247 Qualifiers.push_back(Qualifier);
1248
1249 while (!Qualifiers.empty()) {
1250 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1251 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1252 switch (NNS->getKind()) {
1253 case NestedNameSpecifier::Namespace:
1254 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001255 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001256 TU)))
1257 return true;
1258
1259 break;
1260
1261 case NestedNameSpecifier::NamespaceAlias:
1262 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001263 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001264 TU)))
1265 return true;
1266
1267 break;
1268
1269 case NestedNameSpecifier::TypeSpec:
1270 case NestedNameSpecifier::TypeSpecWithTemplate:
1271 if (Visit(Q.getTypeLoc()))
1272 return true;
1273
1274 break;
1275
1276 case NestedNameSpecifier::Global:
1277 case NestedNameSpecifier::Identifier:
1278 break;
1279 }
1280 }
1281
1282 return false;
1283}
1284
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001285bool CursorVisitor::VisitTemplateParameters(
1286 const TemplateParameterList *Params) {
1287 if (!Params)
1288 return false;
1289
1290 for (TemplateParameterList::const_iterator P = Params->begin(),
1291 PEnd = Params->end();
1292 P != PEnd; ++P) {
1293 if (Visit(MakeCXCursor(*P, TU)))
1294 return true;
1295 }
1296
1297 return false;
1298}
1299
Douglas Gregor0b36e612010-08-31 20:37:03 +00001300bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1301 switch (Name.getKind()) {
1302 case TemplateName::Template:
1303 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1304
1305 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001306 // Visit the overloaded template set.
1307 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1308 return true;
1309
Douglas Gregor0b36e612010-08-31 20:37:03 +00001310 return false;
1311
1312 case TemplateName::DependentTemplate:
1313 // FIXME: Visit nested-name-specifier.
1314 return false;
1315
1316 case TemplateName::QualifiedTemplate:
1317 // FIXME: Visit nested-name-specifier.
1318 return Visit(MakeCursorTemplateRef(
1319 Name.getAsQualifiedTemplateName()->getDecl(),
1320 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001321
1322 case TemplateName::SubstTemplateTemplateParm:
1323 return Visit(MakeCursorTemplateRef(
1324 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1325 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001326
1327 case TemplateName::SubstTemplateTemplateParmPack:
1328 return Visit(MakeCursorTemplateRef(
1329 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1330 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001331 }
1332
1333 return false;
1334}
1335
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001336bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1337 switch (TAL.getArgument().getKind()) {
1338 case TemplateArgument::Null:
1339 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001340 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001341 return false;
1342
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001343 case TemplateArgument::Type:
1344 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1345 return Visit(TSInfo->getTypeLoc());
1346 return false;
1347
1348 case TemplateArgument::Declaration:
1349 if (Expr *E = TAL.getSourceDeclExpression())
1350 return Visit(MakeCXCursor(E, StmtParent, TU));
1351 return false;
1352
1353 case TemplateArgument::Expression:
1354 if (Expr *E = TAL.getSourceExpression())
1355 return Visit(MakeCXCursor(E, StmtParent, TU));
1356 return false;
1357
1358 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001359 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001360 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1361 return true;
1362
Douglas Gregora7fc9012011-01-05 18:58:31 +00001363 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001364 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001365 }
1366
1367 return false;
1368}
1369
Ted Kremeneka0536d82010-05-07 01:04:29 +00001370bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1371 return VisitDeclContext(D);
1372}
1373
Douglas Gregor01829d32010-08-31 14:41:23 +00001374bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1375 return Visit(TL.getUnqualifiedLoc());
1376}
1377
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001379 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380
1381 // Some builtin types (such as Objective-C's "id", "sel", and
1382 // "Class") have associated declarations. Create cursors for those.
1383 QualType VisitType;
1384 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001385 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001387 case BuiltinType::Char_U:
1388 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001389 case BuiltinType::Char16:
1390 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001391 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392 case BuiltinType::UInt:
1393 case BuiltinType::ULong:
1394 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001395 case BuiltinType::UInt128:
1396 case BuiltinType::Char_S:
1397 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001398 case BuiltinType::WChar_U:
1399 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001400 case BuiltinType::Short:
1401 case BuiltinType::Int:
1402 case BuiltinType::Long:
1403 case BuiltinType::LongLong:
1404 case BuiltinType::Int128:
1405 case BuiltinType::Float:
1406 case BuiltinType::Double:
1407 case BuiltinType::LongDouble:
1408 case BuiltinType::NullPtr:
1409 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001410 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001411 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001412 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001413 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001414
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001415 case BuiltinType::ObjCId:
1416 VisitType = Context.getObjCIdType();
1417 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001418
1419 case BuiltinType::ObjCClass:
1420 VisitType = Context.getObjCClassType();
1421 break;
1422
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423 case BuiltinType::ObjCSel:
1424 VisitType = Context.getObjCSelType();
1425 break;
1426 }
1427
1428 if (!VisitType.isNull()) {
1429 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001430 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001431 TU));
1432 }
1433
1434 return false;
1435}
1436
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001437bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001438 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001439}
1440
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001441bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1442 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1443}
1444
1445bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001446 if (TL.isDefinition())
1447 return Visit(MakeCXCursor(TL.getDecl(), TU));
1448
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001449 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1450}
1451
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001452bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001453 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001454}
1455
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001456bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1457 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1458 return true;
1459
John McCallc12c5bb2010-05-15 11:32:37 +00001460 return false;
1461}
1462
1463bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1464 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1465 return true;
1466
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001467 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1468 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1469 TU)))
1470 return true;
1471 }
1472
1473 return false;
1474}
1475
1476bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001477 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001478}
1479
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001480bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1481 return Visit(TL.getInnerLoc());
1482}
1483
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001484bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1485 return Visit(TL.getPointeeLoc());
1486}
1487
1488bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1489 return Visit(TL.getPointeeLoc());
1490}
1491
1492bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1493 return Visit(TL.getPointeeLoc());
1494}
1495
1496bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001497 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001498}
1499
1500bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001501 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001502}
1503
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001504bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1505 return Visit(TL.getModifiedLoc());
1506}
1507
Douglas Gregor01829d32010-08-31 14:41:23 +00001508bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1509 bool SkipResultType) {
1510 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001511 return true;
1512
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001513 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001514 if (Decl *D = TL.getArg(I))
1515 if (Visit(MakeCXCursor(D, TU)))
1516 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001517
1518 return false;
1519}
1520
1521bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1522 if (Visit(TL.getElementLoc()))
1523 return true;
1524
1525 if (Expr *Size = TL.getSizeExpr())
1526 return Visit(MakeCXCursor(Size, StmtParent, TU));
1527
1528 return false;
1529}
1530
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001531bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1532 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001533 // Visit the template name.
1534 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1535 TL.getTemplateNameLoc()))
1536 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001537
1538 // Visit the template arguments.
1539 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1540 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1541 return true;
1542
1543 return false;
1544}
1545
Douglas Gregor2332c112010-01-21 20:48:56 +00001546bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1547 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1548}
1549
1550bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1551 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1552 return Visit(TSInfo->getTypeLoc());
1553
1554 return false;
1555}
1556
Sean Huntca63c202011-05-24 22:41:36 +00001557bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1558 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1559 return Visit(TSInfo->getTypeLoc());
1560
1561 return false;
1562}
1563
Douglas Gregor2494dd02011-03-01 01:34:45 +00001564bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1565 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1566 return true;
1567
1568 return false;
1569}
1570
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001571bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1572 DependentTemplateSpecializationTypeLoc TL) {
1573 // Visit the nested-name-specifier, if there is one.
1574 if (TL.getQualifierLoc() &&
1575 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1576 return true;
1577
1578 // Visit the template arguments.
1579 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1580 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1581 return true;
1582
1583 return false;
1584}
1585
Douglas Gregor9e876872011-03-01 18:12:44 +00001586bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1587 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1588 return true;
1589
1590 return Visit(TL.getNamedTypeLoc());
1591}
1592
Douglas Gregor7536dd52010-12-20 02:24:11 +00001593bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1594 return Visit(TL.getPatternLoc());
1595}
1596
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001597bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1598 if (Expr *E = TL.getUnderlyingExpr())
1599 return Visit(MakeCXCursor(E, StmtParent, TU));
1600
1601 return false;
1602}
1603
1604bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1605 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1606}
1607
1608#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1609bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1610 return Visit##PARENT##Loc(TL); \
1611}
1612
1613DEFAULT_TYPELOC_IMPL(Complex, Type)
1614DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1615DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1616DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1617DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1618DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1619DEFAULT_TYPELOC_IMPL(Vector, Type)
1620DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1621DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1622DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1623DEFAULT_TYPELOC_IMPL(Record, TagType)
1624DEFAULT_TYPELOC_IMPL(Enum, TagType)
1625DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1626DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1627DEFAULT_TYPELOC_IMPL(Auto, Type)
1628
Ted Kremenek3064ef92010-08-27 21:34:58 +00001629bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001630 // Visit the nested-name-specifier, if present.
1631 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1632 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1633 return true;
1634
Ted Kremenek3064ef92010-08-27 21:34:58 +00001635 if (D->isDefinition()) {
1636 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1637 E = D->bases_end(); I != E; ++I) {
1638 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1639 return true;
1640 }
1641 }
1642
1643 return VisitTagDecl(D);
1644}
1645
Ted Kremenek09dfa372010-02-18 05:46:33 +00001646bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001647 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1648 i != e; ++i)
1649 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001650 return true;
1651
1652 return false;
1653}
1654
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001655//===----------------------------------------------------------------------===//
1656// Data-recursive visitor methods.
1657//===----------------------------------------------------------------------===//
1658
Ted Kremenek28a71942010-11-13 00:36:47 +00001659namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001660#define DEF_JOB(NAME, DATA, KIND)\
1661class NAME : public VisitorJob {\
1662public:\
1663 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1664 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001665 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001666};
1667
1668DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1669DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001670DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001671DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001672DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1673 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001674DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001675#undef DEF_JOB
1676
1677class DeclVisit : public VisitorJob {
1678public:
1679 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1680 VisitorJob(parent, VisitorJob::DeclVisitKind,
1681 d, isFirst ? (void*) 1 : (void*) 0) {}
1682 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001683 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001684 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001685 Decl *get() const { return static_cast<Decl*>(data[0]); }
1686 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001687};
Ted Kremenek035dc412010-11-13 00:36:50 +00001688class TypeLocVisit : public VisitorJob {
1689public:
1690 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1691 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1692 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1693
1694 static bool classof(const VisitorJob *VJ) {
1695 return VJ->getKind() == TypeLocVisitKind;
1696 }
1697
Ted Kremenek82f3c502010-11-15 22:23:26 +00001698 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001699 QualType T = QualType::getFromOpaquePtr(data[0]);
1700 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001701 }
1702};
1703
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001704class LabelRefVisit : public VisitorJob {
1705public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001706 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1707 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001708 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001709
1710 static bool classof(const VisitorJob *VJ) {
1711 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1712 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001713 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001714 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001715 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001716};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001717
1718class NestedNameSpecifierLocVisit : public VisitorJob {
1719public:
1720 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1721 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1722 Qualifier.getNestedNameSpecifier(),
1723 Qualifier.getOpaqueData()) { }
1724
1725 static bool classof(const VisitorJob *VJ) {
1726 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1727 }
1728
1729 NestedNameSpecifierLoc get() const {
1730 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1731 data[1]);
1732 }
1733};
1734
Ted Kremenekf64d8032010-11-18 00:02:32 +00001735class DeclarationNameInfoVisit : public VisitorJob {
1736public:
1737 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1738 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1739 static bool classof(const VisitorJob *VJ) {
1740 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1741 }
1742 DeclarationNameInfo get() const {
1743 Stmt *S = static_cast<Stmt*>(data[0]);
1744 switch (S->getStmtClass()) {
1745 default:
1746 llvm_unreachable("Unhandled Stmt");
1747 case Stmt::CXXDependentScopeMemberExprClass:
1748 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1749 case Stmt::DependentScopeDeclRefExprClass:
1750 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1751 }
1752 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001753};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001754class MemberRefVisit : public VisitorJob {
1755public:
1756 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1757 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001758 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001759 static bool classof(const VisitorJob *VJ) {
1760 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1761 }
1762 FieldDecl *get() const {
1763 return static_cast<FieldDecl*>(data[0]);
1764 }
1765 SourceLocation getLoc() const {
1766 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1767 }
1768};
Ted Kremenek28a71942010-11-13 00:36:47 +00001769class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1770 VisitorWorkList &WL;
1771 CXCursor Parent;
1772public:
1773 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1774 : WL(wl), Parent(parent) {}
1775
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001776 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001777 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001778 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001779 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001780 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001781 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001782 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001783 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001784 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001785 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001786 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001787 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001788 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001789 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001790 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001791 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001792 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001793 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001794 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1795 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001796 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001797 void VisitIfStmt(IfStmt *If);
1798 void VisitInitListExpr(InitListExpr *IE);
1799 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001800 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001801 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001802 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1803 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001804 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001805 void VisitStmt(Stmt *S);
1806 void VisitSwitchStmt(SwitchStmt *S);
1807 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001808 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001809 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001810 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001811 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001812 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001813 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001814 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001815
Ted Kremenek28a71942010-11-13 00:36:47 +00001816private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001817 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001818 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001819 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001820 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001821 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001822 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001823 void AddTypeLoc(TypeSourceInfo *TI);
1824 void EnqueueChildren(Stmt *S);
1825};
1826} // end anonyous namespace
1827
Ted Kremenekf64d8032010-11-18 00:02:32 +00001828void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1829 // 'S' should always be non-null, since it comes from the
1830 // statement we are visiting.
1831 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1832}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001833
1834void
1835EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1836 if (Qualifier)
1837 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1838}
1839
Ted Kremenek28a71942010-11-13 00:36:47 +00001840void EnqueueVisitor::AddStmt(Stmt *S) {
1841 if (S)
1842 WL.push_back(StmtVisit(S, Parent));
1843}
Ted Kremenek035dc412010-11-13 00:36:50 +00001844void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001845 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001846 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001847}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001848void EnqueueVisitor::
1849 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1850 if (A)
1851 WL.push_back(ExplicitTemplateArgsVisit(
1852 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1853}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001854void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1855 if (D)
1856 WL.push_back(MemberRefVisit(D, L, Parent));
1857}
Ted Kremenek28a71942010-11-13 00:36:47 +00001858void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1859 if (TI)
1860 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1861 }
1862void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001863 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001864 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001865 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001866 }
1867 if (size == WL.size())
1868 return;
1869 // Now reverse the entries we just added. This will match the DFS
1870 // ordering performed by the worklist.
1871 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1872 std::reverse(I, E);
1873}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001874void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1875 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1876}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001877void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1878 AddDecl(B->getBlockDecl());
1879}
Ted Kremenek28a71942010-11-13 00:36:47 +00001880void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1881 EnqueueChildren(E);
1882 AddTypeLoc(E->getTypeSourceInfo());
1883}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001884void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1885 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1886 E = S->body_rend(); I != E; ++I) {
1887 AddStmt(*I);
1888 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001889}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001890void EnqueueVisitor::
1891VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1892 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1893 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001894 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1895 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001896 if (!E->isImplicitAccess())
1897 AddStmt(E->getBase());
1898}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001899void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1900 // Enqueue the initializer or constructor arguments.
1901 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1902 AddStmt(E->getConstructorArg(I-1));
1903 // Enqueue the array size, if any.
1904 AddStmt(E->getArraySize());
1905 // Enqueue the allocated type.
1906 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1907 // Enqueue the placement arguments.
1908 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1909 AddStmt(E->getPlacementArg(I-1));
1910}
Ted Kremenek28a71942010-11-13 00:36:47 +00001911void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001912 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1913 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001914 AddStmt(CE->getCallee());
1915 AddStmt(CE->getArg(0));
1916}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001917void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1918 // Visit the name of the type being destroyed.
1919 AddTypeLoc(E->getDestroyedTypeInfo());
1920 // Visit the scope type that looks disturbingly like the nested-name-specifier
1921 // but isn't.
1922 AddTypeLoc(E->getScopeTypeInfo());
1923 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001924 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1925 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001926 // Visit base expression.
1927 AddStmt(E->getBase());
1928}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001929void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1930 AddTypeLoc(E->getTypeSourceInfo());
1931}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001932void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1933 EnqueueChildren(E);
1934 AddTypeLoc(E->getTypeSourceInfo());
1935}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001936void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1937 EnqueueChildren(E);
1938 if (E->isTypeOperand())
1939 AddTypeLoc(E->getTypeOperandSourceInfo());
1940}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001941
1942void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1943 *E) {
1944 EnqueueChildren(E);
1945 AddTypeLoc(E->getTypeSourceInfo());
1946}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001947void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1948 EnqueueChildren(E);
1949 if (E->isTypeOperand())
1950 AddTypeLoc(E->getTypeOperandSourceInfo());
1951}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001952void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001953 if (DR->hasExplicitTemplateArgs()) {
1954 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1955 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001956 WL.push_back(DeclRefExprParts(DR, Parent));
1957}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001958void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1959 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1960 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001961 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001962}
Ted Kremenek035dc412010-11-13 00:36:50 +00001963void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1964 unsigned size = WL.size();
1965 bool isFirst = true;
1966 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1967 D != DEnd; ++D) {
1968 AddDecl(*D, isFirst);
1969 isFirst = false;
1970 }
1971 if (size == WL.size())
1972 return;
1973 // Now reverse the entries we just added. This will match the DFS
1974 // ordering performed by the worklist.
1975 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1976 std::reverse(I, E);
1977}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001978void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1979 AddStmt(E->getInit());
1980 typedef DesignatedInitExpr::Designator Designator;
1981 for (DesignatedInitExpr::reverse_designators_iterator
1982 D = E->designators_rbegin(), DEnd = E->designators_rend();
1983 D != DEnd; ++D) {
1984 if (D->isFieldDesignator()) {
1985 if (FieldDecl *Field = D->getField())
1986 AddMemberRef(Field, D->getFieldLoc());
1987 continue;
1988 }
1989 if (D->isArrayDesignator()) {
1990 AddStmt(E->getArrayIndex(*D));
1991 continue;
1992 }
1993 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1994 AddStmt(E->getArrayRangeEnd(*D));
1995 AddStmt(E->getArrayRangeStart(*D));
1996 }
1997}
Ted Kremenek28a71942010-11-13 00:36:47 +00001998void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1999 EnqueueChildren(E);
2000 AddTypeLoc(E->getTypeInfoAsWritten());
2001}
2002void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2003 AddStmt(FS->getBody());
2004 AddStmt(FS->getInc());
2005 AddStmt(FS->getCond());
2006 AddDecl(FS->getConditionVariable());
2007 AddStmt(FS->getInit());
2008}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002009void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2010 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2011}
Ted Kremenek28a71942010-11-13 00:36:47 +00002012void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2013 AddStmt(If->getElse());
2014 AddStmt(If->getThen());
2015 AddStmt(If->getCond());
2016 AddDecl(If->getConditionVariable());
2017}
2018void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2019 // We care about the syntactic form of the initializer list, only.
2020 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2021 IE = Syntactic;
2022 EnqueueChildren(IE);
2023}
2024void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002025 WL.push_back(MemberExprParts(M, Parent));
2026
2027 // If the base of the member access expression is an implicit 'this', don't
2028 // visit it.
2029 // FIXME: If we ever want to show these implicit accesses, this will be
2030 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002031 if (!M->isImplicitAccess())
2032 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002033}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002034void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2035 AddTypeLoc(E->getEncodedTypeSourceInfo());
2036}
Ted Kremenek28a71942010-11-13 00:36:47 +00002037void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2038 EnqueueChildren(M);
2039 AddTypeLoc(M->getClassReceiverTypeInfo());
2040}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002041void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2042 // Visit the components of the offsetof expression.
2043 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2044 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2045 const OffsetOfNode &Node = E->getComponent(I-1);
2046 switch (Node.getKind()) {
2047 case OffsetOfNode::Array:
2048 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2049 break;
2050 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002051 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002052 break;
2053 case OffsetOfNode::Identifier:
2054 case OffsetOfNode::Base:
2055 continue;
2056 }
2057 }
2058 // Visit the type into which we're computing the offset.
2059 AddTypeLoc(E->getTypeSourceInfo());
2060}
Ted Kremenek28a71942010-11-13 00:36:47 +00002061void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002062 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002063 WL.push_back(OverloadExprParts(E, Parent));
2064}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002065void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2066 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002067 EnqueueChildren(E);
2068 if (E->isArgumentType())
2069 AddTypeLoc(E->getArgumentTypeInfo());
2070}
Ted Kremenek28a71942010-11-13 00:36:47 +00002071void EnqueueVisitor::VisitStmt(Stmt *S) {
2072 EnqueueChildren(S);
2073}
2074void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2075 AddStmt(S->getBody());
2076 AddStmt(S->getCond());
2077 AddDecl(S->getConditionVariable());
2078}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002079
Ted Kremenek28a71942010-11-13 00:36:47 +00002080void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2081 AddStmt(W->getBody());
2082 AddStmt(W->getCond());
2083 AddDecl(W->getConditionVariable());
2084}
John Wiegley21ff2e52011-04-28 00:16:57 +00002085
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002086void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2087 AddTypeLoc(E->getQueriedTypeSourceInfo());
2088}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002089
2090void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002091 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002092 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002093}
2094
John Wiegley21ff2e52011-04-28 00:16:57 +00002095void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2096 AddTypeLoc(E->getQueriedTypeSourceInfo());
2097}
2098
John Wiegley55262202011-04-25 06:54:41 +00002099void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2100 EnqueueChildren(E);
2101}
2102
Ted Kremenek28a71942010-11-13 00:36:47 +00002103void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2104 VisitOverloadExpr(U);
2105 if (!U->isImplicitAccess())
2106 AddStmt(U->getBase());
2107}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002108void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2109 AddStmt(E->getSubExpr());
2110 AddTypeLoc(E->getWrittenTypeInfo());
2111}
Douglas Gregor94d96292011-01-19 20:34:17 +00002112void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2113 WL.push_back(SizeOfPackExprParts(E, Parent));
2114}
Ted Kremenek60458782010-11-12 21:34:16 +00002115
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002116void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002117 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002118}
2119
2120bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2121 if (RegionOfInterest.isValid()) {
2122 SourceRange Range = getRawCursorExtent(C);
2123 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2124 return false;
2125 }
2126 return true;
2127}
2128
2129bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2130 while (!WL.empty()) {
2131 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002132 VisitorJob LI = WL.back();
2133 WL.pop_back();
2134
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002135 // Set the Parent field, then back to its old value once we're done.
2136 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2137
2138 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002139 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002140 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002141 if (!D)
2142 continue;
2143
2144 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002145 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002146 return true;
2147
2148 continue;
2149 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002150 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2151 const ExplicitTemplateArgumentList *ArgList =
2152 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2153 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2154 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2155 Arg != ArgEnd; ++Arg) {
2156 if (VisitTemplateArgumentLoc(*Arg))
2157 return true;
2158 }
2159 continue;
2160 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002161 case VisitorJob::TypeLocVisitKind: {
2162 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002163 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002164 return true;
2165 continue;
2166 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002167 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002168 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002169 if (LabelStmt *stmt = LS->getStmt()) {
2170 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2171 TU))) {
2172 return true;
2173 }
2174 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002175 continue;
2176 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002177
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002178 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2179 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2180 if (VisitNestedNameSpecifierLoc(V->get()))
2181 return true;
2182 continue;
2183 }
2184
Ted Kremenekf64d8032010-11-18 00:02:32 +00002185 case VisitorJob::DeclarationNameInfoVisitKind: {
2186 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2187 ->get()))
2188 return true;
2189 continue;
2190 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002191 case VisitorJob::MemberRefVisitKind: {
2192 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2193 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2194 return true;
2195 continue;
2196 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002197 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002198 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002199 if (!S)
2200 continue;
2201
Ted Kremenekf1107452010-11-12 18:26:56 +00002202 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002203 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002204 if (!IsInRegionOfInterest(Cursor))
2205 continue;
2206 switch (Visitor(Cursor, Parent, ClientData)) {
2207 case CXChildVisit_Break: return true;
2208 case CXChildVisit_Continue: break;
2209 case CXChildVisit_Recurse:
2210 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002211 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002212 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002213 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002214 }
2215 case VisitorJob::MemberExprPartsKind: {
2216 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002217 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002218
2219 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002220 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2221 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002222 return true;
2223
2224 // Visit the declaration name.
2225 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2226 return true;
2227
2228 // Visit the explicitly-specified template arguments, if any.
2229 if (M->hasExplicitTemplateArgs()) {
2230 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2231 *ArgEnd = Arg + M->getNumTemplateArgs();
2232 Arg != ArgEnd; ++Arg) {
2233 if (VisitTemplateArgumentLoc(*Arg))
2234 return true;
2235 }
2236 }
2237 continue;
2238 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002239 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002240 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002241 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002242 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2243 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002244 return true;
2245 // Visit declaration name.
2246 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2247 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002248 continue;
2249 }
Ted Kremenek60458782010-11-12 21:34:16 +00002250 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002251 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002252 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002253 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2254 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002255 return true;
2256 // Visit the declaration name.
2257 if (VisitDeclarationNameInfo(O->getNameInfo()))
2258 return true;
2259 // Visit the overloaded declaration reference.
2260 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2261 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002262 continue;
2263 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002264 case VisitorJob::SizeOfPackExprPartsKind: {
2265 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2266 NamedDecl *Pack = E->getPack();
2267 if (isa<TemplateTypeParmDecl>(Pack)) {
2268 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2269 E->getPackLoc(), TU)))
2270 return true;
2271
2272 continue;
2273 }
2274
2275 if (isa<TemplateTemplateParmDecl>(Pack)) {
2276 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2277 E->getPackLoc(), TU)))
2278 return true;
2279
2280 continue;
2281 }
2282
2283 // Non-type template parameter packs and function parameter packs are
2284 // treated like DeclRefExpr cursors.
2285 continue;
2286 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002287 }
2288 }
2289 return false;
2290}
2291
Ted Kremenekcdba6592010-11-18 00:42:18 +00002292bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002293 VisitorWorkList *WL = 0;
2294 if (!WorkListFreeList.empty()) {
2295 WL = WorkListFreeList.back();
2296 WL->clear();
2297 WorkListFreeList.pop_back();
2298 }
2299 else {
2300 WL = new VisitorWorkList();
2301 WorkListCache.push_back(WL);
2302 }
2303 EnqueueWorkList(*WL, S);
2304 bool result = RunVisitorWorkList(*WL);
2305 WorkListFreeList.push_back(WL);
2306 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002307}
2308
Francois Pichet48a8d142011-07-25 22:00:44 +00002309namespace {
2310typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2311RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2312 const DeclarationNameInfo &NI,
2313 const SourceRange &QLoc,
2314 const ExplicitTemplateArgumentList *TemplateArgs = 0){
2315 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2316 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2317 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2318
2319 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2320
2321 RefNamePieces Pieces;
2322
2323 if (WantQualifier && QLoc.isValid())
2324 Pieces.push_back(QLoc);
2325
2326 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2327 Pieces.push_back(NI.getLoc());
2328
2329 if (WantTemplateArgs && TemplateArgs)
2330 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2331 TemplateArgs->RAngleLoc));
2332
2333 if (Kind == DeclarationName::CXXOperatorName) {
2334 Pieces.push_back(SourceLocation::getFromRawEncoding(
2335 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2336 Pieces.push_back(SourceLocation::getFromRawEncoding(
2337 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2338 }
2339
2340 if (WantSinglePiece) {
2341 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2342 Pieces.clear();
2343 Pieces.push_back(R);
2344 }
2345
2346 return Pieces;
2347}
2348}
2349
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002350//===----------------------------------------------------------------------===//
2351// Misc. API hooks.
2352//===----------------------------------------------------------------------===//
2353
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002354static llvm::sys::Mutex EnableMultithreadingMutex;
2355static bool EnabledMultithreading;
2356
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002357extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002358CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2359 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002360 // Disable pretty stack trace functionality, which will otherwise be a very
2361 // poor citizen of the world and set up all sorts of signal handlers.
2362 llvm::DisablePrettyStackTrace = true;
2363
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002364 // We use crash recovery to make some of our APIs more reliable, implicitly
2365 // enable it.
2366 llvm::CrashRecoveryContext::Enable();
2367
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002368 // Enable support for multithreading in LLVM.
2369 {
2370 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2371 if (!EnabledMultithreading) {
2372 llvm::llvm_start_multithreaded();
2373 EnabledMultithreading = true;
2374 }
2375 }
2376
Douglas Gregora030b7c2010-01-22 20:35:53 +00002377 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002378 if (excludeDeclarationsFromPCH)
2379 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002380 if (displayDiagnostics)
2381 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002382 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002383}
2384
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002385void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002386 if (CIdx)
2387 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002388}
2389
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002390void clang_toggleCrashRecovery(unsigned isEnabled) {
2391 if (isEnabled)
2392 llvm::CrashRecoveryContext::Enable();
2393 else
2394 llvm::CrashRecoveryContext::Disable();
2395}
2396
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002397CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002398 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002399 if (!CIdx)
2400 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002401
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002402 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002403 FileSystemOptions FileSystemOpts;
2404 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002405
Douglas Gregor28019772010-04-05 23:52:57 +00002406 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002407 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002408 CXXIdx->getOnlyLocalDecls(),
2409 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002410 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002411}
2412
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002413unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002414 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002415 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002416}
2417
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002418CXTranslationUnit
2419clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2420 const char *source_filename,
2421 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002422 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002423 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002424 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002425 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002426 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002427 return clang_parseTranslationUnit(CIdx, source_filename,
2428 command_line_args, num_command_line_args,
2429 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002430 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002431}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002432
2433struct ParseTranslationUnitInfo {
2434 CXIndex CIdx;
2435 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002436 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002437 int num_command_line_args;
2438 struct CXUnsavedFile *unsaved_files;
2439 unsigned num_unsaved_files;
2440 unsigned options;
2441 CXTranslationUnit result;
2442};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002443static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002444 ParseTranslationUnitInfo *PTUI =
2445 static_cast<ParseTranslationUnitInfo*>(UserData);
2446 CXIndex CIdx = PTUI->CIdx;
2447 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002448 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002449 int num_command_line_args = PTUI->num_command_line_args;
2450 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2451 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2452 unsigned options = PTUI->options;
2453 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002454
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002455 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002456 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002458 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2459
Douglas Gregor44c181a2010-07-23 00:33:23 +00002460 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002461 // FIXME: Add a flag for modules.
2462 TranslationUnitKind TUKind
2463 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002464 bool CacheCodeCompetionResults
2465 = options & CXTranslationUnit_CacheCompletionResults;
2466
Douglas Gregor5352ac02010-01-28 00:27:43 +00002467 // Configure the diagnostics.
2468 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002469 llvm::IntrusiveRefCntPtr<Diagnostic>
2470 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2471 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002472
Ted Kremenek25a11e12011-03-22 01:15:24 +00002473 // Recover resources if we crash before exiting this function.
2474 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2475 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2476 DiagCleanup(Diags.getPtr());
2477
2478 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2479 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2480
2481 // Recover resources if we crash before exiting this function.
2482 llvm::CrashRecoveryContextCleanupRegistrar<
2483 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2484
Douglas Gregor4db64a42010-01-23 00:14:00 +00002485 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002486 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002487 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002488 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002489 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2490 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002491 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002492
Ted Kremenek25a11e12011-03-22 01:15:24 +00002493 llvm::OwningPtr<std::vector<const char *> >
2494 Args(new std::vector<const char*>());
2495
2496 // Recover resources if we crash before exiting this method.
2497 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2498 ArgsCleanup(Args.get());
2499
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002500 // Since the Clang C library is primarily used by batch tools dealing with
2501 // (often very broken) source code, where spell-checking can have a
2502 // significant negative impact on performance (particularly when
2503 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002504 // Only do this if we haven't found a spell-checking-related argument.
2505 bool FoundSpellCheckingArgument = false;
2506 for (int I = 0; I != num_command_line_args; ++I) {
2507 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2508 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2509 FoundSpellCheckingArgument = true;
2510 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002511 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002512 }
2513 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002514 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002515
Ted Kremenek25a11e12011-03-22 01:15:24 +00002516 Args->insert(Args->end(), command_line_args,
2517 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002518
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002519 // The 'source_filename' argument is optional. If the caller does not
2520 // specify it then it is assumed that the source file is specified
2521 // in the actual argument list.
2522 // Put the source file after command_line_args otherwise if '-x' flag is
2523 // present it will be unused.
2524 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002525 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002526
Douglas Gregor44c181a2010-07-23 00:33:23 +00002527 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002528 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002529 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002530 Args->push_back("-Xclang");
2531 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002532 NestedMacroExpansions
2533 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002534 }
2535
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002536 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002537 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002538 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2539 /* vector::data() not portable */,
2540 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002541 Diags,
2542 CXXIdx->getClangResourcesPath(),
2543 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002544 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002545 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002546 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002547 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002548 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002549 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002550 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002551 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002552
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002553 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002554 // Make sure to check that 'Unit' is non-NULL.
2555 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2556 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2557 DEnd = Unit->stored_diag_end();
2558 D != DEnd; ++D) {
2559 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2560 CXString Msg = clang_formatDiagnostic(&Diag,
2561 clang_defaultDiagnosticDisplayOptions());
2562 fprintf(stderr, "%s\n", clang_getCString(Msg));
2563 clang_disposeString(Msg);
2564 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002565#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002566 // On Windows, force a flush, since there may be multiple copies of
2567 // stderr and stdout in the file system, all with different buffers
2568 // but writing to the same device.
2569 fflush(stderr);
2570#endif
2571 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002572 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002573
Ted Kremeneka60ed472010-11-16 08:15:36 +00002574 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002575}
2576CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2577 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002578 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002579 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002580 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002581 unsigned num_unsaved_files,
2582 unsigned options) {
2583 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002584 num_command_line_args, unsaved_files,
2585 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002586 llvm::CrashRecoveryContext CRC;
2587
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002588 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002589 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2590 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2591 fprintf(stderr, " 'command_line_args' : [");
2592 for (int i = 0; i != num_command_line_args; ++i) {
2593 if (i)
2594 fprintf(stderr, ", ");
2595 fprintf(stderr, "'%s'", command_line_args[i]);
2596 }
2597 fprintf(stderr, "],\n");
2598 fprintf(stderr, " 'unsaved_files' : [");
2599 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2600 if (i)
2601 fprintf(stderr, ", ");
2602 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2603 unsaved_files[i].Length);
2604 }
2605 fprintf(stderr, "],\n");
2606 fprintf(stderr, " 'options' : %d,\n", options);
2607 fprintf(stderr, "}\n");
2608
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002609 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002610 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2611 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002612 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002613
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002614 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002615}
2616
Douglas Gregor19998442010-08-13 15:35:05 +00002617unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2618 return CXSaveTranslationUnit_None;
2619}
2620
2621int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2622 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002623 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002624 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002625
Douglas Gregor39c411f2011-07-06 16:43:36 +00002626 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002627 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2628 PrintLibclangResourceUsage(TU);
2629 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002630}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002631
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002632void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002633 if (CTUnit) {
2634 // If the translation unit has been marked as unsafe to free, just discard
2635 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002636 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002637 return;
2638
Ted Kremeneka60ed472010-11-16 08:15:36 +00002639 delete static_cast<ASTUnit *>(CTUnit->TUData);
2640 disposeCXStringPool(CTUnit->StringPool);
2641 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002642 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002643}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002644
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002645unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2646 return CXReparse_None;
2647}
2648
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002649struct ReparseTranslationUnitInfo {
2650 CXTranslationUnit TU;
2651 unsigned num_unsaved_files;
2652 struct CXUnsavedFile *unsaved_files;
2653 unsigned options;
2654 int result;
2655};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002656
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002657static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002658 ReparseTranslationUnitInfo *RTUI =
2659 static_cast<ReparseTranslationUnitInfo*>(UserData);
2660 CXTranslationUnit TU = RTUI->TU;
2661 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2662 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2663 unsigned options = RTUI->options;
2664 (void) options;
2665 RTUI->result = 1;
2666
Douglas Gregorabc563f2010-07-19 21:46:24 +00002667 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002668 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002669
Ted Kremeneka60ed472010-11-16 08:15:36 +00002670 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002671 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002672
Ted Kremenek25a11e12011-03-22 01:15:24 +00002673 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2674 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2675
2676 // Recover resources if we crash before exiting this function.
2677 llvm::CrashRecoveryContextCleanupRegistrar<
2678 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2679
Douglas Gregorabc563f2010-07-19 21:46:24 +00002680 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002681 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002682 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002683 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002684 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2685 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002686 }
2687
Ted Kremenek4ee99262011-03-22 20:16:19 +00002688 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2689 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002690 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002691}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002692
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002693int clang_reparseTranslationUnit(CXTranslationUnit TU,
2694 unsigned num_unsaved_files,
2695 struct CXUnsavedFile *unsaved_files,
2696 unsigned options) {
2697 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2698 options, 0 };
2699 llvm::CrashRecoveryContext CRC;
2700
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002701 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002702 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002703 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002704 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002705 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2706 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002707
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002708 return RTUI.result;
2709}
2710
Douglas Gregordf95a132010-08-09 20:45:32 +00002711
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002712CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002713 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002714 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715
Ted Kremeneka60ed472010-11-16 08:15:36 +00002716 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002717 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002718}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002719
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002720CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002721 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002722 return Result;
2723}
2724
Ted Kremenekfb480492010-01-13 21:46:36 +00002725} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002726
Ted Kremenekfb480492010-01-13 21:46:36 +00002727//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002728// CXSourceLocation and CXSourceRange Operations.
2729//===----------------------------------------------------------------------===//
2730
Douglas Gregorb9790342010-01-22 21:44:22 +00002731extern "C" {
2732CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002733 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002734 return Result;
2735}
2736
2737unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002738 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2739 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2740 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002741}
2742
2743CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2744 CXFile file,
2745 unsigned line,
2746 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002747 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002748 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002749
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002750 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002751 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002752 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002753 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002754 = CXXUnit->getSourceManager().getLocation(File, line, column);
2755 if (SLoc.isInvalid()) {
2756 if (Logging)
2757 llvm::errs() << "clang_getLocation(\"" << File->getName()
2758 << "\", " << line << ", " << column << ") = invalid\n";
2759 return clang_getNullLocation();
2760 }
2761
2762 if (Logging)
2763 llvm::errs() << "clang_getLocation(\"" << File->getName()
2764 << "\", " << line << ", " << column << ") = "
2765 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002766
2767 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2768}
2769
2770CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2771 CXFile file,
2772 unsigned offset) {
2773 if (!tu || !file)
2774 return clang_getNullLocation();
2775
Ted Kremeneka60ed472010-11-16 08:15:36 +00002776 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002777 SourceLocation Start
2778 = CXXUnit->getSourceManager().getLocation(
2779 static_cast<const FileEntry *>(file),
2780 1, 1);
2781 if (Start.isInvalid()) return clang_getNullLocation();
2782
2783 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2784
2785 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002786
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002787 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002788}
2789
Douglas Gregor5352ac02010-01-28 00:27:43 +00002790CXSourceRange clang_getNullRange() {
2791 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2792 return Result;
2793}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002794
Douglas Gregor5352ac02010-01-28 00:27:43 +00002795CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2796 if (begin.ptr_data[0] != end.ptr_data[0] ||
2797 begin.ptr_data[1] != end.ptr_data[1])
2798 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002799
2800 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002801 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002802 return Result;
2803}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002804
2805unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2806{
2807 return range1.ptr_data[0] == range2.ptr_data[0]
2808 && range1.ptr_data[1] == range2.ptr_data[1]
2809 && range1.begin_int_data == range2.begin_int_data
2810 && range1.end_int_data == range2.end_int_data;
2811}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002812} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002813
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002814static void createNullLocation(CXFile *file, unsigned *line,
2815 unsigned *column, unsigned *offset) {
2816 if (file)
2817 *file = 0;
2818 if (line)
2819 *line = 0;
2820 if (column)
2821 *column = 0;
2822 if (offset)
2823 *offset = 0;
2824 return;
2825}
2826
2827extern "C" {
Chandler Carruth20174222011-08-31 16:53:37 +00002828void clang_getExpansionLocation(CXSourceLocation location,
2829 CXFile *file,
2830 unsigned *line,
2831 unsigned *column,
2832 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002833 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2834
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002835 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002836 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002837 return;
2838 }
2839
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002840 const SourceManager &SM =
2841 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth20174222011-08-31 16:53:37 +00002842 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002843
Chandler Carruthcea731a2011-07-14 16:07:57 +00002844 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002845 // This can manifest in invalid code.
Chandler Carruth20174222011-08-31 16:53:37 +00002846 FileID fileID = SM.getFileID(ExpansionLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002847 bool Invalid = false;
2848 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2849 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002850 createNullLocation(file, line, column, offset);
2851 return;
2852 }
2853
Douglas Gregor1db19de2010-01-19 21:36:55 +00002854 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002855 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002856 if (line)
Chandler Carruth20174222011-08-31 16:53:37 +00002857 *line = SM.getExpansionLineNumber(ExpansionLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002858 if (column)
Chandler Carruth20174222011-08-31 16:53:37 +00002859 *column = SM.getExpansionColumnNumber(ExpansionLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002860 if (offset)
Chandler Carruth20174222011-08-31 16:53:37 +00002861 *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2862}
2863
Argyrios Kyrtzidise6be34d2011-09-13 21:49:08 +00002864void clang_getPresumedLocation(CXSourceLocation location,
2865 CXString *filename,
2866 unsigned *line,
2867 unsigned *column) {
2868 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2869
2870 if (!location.ptr_data[0] || Loc.isInvalid()) {
2871 if (filename)
2872 *filename = createCXString("");
2873 if (line)
2874 *line = 0;
2875 if (column)
2876 *column = 0;
2877 }
2878 else {
2879 const SourceManager &SM =
2880 *static_cast<const SourceManager*>(location.ptr_data[0]);
2881 PresumedLoc PreLoc = SM.getPresumedLoc(Loc);
2882
2883 if (filename)
2884 *filename = createCXString(PreLoc.getFilename());
2885 if (line)
2886 *line = PreLoc.getLine();
2887 if (column)
2888 *column = PreLoc.getColumn();
2889 }
2890}
2891
Chandler Carruth20174222011-08-31 16:53:37 +00002892void clang_getInstantiationLocation(CXSourceLocation location,
2893 CXFile *file,
2894 unsigned *line,
2895 unsigned *column,
2896 unsigned *offset) {
2897 // Redirect to new API.
2898 clang_getExpansionLocation(location, file, line, column, offset);
Douglas Gregore69517c2010-01-26 03:07:15 +00002899}
2900
Douglas Gregora9b06d42010-11-09 06:24:54 +00002901void clang_getSpellingLocation(CXSourceLocation location,
2902 CXFile *file,
2903 unsigned *line,
2904 unsigned *column,
2905 unsigned *offset) {
2906 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2907
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002908 if (!location.ptr_data[0] || Loc.isInvalid())
2909 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002910
2911 const SourceManager &SM =
2912 *static_cast<const SourceManager*>(location.ptr_data[0]);
2913 SourceLocation SpellLoc = Loc;
2914 if (SpellLoc.isMacroID()) {
2915 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2916 if (SimpleSpellingLoc.isFileID() &&
2917 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2918 SpellLoc = SimpleSpellingLoc;
2919 else
Chandler Carruth40278532011-07-25 16:49:02 +00002920 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002921 }
2922
2923 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2924 FileID FID = LocInfo.first;
2925 unsigned FileOffset = LocInfo.second;
2926
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002927 if (FID.isInvalid())
2928 return createNullLocation(file, line, column, offset);
2929
Douglas Gregora9b06d42010-11-09 06:24:54 +00002930 if (file)
2931 *file = (void *)SM.getFileEntryForID(FID);
2932 if (line)
2933 *line = SM.getLineNumber(FID, FileOffset);
2934 if (column)
2935 *column = SM.getColumnNumber(FID, FileOffset);
2936 if (offset)
2937 *offset = FileOffset;
2938}
2939
Douglas Gregor1db19de2010-01-19 21:36:55 +00002940CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002941 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002942 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002943 return Result;
2944}
2945
2946CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002947 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002948 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002949 return Result;
2950}
2951
Douglas Gregorb9790342010-01-22 21:44:22 +00002952} // end: extern "C"
2953
Douglas Gregor1db19de2010-01-19 21:36:55 +00002954//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002955// CXFile Operations.
2956//===----------------------------------------------------------------------===//
2957
2958extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002959CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002960 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002961 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002962
Steve Naroff88145032009-10-27 14:35:18 +00002963 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002964 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002965}
2966
2967time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002968 if (!SFile)
2969 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002970
Steve Naroff88145032009-10-27 14:35:18 +00002971 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2972 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002973}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002974
Douglas Gregorb9790342010-01-22 21:44:22 +00002975CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2976 if (!tu)
2977 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002978
Ted Kremeneka60ed472010-11-16 08:15:36 +00002979 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002980
Douglas Gregorb9790342010-01-22 21:44:22 +00002981 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002982 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002983}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002984
Douglas Gregordd3e5542011-05-04 00:14:37 +00002985unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2986 if (!tu || !file)
2987 return 0;
2988
2989 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2990 FileEntry *FEnt = static_cast<FileEntry *>(file);
2991 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2992 .isFileMultipleIncludeGuarded(FEnt);
2993}
2994
Ted Kremenekfb480492010-01-13 21:46:36 +00002995} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002996
Ted Kremenekfb480492010-01-13 21:46:36 +00002997//===----------------------------------------------------------------------===//
2998// CXCursor Operations.
2999//===----------------------------------------------------------------------===//
3000
Ted Kremenekfb480492010-01-13 21:46:36 +00003001static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00003002 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00003003 return getDeclFromExpr(CE->getSubExpr());
3004
Ted Kremenekfb480492010-01-13 21:46:36 +00003005 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
3006 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003007 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3008 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00003009 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3010 return ME->getMemberDecl();
3011 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
3012 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00003013 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00003014 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00003015
Ted Kremenekfb480492010-01-13 21:46:36 +00003016 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3017 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00003018 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00003019 if (!CE->isElidable())
3020 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00003021 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3022 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003023
Douglas Gregordb1314e2010-10-01 21:11:22 +00003024 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3025 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00003026 if (SubstNonTypeTemplateParmPackExpr *NTTP
3027 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3028 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00003029 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3030 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3031 isa<ParmVarDecl>(SizeOfPack->getPack()))
3032 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00003033
Ted Kremenekfb480492010-01-13 21:46:36 +00003034 return 0;
3035}
3036
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003037static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00003038 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3039 return getLocationFromExpr(CE->getSubExpr());
3040
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003041 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3042 return /*FIXME:*/Msg->getLeftLoc();
3043 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3044 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003045 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3046 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003047 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3048 return Member->getMemberLoc();
3049 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3050 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003051 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3052 return SizeOfPack->getPackLoc();
3053
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003054 return E->getLocStart();
3055}
3056
Ted Kremenekfb480492010-01-13 21:46:36 +00003057extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003058
3059unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003060 CXCursorVisitor visitor,
3061 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003062 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003063 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003064 return CursorVis.VisitChildren(parent);
3065}
3066
David Chisnall3387c652010-11-03 14:12:26 +00003067#ifndef __has_feature
3068#define __has_feature(x) 0
3069#endif
3070#if __has_feature(blocks)
3071typedef enum CXChildVisitResult
3072 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3073
3074static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3075 CXClientData client_data) {
3076 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3077 return block(cursor, parent);
3078}
3079#else
3080// If we are compiled with a compiler that doesn't have native blocks support,
3081// define and call the block manually, so the
3082typedef struct _CXChildVisitResult
3083{
3084 void *isa;
3085 int flags;
3086 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003087 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3088 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003089} *CXCursorVisitorBlock;
3090
3091static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3092 CXClientData client_data) {
3093 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3094 return block->invoke(block, cursor, parent);
3095}
3096#endif
3097
3098
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003099unsigned clang_visitChildrenWithBlock(CXCursor parent,
3100 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003101 return clang_visitChildren(parent, visitWithBlock, block);
3102}
3103
Douglas Gregor78205d42010-01-20 21:45:58 +00003104static CXString getDeclSpelling(Decl *D) {
3105 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003106 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003107 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003108 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3109 return createCXString(Property->getIdentifier()->getName());
3110
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003111 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003112 }
3113
Douglas Gregor78205d42010-01-20 21:45:58 +00003114 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003115 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003116
Douglas Gregor78205d42010-01-20 21:45:58 +00003117 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3118 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3119 // and returns different names. NamedDecl returns the class name and
3120 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003121 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003122
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003123 if (isa<UsingDirectiveDecl>(D))
3124 return createCXString("");
3125
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003126 llvm::SmallString<1024> S;
3127 llvm::raw_svector_ostream os(S);
3128 ND->printName(os);
3129
3130 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003131}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003132
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003133CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003134 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003135 return clang_getTranslationUnitSpelling(
3136 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003137
Steve Narofff334b4e2009-09-02 18:26:48 +00003138 if (clang_isReference(C.kind)) {
3139 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003140 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003141 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003142 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003143 }
3144 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003145 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003146 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003147 }
3148 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003149 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003150 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003151 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003152 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003153 case CXCursor_CXXBaseSpecifier: {
3154 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3155 return createCXString(B->getType().getAsString());
3156 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003157 case CXCursor_TypeRef: {
3158 TypeDecl *Type = getCursorTypeRef(C).first;
3159 assert(Type && "Missing type decl");
3160
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003161 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3162 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003163 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003164 case CXCursor_TemplateRef: {
3165 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003166 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003167
3168 return createCXString(Template->getNameAsString());
3169 }
Douglas Gregor69319002010-08-31 23:48:11 +00003170
3171 case CXCursor_NamespaceRef: {
3172 NamedDecl *NS = getCursorNamespaceRef(C).first;
3173 assert(NS && "Missing namespace decl");
3174
3175 return createCXString(NS->getNameAsString());
3176 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003177
Douglas Gregora67e03f2010-09-09 21:42:20 +00003178 case CXCursor_MemberRef: {
3179 FieldDecl *Field = getCursorMemberRef(C).first;
3180 assert(Field && "Missing member decl");
3181
3182 return createCXString(Field->getNameAsString());
3183 }
3184
Douglas Gregor36897b02010-09-10 00:22:18 +00003185 case CXCursor_LabelRef: {
3186 LabelStmt *Label = getCursorLabelRef(C).first;
3187 assert(Label && "Missing label");
3188
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003189 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003190 }
3191
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003192 case CXCursor_OverloadedDeclRef: {
3193 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3194 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3195 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3196 return createCXString(ND->getNameAsString());
3197 return createCXString("");
3198 }
3199 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3200 return createCXString(E->getName().getAsString());
3201 OverloadedTemplateStorage *Ovl
3202 = Storage.get<OverloadedTemplateStorage*>();
3203 if (Ovl->size() == 0)
3204 return createCXString("");
3205 return createCXString((*Ovl->begin())->getNameAsString());
3206 }
3207
Daniel Dunbaracca7252009-11-30 20:42:49 +00003208 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003209 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003210 }
3211 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003212
3213 if (clang_isExpression(C.kind)) {
3214 Decl *D = getDeclFromExpr(getCursorExpr(C));
3215 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003216 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003217 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003218 }
3219
Douglas Gregor36897b02010-09-10 00:22:18 +00003220 if (clang_isStatement(C.kind)) {
3221 Stmt *S = getCursorStmt(C);
3222 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003223 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003224
3225 return createCXString("");
3226 }
3227
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003228 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003229 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003230 ->getNameStart());
3231
Douglas Gregor572feb22010-03-18 18:04:21 +00003232 if (C.kind == CXCursor_MacroDefinition)
3233 return createCXString(getCursorMacroDefinition(C)->getName()
3234 ->getNameStart());
3235
Douglas Gregorecdcb882010-10-20 22:00:55 +00003236 if (C.kind == CXCursor_InclusionDirective)
3237 return createCXString(getCursorInclusionDirective(C)->getFileName());
3238
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003239 if (clang_isDeclaration(C.kind))
3240 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003241
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003242 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003243}
3244
Douglas Gregor358559d2010-10-02 22:49:11 +00003245CXString clang_getCursorDisplayName(CXCursor C) {
3246 if (!clang_isDeclaration(C.kind))
3247 return clang_getCursorSpelling(C);
3248
3249 Decl *D = getCursorDecl(C);
3250 if (!D)
3251 return createCXString("");
3252
3253 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3254 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3255 D = FunTmpl->getTemplatedDecl();
3256
3257 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3258 llvm::SmallString<64> Str;
3259 llvm::raw_svector_ostream OS(Str);
3260 OS << Function->getNameAsString();
3261 if (Function->getPrimaryTemplate())
3262 OS << "<>";
3263 OS << "(";
3264 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3265 if (I)
3266 OS << ", ";
3267 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3268 }
3269
3270 if (Function->isVariadic()) {
3271 if (Function->getNumParams())
3272 OS << ", ";
3273 OS << "...";
3274 }
3275 OS << ")";
3276 return createCXString(OS.str());
3277 }
3278
3279 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3280 llvm::SmallString<64> Str;
3281 llvm::raw_svector_ostream OS(Str);
3282 OS << ClassTemplate->getNameAsString();
3283 OS << "<";
3284 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3285 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3286 if (I)
3287 OS << ", ";
3288
3289 NamedDecl *Param = Params->getParam(I);
3290 if (Param->getIdentifier()) {
3291 OS << Param->getIdentifier()->getName();
3292 continue;
3293 }
3294
3295 // There is no parameter name, which makes this tricky. Try to come up
3296 // with something useful that isn't too long.
3297 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3298 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3299 else if (NonTypeTemplateParmDecl *NTTP
3300 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3301 OS << NTTP->getType().getAsString(Policy);
3302 else
3303 OS << "template<...> class";
3304 }
3305
3306 OS << ">";
3307 return createCXString(OS.str());
3308 }
3309
3310 if (ClassTemplateSpecializationDecl *ClassSpec
3311 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3312 // If the type was explicitly written, use that.
3313 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3314 return createCXString(TSInfo->getType().getAsString(Policy));
3315
3316 llvm::SmallString<64> Str;
3317 llvm::raw_svector_ostream OS(Str);
3318 OS << ClassSpec->getNameAsString();
3319 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003320 ClassSpec->getTemplateArgs().data(),
3321 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003322 Policy);
3323 return createCXString(OS.str());
3324 }
3325
3326 return clang_getCursorSpelling(C);
3327}
3328
Ted Kremeneke68fff62010-02-17 00:41:32 +00003329CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003330 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003331 case CXCursor_FunctionDecl:
3332 return createCXString("FunctionDecl");
3333 case CXCursor_TypedefDecl:
3334 return createCXString("TypedefDecl");
3335 case CXCursor_EnumDecl:
3336 return createCXString("EnumDecl");
3337 case CXCursor_EnumConstantDecl:
3338 return createCXString("EnumConstantDecl");
3339 case CXCursor_StructDecl:
3340 return createCXString("StructDecl");
3341 case CXCursor_UnionDecl:
3342 return createCXString("UnionDecl");
3343 case CXCursor_ClassDecl:
3344 return createCXString("ClassDecl");
3345 case CXCursor_FieldDecl:
3346 return createCXString("FieldDecl");
3347 case CXCursor_VarDecl:
3348 return createCXString("VarDecl");
3349 case CXCursor_ParmDecl:
3350 return createCXString("ParmDecl");
3351 case CXCursor_ObjCInterfaceDecl:
3352 return createCXString("ObjCInterfaceDecl");
3353 case CXCursor_ObjCCategoryDecl:
3354 return createCXString("ObjCCategoryDecl");
3355 case CXCursor_ObjCProtocolDecl:
3356 return createCXString("ObjCProtocolDecl");
3357 case CXCursor_ObjCPropertyDecl:
3358 return createCXString("ObjCPropertyDecl");
3359 case CXCursor_ObjCIvarDecl:
3360 return createCXString("ObjCIvarDecl");
3361 case CXCursor_ObjCInstanceMethodDecl:
3362 return createCXString("ObjCInstanceMethodDecl");
3363 case CXCursor_ObjCClassMethodDecl:
3364 return createCXString("ObjCClassMethodDecl");
3365 case CXCursor_ObjCImplementationDecl:
3366 return createCXString("ObjCImplementationDecl");
3367 case CXCursor_ObjCCategoryImplDecl:
3368 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003369 case CXCursor_CXXMethod:
3370 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003371 case CXCursor_UnexposedDecl:
3372 return createCXString("UnexposedDecl");
3373 case CXCursor_ObjCSuperClassRef:
3374 return createCXString("ObjCSuperClassRef");
3375 case CXCursor_ObjCProtocolRef:
3376 return createCXString("ObjCProtocolRef");
3377 case CXCursor_ObjCClassRef:
3378 return createCXString("ObjCClassRef");
3379 case CXCursor_TypeRef:
3380 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003381 case CXCursor_TemplateRef:
3382 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003383 case CXCursor_NamespaceRef:
3384 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003385 case CXCursor_MemberRef:
3386 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003387 case CXCursor_LabelRef:
3388 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003389 case CXCursor_OverloadedDeclRef:
3390 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003391 case CXCursor_UnexposedExpr:
3392 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003393 case CXCursor_BlockExpr:
3394 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003395 case CXCursor_DeclRefExpr:
3396 return createCXString("DeclRefExpr");
3397 case CXCursor_MemberRefExpr:
3398 return createCXString("MemberRefExpr");
3399 case CXCursor_CallExpr:
3400 return createCXString("CallExpr");
3401 case CXCursor_ObjCMessageExpr:
3402 return createCXString("ObjCMessageExpr");
3403 case CXCursor_UnexposedStmt:
3404 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003405 case CXCursor_LabelStmt:
3406 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003407 case CXCursor_InvalidFile:
3408 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003409 case CXCursor_InvalidCode:
3410 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003411 case CXCursor_NoDeclFound:
3412 return createCXString("NoDeclFound");
3413 case CXCursor_NotImplemented:
3414 return createCXString("NotImplemented");
3415 case CXCursor_TranslationUnit:
3416 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003417 case CXCursor_UnexposedAttr:
3418 return createCXString("UnexposedAttr");
3419 case CXCursor_IBActionAttr:
3420 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003421 case CXCursor_IBOutletAttr:
3422 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003423 case CXCursor_IBOutletCollectionAttr:
3424 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003425 case CXCursor_CXXFinalAttr:
3426 return createCXString("attribute(final)");
3427 case CXCursor_CXXOverrideAttr:
3428 return createCXString("attribute(override)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003429 case CXCursor_PreprocessingDirective:
3430 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003431 case CXCursor_MacroDefinition:
3432 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003433 case CXCursor_MacroExpansion:
3434 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003435 case CXCursor_InclusionDirective:
3436 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003437 case CXCursor_Namespace:
3438 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003439 case CXCursor_LinkageSpec:
3440 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003441 case CXCursor_CXXBaseSpecifier:
3442 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003443 case CXCursor_Constructor:
3444 return createCXString("CXXConstructor");
3445 case CXCursor_Destructor:
3446 return createCXString("CXXDestructor");
3447 case CXCursor_ConversionFunction:
3448 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003449 case CXCursor_TemplateTypeParameter:
3450 return createCXString("TemplateTypeParameter");
3451 case CXCursor_NonTypeTemplateParameter:
3452 return createCXString("NonTypeTemplateParameter");
3453 case CXCursor_TemplateTemplateParameter:
3454 return createCXString("TemplateTemplateParameter");
3455 case CXCursor_FunctionTemplate:
3456 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003457 case CXCursor_ClassTemplate:
3458 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003459 case CXCursor_ClassTemplatePartialSpecialization:
3460 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003461 case CXCursor_NamespaceAlias:
3462 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003463 case CXCursor_UsingDirective:
3464 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003465 case CXCursor_UsingDeclaration:
3466 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003467 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003468 return createCXString("TypeAliasDecl");
3469 case CXCursor_ObjCSynthesizeDecl:
3470 return createCXString("ObjCSynthesizeDecl");
3471 case CXCursor_ObjCDynamicDecl:
3472 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003473 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003474
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003475 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003476 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003477}
Steve Naroff89922f82009-08-31 00:59:03 +00003478
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003479struct GetCursorData {
3480 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003481 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003482 CXCursor &BestCursor;
3483
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003484 GetCursorData(SourceManager &SM,
3485 SourceLocation tokenBegin, CXCursor &outputCursor)
3486 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3487 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3488 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003489};
3490
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003491static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3492 CXCursor parent,
3493 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003494 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3495 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003496
3497 // If we point inside a macro argument we should provide info of what the
3498 // token is so use the actual cursor, don't replace it with a macro expansion
3499 // cursor.
3500 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3501 return CXChildVisit_Recurse;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003502
3503 if (clang_isExpression(cursor.kind) &&
3504 clang_isDeclaration(BestCursor->kind)) {
3505 Decl *D = getCursorDecl(*BestCursor);
3506
3507 // Avoid having the cursor of an expression replace the declaration cursor
3508 // when the expression source range overlaps the declaration range.
3509 // This can happen for C++ constructor expressions whose range generally
3510 // include the variable declaration, e.g.:
3511 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3512 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3513 D->getLocation() == Data->TokenBeginLoc)
3514 return CXChildVisit_Break;
3515 }
3516
Douglas Gregor93798e22010-11-05 21:11:19 +00003517 // If our current best cursor is the construction of a temporary object,
3518 // don't replace that cursor with a type reference, because we want
3519 // clang_getCursor() to point at the constructor.
3520 if (clang_isExpression(BestCursor->kind) &&
3521 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3522 cursor.kind == CXCursor_TypeRef)
3523 return CXChildVisit_Recurse;
3524
Douglas Gregor85fe1562010-12-10 07:23:11 +00003525 // Don't override a preprocessing cursor with another preprocessing
3526 // cursor; we want the outermost preprocessing cursor.
3527 if (clang_isPreprocessing(cursor.kind) &&
3528 clang_isPreprocessing(BestCursor->kind))
3529 return CXChildVisit_Recurse;
3530
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003531 *BestCursor = cursor;
3532 return CXChildVisit_Recurse;
3533}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003534
Douglas Gregorb9790342010-01-22 21:44:22 +00003535CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3536 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003537 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003538
Ted Kremeneka60ed472010-11-16 08:15:36 +00003539 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003540 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3541
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003542 // Translate the given source location to make it point at the beginning of
3543 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003544 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003545
3546 // Guard against an invalid SourceLocation, or we may assert in one
3547 // of the following calls.
3548 if (SLoc.isInvalid())
3549 return clang_getNullCursor();
3550
Douglas Gregor40749ee2010-11-03 00:35:38 +00003551 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003552 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3553 CXXUnit->getASTContext().getLangOptions());
3554
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003555 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3556 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003557 // FIXME: Would be great to have a "hint" cursor, then walk from that
3558 // hint cursor upward until we find a cursor whose source range encloses
3559 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003560 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003561 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003562 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00003563 /*VisitPreprocessorLast=*/true,
3564 SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003565 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003566 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003567
3568 if (Logging) {
3569 CXFile SearchFile;
3570 unsigned SearchLine, SearchColumn;
3571 CXFile ResultFile;
3572 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003573 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3574 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003575 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3576
Chandler Carruth20174222011-08-31 16:53:37 +00003577 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3578 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3579 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003580 SearchFileName = clang_getFileName(SearchFile);
3581 ResultFileName = clang_getFileName(ResultFile);
3582 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003583 USR = clang_getCursorUSR(Result);
3584 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003585 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3586 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003587 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3588 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003589 clang_disposeString(SearchFileName);
3590 clang_disposeString(ResultFileName);
3591 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003592 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003593
3594 CXCursor Definition = clang_getCursorDefinition(Result);
3595 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3596 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3597 CXString DefinitionKindSpelling
3598 = clang_getCursorKindSpelling(Definition.kind);
3599 CXFile DefinitionFile;
3600 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003601 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3602 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003603 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3604 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3605 clang_getCString(DefinitionKindSpelling),
3606 clang_getCString(DefinitionFileName),
3607 DefinitionLine, DefinitionColumn);
3608 clang_disposeString(DefinitionFileName);
3609 clang_disposeString(DefinitionKindSpelling);
3610 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003611 }
3612
Ted Kremeneke68fff62010-02-17 00:41:32 +00003613 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003614}
3615
Ted Kremenek73885552009-11-17 19:28:59 +00003616CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003617 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003618}
3619
3620unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003621 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003622}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003623
Douglas Gregor9ce55842010-11-20 00:09:34 +00003624unsigned clang_hashCursor(CXCursor C) {
3625 unsigned Index = 0;
3626 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3627 Index = 1;
3628
3629 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3630 std::make_pair(C.kind, C.data[Index]));
3631}
3632
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003633unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003634 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3635}
3636
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003637unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003638 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3639}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003640
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003641unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003642 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3643}
3644
Douglas Gregor97b98722010-01-19 23:20:36 +00003645unsigned clang_isExpression(enum CXCursorKind K) {
3646 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3647}
3648
3649unsigned clang_isStatement(enum CXCursorKind K) {
3650 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3651}
3652
Douglas Gregor8be80e12011-07-06 03:00:34 +00003653unsigned clang_isAttribute(enum CXCursorKind K) {
3654 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3655}
3656
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003657unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3658 return K == CXCursor_TranslationUnit;
3659}
3660
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003661unsigned clang_isPreprocessing(enum CXCursorKind K) {
3662 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3663}
3664
Ted Kremenekad6eff62010-03-08 21:17:29 +00003665unsigned clang_isUnexposed(enum CXCursorKind K) {
3666 switch (K) {
3667 case CXCursor_UnexposedDecl:
3668 case CXCursor_UnexposedExpr:
3669 case CXCursor_UnexposedStmt:
3670 case CXCursor_UnexposedAttr:
3671 return true;
3672 default:
3673 return false;
3674 }
3675}
3676
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003677CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003678 return C.kind;
3679}
3680
Douglas Gregor98258af2010-01-18 22:46:11 +00003681CXSourceLocation clang_getCursorLocation(CXCursor C) {
3682 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003683 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003684 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003685 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3686 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003687 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003688 }
3689
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003690 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003691 std::pair<ObjCProtocolDecl *, SourceLocation> P
3692 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003693 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003694 }
3695
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003696 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003697 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3698 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003699 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003700 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003701
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003702 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003703 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003704 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003705 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003706
3707 case CXCursor_TemplateRef: {
3708 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3709 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3710 }
3711
Douglas Gregor69319002010-08-31 23:48:11 +00003712 case CXCursor_NamespaceRef: {
3713 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3714 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3715 }
3716
Douglas Gregora67e03f2010-09-09 21:42:20 +00003717 case CXCursor_MemberRef: {
3718 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3719 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3720 }
3721
Ted Kremenek3064ef92010-08-27 21:34:58 +00003722 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003723 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3724 if (!BaseSpec)
3725 return clang_getNullLocation();
3726
3727 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3728 return cxloc::translateSourceLocation(getCursorContext(C),
3729 TSInfo->getTypeLoc().getBeginLoc());
3730
3731 return cxloc::translateSourceLocation(getCursorContext(C),
3732 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003733 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003734
Douglas Gregor36897b02010-09-10 00:22:18 +00003735 case CXCursor_LabelRef: {
3736 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3737 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3738 }
3739
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003740 case CXCursor_OverloadedDeclRef:
3741 return cxloc::translateSourceLocation(getCursorContext(C),
3742 getCursorOverloadedDeclRef(C).second);
3743
Douglas Gregorf46034a2010-01-18 23:41:10 +00003744 default:
3745 // FIXME: Need a way to enumerate all non-reference cases.
3746 llvm_unreachable("Missed a reference kind");
3747 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003748 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003749
3750 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003751 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003752 getLocationFromExpr(getCursorExpr(C)));
3753
Douglas Gregor36897b02010-09-10 00:22:18 +00003754 if (clang_isStatement(C.kind))
3755 return cxloc::translateSourceLocation(getCursorContext(C),
3756 getCursorStmt(C)->getLocStart());
3757
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003758 if (C.kind == CXCursor_PreprocessingDirective) {
3759 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3760 return cxloc::translateSourceLocation(getCursorContext(C), L);
3761 }
Douglas Gregor48072312010-03-18 15:23:44 +00003762
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003763 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003764 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003765 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003766 return cxloc::translateSourceLocation(getCursorContext(C), L);
3767 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003768
3769 if (C.kind == CXCursor_MacroDefinition) {
3770 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3771 return cxloc::translateSourceLocation(getCursorContext(C), L);
3772 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003773
3774 if (C.kind == CXCursor_InclusionDirective) {
3775 SourceLocation L
3776 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3777 return cxloc::translateSourceLocation(getCursorContext(C), L);
3778 }
3779
Ted Kremenek9a700d22010-05-12 06:16:13 +00003780 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003781 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003782
Douglas Gregorf46034a2010-01-18 23:41:10 +00003783 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003784 SourceLocation Loc = D->getLocation();
3785 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3786 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003787 // FIXME: Multiple variables declared in a single declaration
3788 // currently lack the information needed to correctly determine their
3789 // ranges when accounting for the type-specifier. We use context
3790 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3791 // and if so, whether it is the first decl.
3792 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3793 if (!cxcursor::isFirstInDeclGroup(C))
3794 Loc = VD->getLocation();
3795 }
3796
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003797 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003798}
Douglas Gregora7bde202010-01-19 00:34:46 +00003799
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003800} // end extern "C"
3801
3802static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003803 if (clang_isReference(C.kind)) {
3804 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003805 case CXCursor_ObjCSuperClassRef:
3806 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003807
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003808 case CXCursor_ObjCProtocolRef:
3809 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003810
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003811 case CXCursor_ObjCClassRef:
3812 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003813
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003814 case CXCursor_TypeRef:
3815 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003816
3817 case CXCursor_TemplateRef:
3818 return getCursorTemplateRef(C).second;
3819
Douglas Gregor69319002010-08-31 23:48:11 +00003820 case CXCursor_NamespaceRef:
3821 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003822
3823 case CXCursor_MemberRef:
3824 return getCursorMemberRef(C).second;
3825
Ted Kremenek3064ef92010-08-27 21:34:58 +00003826 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003827 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003828
Douglas Gregor36897b02010-09-10 00:22:18 +00003829 case CXCursor_LabelRef:
3830 return getCursorLabelRef(C).second;
3831
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003832 case CXCursor_OverloadedDeclRef:
3833 return getCursorOverloadedDeclRef(C).second;
3834
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003835 default:
3836 // FIXME: Need a way to enumerate all non-reference cases.
3837 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003838 }
3839 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003840
3841 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003842 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003843
3844 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003845 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003847 if (clang_isAttribute(C.kind))
3848 return getCursorAttr(C)->getRange();
3849
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003850 if (C.kind == CXCursor_PreprocessingDirective)
3851 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003852
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003853 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003854 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003855
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003856 if (C.kind == CXCursor_MacroDefinition)
3857 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003858
3859 if (C.kind == CXCursor_InclusionDirective)
3860 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3861
Ted Kremenek007a7c92010-11-01 23:26:51 +00003862 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3863 Decl *D = cxcursor::getCursorDecl(C);
3864 SourceRange R = D->getSourceRange();
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());
3873 }
3874 return R;
3875 }
Douglas Gregor66537982010-11-17 17:14:07 +00003876 return SourceRange();
3877}
3878
3879/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3880/// the decl-specifier-seq for declarations.
3881static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3882 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3883 Decl *D = cxcursor::getCursorDecl(C);
3884 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003885
Douglas Gregor2494dd02011-03-01 01:34:45 +00003886 // Adjust the start of the location for declarations preceded by
3887 // declaration specifiers.
3888 SourceLocation StartLoc;
3889 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3890 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3891 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3892 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3893 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3894 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3895 }
3896
3897 if (StartLoc.isValid() && R.getBegin().isValid() &&
3898 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3899 R.setBegin(StartLoc);
3900
3901 // FIXME: Multiple variables declared in a single declaration
3902 // currently lack the information needed to correctly determine their
3903 // ranges when accounting for the type-specifier. We use context
3904 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3905 // and if so, whether it is the first decl.
3906 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3907 if (!cxcursor::isFirstInDeclGroup(C))
3908 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003909 }
3910
3911 return R;
3912 }
3913
3914 return getRawCursorExtent(C);
3915}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003916
3917extern "C" {
3918
3919CXSourceRange clang_getCursorExtent(CXCursor C) {
3920 SourceRange R = getRawCursorExtent(C);
3921 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003922 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003923
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003924 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003925}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003926
3927CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003928 if (clang_isInvalid(C.kind))
3929 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003930
Ted Kremeneka60ed472010-11-16 08:15:36 +00003931 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003932 if (clang_isDeclaration(C.kind)) {
3933 Decl *D = getCursorDecl(C);
3934 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003935 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003936 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003937 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003938 if (ObjCForwardProtocolDecl *Protocols
3939 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003940 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003941 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003942 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3943 return MakeCXCursor(Property, tu);
3944
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003945 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003946 }
3947
Douglas Gregor97b98722010-01-19 23:20:36 +00003948 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003949 Expr *E = getCursorExpr(C);
3950 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003951 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003952 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003953
3954 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003955 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003956
Douglas Gregor97b98722010-01-19 23:20:36 +00003957 return clang_getNullCursor();
3958 }
3959
Douglas Gregor36897b02010-09-10 00:22:18 +00003960 if (clang_isStatement(C.kind)) {
3961 Stmt *S = getCursorStmt(C);
3962 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003963 if (LabelDecl *label = Goto->getLabel())
3964 if (LabelStmt *labelS = label->getStmt())
3965 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003966
3967 return clang_getNullCursor();
3968 }
3969
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003970 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003971 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003972 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003973 }
3974
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003975 if (!clang_isReference(C.kind))
3976 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003977
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003978 switch (C.kind) {
3979 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003980 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003981
3982 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003983 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003984
3985 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003986 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003987
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003988 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003989 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003990
3991 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003992 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003993
Douglas Gregor69319002010-08-31 23:48:11 +00003994 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003995 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003996
Douglas Gregora67e03f2010-09-09 21:42:20 +00003997 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003998 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003999
Ted Kremenek3064ef92010-08-27 21:34:58 +00004000 case CXCursor_CXXBaseSpecifier: {
4001 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4002 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004003 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004004 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004005
Douglas Gregor36897b02010-09-10 00:22:18 +00004006 case CXCursor_LabelRef:
4007 // FIXME: We end up faking the "parent" declaration here because we
4008 // don't want to make CXCursor larger.
4009 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004010 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4011 .getTranslationUnitDecl(),
4012 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004013
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004014 case CXCursor_OverloadedDeclRef:
4015 return C;
4016
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004017 default:
4018 // We would prefer to enumerate all non-reference cursor kinds here.
4019 llvm_unreachable("Unhandled reference cursor kind");
4020 break;
4021 }
4022 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004023
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004024 return clang_getNullCursor();
4025}
4026
Douglas Gregorb6998662010-01-19 19:34:47 +00004027CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004028 if (clang_isInvalid(C.kind))
4029 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004030
Ted Kremeneka60ed472010-11-16 08:15:36 +00004031 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004032
Douglas Gregorb6998662010-01-19 19:34:47 +00004033 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004034 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004035 C = clang_getCursorReferenced(C);
4036 WasReference = true;
4037 }
4038
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004039 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004040 return clang_getCursorReferenced(C);
4041
Douglas Gregorb6998662010-01-19 19:34:47 +00004042 if (!clang_isDeclaration(C.kind))
4043 return clang_getNullCursor();
4044
4045 Decl *D = getCursorDecl(C);
4046 if (!D)
4047 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004048
Douglas Gregorb6998662010-01-19 19:34:47 +00004049 switch (D->getKind()) {
4050 // Declaration kinds that don't really separate the notions of
4051 // declaration and definition.
4052 case Decl::Namespace:
4053 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004054 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004055 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004056 case Decl::TemplateTypeParm:
4057 case Decl::EnumConstant:
4058 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004059 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004060 case Decl::ObjCIvar:
4061 case Decl::ObjCAtDefsField:
4062 case Decl::ImplicitParam:
4063 case Decl::ParmVar:
4064 case Decl::NonTypeTemplateParm:
4065 case Decl::TemplateTemplateParm:
4066 case Decl::ObjCCategoryImpl:
4067 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004068 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004069 case Decl::LinkageSpec:
4070 case Decl::ObjCPropertyImpl:
4071 case Decl::FileScopeAsm:
4072 case Decl::StaticAssert:
4073 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004074 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004075 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004076 return C;
4077
4078 // Declaration kinds that don't make any sense here, but are
4079 // nonetheless harmless.
4080 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004081 break;
4082
4083 // Declaration kinds for which the definition is not resolvable.
4084 case Decl::UnresolvedUsingTypename:
4085 case Decl::UnresolvedUsingValue:
4086 break;
4087
4088 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004089 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004090 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004091
4092 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004093 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004094
4095 case Decl::Enum:
4096 case Decl::Record:
4097 case Decl::CXXRecord:
4098 case Decl::ClassTemplateSpecialization:
4099 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004100 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004101 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004102 return clang_getNullCursor();
4103
4104 case Decl::Function:
4105 case Decl::CXXMethod:
4106 case Decl::CXXConstructor:
4107 case Decl::CXXDestructor:
4108 case Decl::CXXConversion: {
4109 const FunctionDecl *Def = 0;
4110 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004111 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004112 return clang_getNullCursor();
4113 }
4114
4115 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004116 // Ask the variable if it has a definition.
4117 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004118 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004119 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004120 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004121
Douglas Gregorb6998662010-01-19 19:34:47 +00004122 case Decl::FunctionTemplate: {
4123 const FunctionDecl *Def = 0;
4124 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004125 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004126 return clang_getNullCursor();
4127 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004128
Douglas Gregorb6998662010-01-19 19:34:47 +00004129 case Decl::ClassTemplate: {
4130 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004131 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004132 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004133 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004134 return clang_getNullCursor();
4135 }
4136
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004137 case Decl::Using:
4138 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004139 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004140
4141 case Decl::UsingShadow:
4142 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004143 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004144 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004145
4146 case Decl::ObjCMethod: {
4147 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4148 if (Method->isThisDeclarationADefinition())
4149 return C;
4150
4151 // Dig out the method definition in the associated
4152 // @implementation, if we have it.
4153 // FIXME: The ASTs should make finding the definition easier.
4154 if (ObjCInterfaceDecl *Class
4155 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4156 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4157 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4158 Method->isInstanceMethod()))
4159 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004160 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004161
4162 return clang_getNullCursor();
4163 }
4164
4165 case Decl::ObjCCategory:
4166 if (ObjCCategoryImplDecl *Impl
4167 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004168 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004169 return clang_getNullCursor();
4170
4171 case Decl::ObjCProtocol:
4172 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4173 return C;
4174 return clang_getNullCursor();
4175
4176 case Decl::ObjCInterface:
4177 // There are two notions of a "definition" for an Objective-C
4178 // class: the interface and its implementation. When we resolved a
4179 // reference to an Objective-C class, produce the @interface as
4180 // the definition; when we were provided with the interface,
4181 // produce the @implementation as the definition.
4182 if (WasReference) {
4183 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4184 return C;
4185 } else if (ObjCImplementationDecl *Impl
4186 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004187 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004188 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004189
Douglas Gregorb6998662010-01-19 19:34:47 +00004190 case Decl::ObjCProperty:
4191 // FIXME: We don't really know where to find the
4192 // ObjCPropertyImplDecls that implement this property.
4193 return clang_getNullCursor();
4194
4195 case Decl::ObjCCompatibleAlias:
4196 if (ObjCInterfaceDecl *Class
4197 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4198 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004199 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004200
Douglas Gregorb6998662010-01-19 19:34:47 +00004201 return clang_getNullCursor();
4202
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004203 case Decl::ObjCForwardProtocol:
4204 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004205 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004206
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004207 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004208 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004209 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004210
4211 case Decl::Friend:
4212 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004213 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004214 return clang_getNullCursor();
4215
4216 case Decl::FriendTemplate:
4217 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004218 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004219 return clang_getNullCursor();
4220 }
4221
4222 return clang_getNullCursor();
4223}
4224
4225unsigned clang_isCursorDefinition(CXCursor C) {
4226 if (!clang_isDeclaration(C.kind))
4227 return 0;
4228
4229 return clang_getCursorDefinition(C) == C;
4230}
4231
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004232CXCursor clang_getCanonicalCursor(CXCursor C) {
4233 if (!clang_isDeclaration(C.kind))
4234 return C;
4235
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004236 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004237 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4238 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4239 return MakeCXCursor(CatD, getCursorTU(C));
4240
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004241 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4242 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4243 return MakeCXCursor(IFD, getCursorTU(C));
4244
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004245 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004246 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004247
4248 return C;
4249}
4250
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004251unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004252 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004253 return 0;
4254
4255 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4256 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4257 return E->getNumDecls();
4258
4259 if (OverloadedTemplateStorage *S
4260 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4261 return S->size();
4262
4263 Decl *D = Storage.get<Decl*>();
4264 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004265 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004266 if (isa<ObjCClassDecl>(D))
4267 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004268 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4269 return Protocols->protocol_size();
4270
4271 return 0;
4272}
4273
4274CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004275 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004276 return clang_getNullCursor();
4277
4278 if (index >= clang_getNumOverloadedDecls(cursor))
4279 return clang_getNullCursor();
4280
Ted Kremeneka60ed472010-11-16 08:15:36 +00004281 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004282 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4283 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004284 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004285
4286 if (OverloadedTemplateStorage *S
4287 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004288 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004289
4290 Decl *D = Storage.get<Decl*>();
4291 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4292 // FIXME: This is, unfortunately, linear time.
4293 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4294 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004295 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004296 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004297 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004298 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004299 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004300 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004301
4302 return clang_getNullCursor();
4303}
4304
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004305void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004306 const char **startBuf,
4307 const char **endBuf,
4308 unsigned *startLine,
4309 unsigned *startColumn,
4310 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004311 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004312 assert(getCursorDecl(C) && "CXCursor has null decl");
4313 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004314 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4315 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004316
Steve Naroff4ade6d62009-09-23 17:52:52 +00004317 SourceManager &SM = FD->getASTContext().getSourceManager();
4318 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4319 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4320 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4321 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4322 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4323 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4324}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004325
Douglas Gregor430d7a12011-07-25 17:48:11 +00004326
4327CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4328 unsigned PieceIndex) {
4329 RefNamePieces Pieces;
4330
4331 switch (C.kind) {
4332 case CXCursor_MemberRefExpr:
4333 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4334 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4335 E->getQualifierLoc().getSourceRange());
4336 break;
4337
4338 case CXCursor_DeclRefExpr:
4339 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4340 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4341 E->getQualifierLoc().getSourceRange(),
4342 E->getExplicitTemplateArgsOpt());
4343 break;
4344
4345 case CXCursor_CallExpr:
4346 if (CXXOperatorCallExpr *OCE =
4347 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4348 Expr *Callee = OCE->getCallee();
4349 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4350 Callee = ICE->getSubExpr();
4351
4352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4353 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4354 DRE->getQualifierLoc().getSourceRange());
4355 }
4356 break;
4357
4358 default:
4359 break;
4360 }
4361
4362 if (Pieces.empty()) {
4363 if (PieceIndex == 0)
4364 return clang_getCursorExtent(C);
4365 } else if (PieceIndex < Pieces.size()) {
4366 SourceRange R = Pieces[PieceIndex];
4367 if (R.isValid())
4368 return cxloc::translateSourceRange(getCursorContext(C), R);
4369 }
4370
4371 return clang_getNullRange();
4372}
4373
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004374void clang_enableStackTraces(void) {
4375 llvm::sys::PrintStackTraceOnErrorSignal();
4376}
4377
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004378void clang_executeOnThread(void (*fn)(void*), void *user_data,
4379 unsigned stack_size) {
4380 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4381}
4382
Ted Kremenekfb480492010-01-13 21:46:36 +00004383} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004384
Ted Kremenekfb480492010-01-13 21:46:36 +00004385//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386// Token-based Operations.
4387//===----------------------------------------------------------------------===//
4388
4389/* CXToken layout:
4390 * int_data[0]: a CXTokenKind
4391 * int_data[1]: starting token location
4392 * int_data[2]: token length
4393 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004394 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004395 * otherwise unused.
4396 */
4397extern "C" {
4398
4399CXTokenKind clang_getTokenKind(CXToken CXTok) {
4400 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4401}
4402
4403CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4404 switch (clang_getTokenKind(CXTok)) {
4405 case CXToken_Identifier:
4406 case CXToken_Keyword:
4407 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004408 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4409 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004410
4411 case CXToken_Literal: {
4412 // We have stashed the starting pointer in the ptr_data field. Use it.
4413 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004414 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004415 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004416
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004417 case CXToken_Punctuation:
4418 case CXToken_Comment:
4419 break;
4420 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004421
4422 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004423 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004424 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004425 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004426 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004427
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004428 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4429 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004430 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004431 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004432 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004433 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4434 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004435 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004436
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004437 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004438}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004439
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004440CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004441 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004442 if (!CXXUnit)
4443 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004444
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004445 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4446 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4447}
4448
4449CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004450 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004451 if (!CXXUnit)
4452 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004453
4454 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004455 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4456}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004457
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004458void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4459 CXToken **Tokens, unsigned *NumTokens) {
4460 if (Tokens)
4461 *Tokens = 0;
4462 if (NumTokens)
4463 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004464
Ted Kremeneka60ed472010-11-16 08:15:36 +00004465 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004466 if (!CXXUnit || !Tokens || !NumTokens)
4467 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004468
Douglas Gregorbdf60622010-03-05 21:16:25 +00004469 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4470
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004471 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004472 if (R.isInvalid())
4473 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004474
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004475 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4476 std::pair<FileID, unsigned> BeginLocInfo
4477 = SourceMgr.getDecomposedLoc(R.getBegin());
4478 std::pair<FileID, unsigned> EndLocInfo
4479 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004480
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004481 // Cannot tokenize across files.
4482 if (BeginLocInfo.first != EndLocInfo.first)
4483 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004484
4485 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004486 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004487 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004488 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004489 if (Invalid)
4490 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004491
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004492 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4493 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004494 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004495 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004496
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004497 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004498 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004499 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004500 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004501 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004502 do {
4503 // Lex the next token
4504 Lex.LexFromRawLexer(Tok);
4505 if (Tok.is(tok::eof))
4506 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004507
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004508 // Initialize the CXToken.
4509 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004510
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004511 // - Common fields
4512 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4513 CXTok.int_data[2] = Tok.getLength();
4514 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004515
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004516 // - Kind-specific fields
4517 if (Tok.isLiteral()) {
4518 CXTok.int_data[0] = CXToken_Literal;
4519 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004520 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004521 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004522 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004523 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004524
David Chisnall096428b2010-10-13 21:44:48 +00004525 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004526 CXTok.int_data[0] = CXToken_Keyword;
4527 }
4528 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004529 CXTok.int_data[0] = Tok.is(tok::identifier)
4530 ? CXToken_Identifier
4531 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004532 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004533 CXTok.ptr_data = II;
4534 } else if (Tok.is(tok::comment)) {
4535 CXTok.int_data[0] = CXToken_Comment;
4536 CXTok.ptr_data = 0;
4537 } else {
4538 CXTok.int_data[0] = CXToken_Punctuation;
4539 CXTok.ptr_data = 0;
4540 }
4541 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004542 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004543 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004544
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004545 if (CXTokens.empty())
4546 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004547
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004548 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4549 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4550 *NumTokens = CXTokens.size();
4551}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004552
Ted Kremenek6db61092010-05-05 00:55:15 +00004553void clang_disposeTokens(CXTranslationUnit TU,
4554 CXToken *Tokens, unsigned NumTokens) {
4555 free(Tokens);
4556}
4557
4558} // end: extern "C"
4559
4560//===----------------------------------------------------------------------===//
4561// Token annotation APIs.
4562//===----------------------------------------------------------------------===//
4563
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004564typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004565static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4566 CXCursor parent,
4567 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004568namespace {
4569class AnnotateTokensWorker {
4570 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004571 CXToken *Tokens;
4572 CXCursor *Cursors;
4573 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004574 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004575 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004576 CursorVisitor AnnotateVis;
4577 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004578 bool HasContextSensitiveKeywords;
4579
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004580 bool MoreTokens() const { return TokIdx < NumTokens; }
4581 unsigned NextToken() const { return TokIdx; }
4582 void AdvanceToken() { ++TokIdx; }
4583 SourceLocation GetTokenLoc(unsigned tokI) {
4584 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4585 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004586 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004587 return Tokens[tokI].int_data[3] != 0;
4588 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004589 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004590 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4591 }
4592
4593 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004594 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4595 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004596
Ted Kremenek6db61092010-05-05 00:55:15 +00004597public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004598 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004599 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004600 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004601 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004602 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004603 AnnotateVis(tu,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00004604 AnnotateTokensVisitor, this, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004605 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4606 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004607
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004608 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004609 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004610 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004611 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004612 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004613 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004614
4615 /// \brief Determine whether the annotator saw any cursors that have
4616 /// context-sensitive keywords.
4617 bool hasContextSensitiveKeywords() const {
4618 return HasContextSensitiveKeywords;
4619 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004620};
4621}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004622
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004623void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4624 // Walk the AST within the region of interest, annotating tokens
4625 // along the way.
4626 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004627
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004628 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4629 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004630 if (Pos != Annotated.end() &&
4631 (clang_isInvalid(Cursors[I].kind) ||
4632 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004633 Cursors[I] = Pos->second;
4634 }
4635
4636 // Finish up annotating any tokens left.
4637 if (!MoreTokens())
4638 return;
4639
4640 const CXCursor &C = clang_getNullCursor();
4641 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4642 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4643 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004644 }
4645}
4646
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004647/// \brief It annotates and advances tokens with a cursor until the comparison
4648//// between the cursor location and the source range is the same as
4649/// \arg compResult.
4650///
4651/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4652/// Pass RangeOverlap to annotate tokens inside a range.
4653void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4654 RangeComparisonResult compResult,
4655 SourceRange range) {
4656 while (MoreTokens()) {
4657 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004658 if (isFunctionMacroToken(I))
4659 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004660
4661 SourceLocation TokLoc = GetTokenLoc(I);
4662 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4663 Cursors[I] = updateC;
4664 AdvanceToken();
4665 continue;
4666 }
4667 break;
4668 }
4669}
4670
4671/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004672void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4673 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004674 RangeComparisonResult compResult,
4675 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004676 assert(MoreTokens());
4677 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004678 "Should be called only for macro arg tokens");
4679
4680 // This works differently than annotateAndAdvanceTokens; because expanded
4681 // macro arguments can have arbitrary translation-unit source order, we do not
4682 // advance the token index one by one until a token fails the range test.
4683 // We only advance once past all of the macro arg tokens if all of them
4684 // pass the range test. If one of them fails we keep the token index pointing
4685 // at the start of the macro arg tokens so that the failing token will be
4686 // annotated by a subsequent annotation try.
4687
4688 bool atLeastOneCompFail = false;
4689
4690 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004691 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4692 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004693 if (TokLoc.isFileID())
4694 continue; // not macro arg token, it's parens or comma.
4695 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4696 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4697 Cursors[I] = updateC;
4698 } else
4699 atLeastOneCompFail = true;
4700 }
4701
4702 if (!atLeastOneCompFail)
4703 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4704}
4705
Ted Kremenek6db61092010-05-05 00:55:15 +00004706enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004707AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004708 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004709 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004710 if (cursorRange.isInvalid())
4711 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004712
4713 if (!HasContextSensitiveKeywords) {
4714 // Objective-C properties can have context-sensitive keywords.
4715 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4716 if (ObjCPropertyDecl *Property
4717 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4718 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4719 }
4720 // Objective-C methods can have context-sensitive keywords.
4721 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4722 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4723 if (ObjCMethodDecl *Method
4724 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4725 if (Method->getObjCDeclQualifier())
4726 HasContextSensitiveKeywords = true;
4727 else {
4728 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4729 PEnd = Method->param_end();
4730 P != PEnd; ++P) {
4731 if ((*P)->getObjCDeclQualifier()) {
4732 HasContextSensitiveKeywords = true;
4733 break;
4734 }
4735 }
4736 }
4737 }
4738 }
4739 // C++ methods can have context-sensitive keywords.
4740 else if (cursor.kind == CXCursor_CXXMethod) {
4741 if (CXXMethodDecl *Method
4742 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4743 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4744 HasContextSensitiveKeywords = true;
4745 }
4746 }
4747 // C++ classes can have context-sensitive keywords.
4748 else if (cursor.kind == CXCursor_StructDecl ||
4749 cursor.kind == CXCursor_ClassDecl ||
4750 cursor.kind == CXCursor_ClassTemplate ||
4751 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4752 if (Decl *D = getCursorDecl(cursor))
4753 if (D->hasAttr<FinalAttr>())
4754 HasContextSensitiveKeywords = true;
4755 }
4756 }
4757
Douglas Gregor4419b672010-10-21 06:10:04 +00004758 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004759 // For macro expansions, just note where the beginning of the macro
4760 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004761 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004762 Annotated[Loc.int_data] = cursor;
4763 return CXChildVisit_Recurse;
4764 }
4765
Douglas Gregor4419b672010-10-21 06:10:04 +00004766 // Items in the preprocessing record are kept separate from items in
4767 // declarations, so we keep a separate token index.
4768 unsigned SavedTokIdx = TokIdx;
4769 TokIdx = PreprocessingTokIdx;
4770
4771 // Skip tokens up until we catch up to the beginning of the preprocessing
4772 // entry.
4773 while (MoreTokens()) {
4774 const unsigned I = NextToken();
4775 SourceLocation TokLoc = GetTokenLoc(I);
4776 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4777 case RangeBefore:
4778 AdvanceToken();
4779 continue;
4780 case RangeAfter:
4781 case RangeOverlap:
4782 break;
4783 }
4784 break;
4785 }
4786
4787 // Look at all of the tokens within this range.
4788 while (MoreTokens()) {
4789 const unsigned I = NextToken();
4790 SourceLocation TokLoc = GetTokenLoc(I);
4791 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4792 case RangeBefore:
4793 assert(0 && "Infeasible");
4794 case RangeAfter:
4795 break;
4796 case RangeOverlap:
4797 Cursors[I] = cursor;
4798 AdvanceToken();
4799 continue;
4800 }
4801 break;
4802 }
4803
4804 // Save the preprocessing token index; restore the non-preprocessing
4805 // token index.
4806 PreprocessingTokIdx = TokIdx;
4807 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004808 return CXChildVisit_Recurse;
4809 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004810
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004811 if (cursorRange.isInvalid())
4812 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004813
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004814 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4815
Ted Kremeneka333c662010-05-12 05:29:33 +00004816 // Adjust the annotated range based specific declarations.
4817 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4818 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004819 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004820
4821 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004822 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004823 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4824 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4825 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4826 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4827 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004828 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004829
4830 if (StartLoc.isValid() && L.isValid() &&
4831 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4832 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004833 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004834
Ted Kremenek3f404602010-08-14 01:14:06 +00004835 // If the location of the cursor occurs within a macro instantiation, record
4836 // the spelling location of the cursor in our annotation map. We can then
4837 // paper over the token labelings during a post-processing step to try and
4838 // get cursor mappings for tokens that are the *arguments* of a macro
4839 // instantiation.
4840 if (L.isMacroID()) {
4841 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4842 // Only invalidate the old annotation if it isn't part of a preprocessing
4843 // directive. Here we assume that the default construction of CXCursor
4844 // results in CXCursor.kind being an initialized value (i.e., 0). If
4845 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004846
Ted Kremenek3f404602010-08-14 01:14:06 +00004847 CXCursor &oldC = Annotated[rawEncoding];
4848 if (!clang_isPreprocessing(oldC.kind))
4849 oldC = cursor;
4850 }
4851
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004852 const enum CXCursorKind K = clang_getCursorKind(parent);
4853 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004854 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4855 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004856
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004857 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004858
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004859 // Avoid having the cursor of an expression "overwrite" the annotation of the
4860 // variable declaration that it belongs to.
4861 // This can happen for C++ constructor expressions whose range generally
4862 // include the variable declaration, e.g.:
4863 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4864 if (clang_isExpression(cursorK)) {
4865 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004866 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004867 const unsigned I = NextToken();
4868 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4869 E->getLocStart() == D->getLocation() &&
4870 E->getLocStart() == GetTokenLoc(I)) {
4871 Cursors[I] = updateC;
4872 AdvanceToken();
4873 }
4874 }
4875 }
4876
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004877 // Visit children to get their cursor information.
4878 const unsigned BeforeChildren = NextToken();
4879 VisitChildren(cursor);
4880 const unsigned AfterChildren = NextToken();
4881
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004882 // Scan the tokens that are at the end of the cursor, but are not captured
4883 // but the child cursors.
4884 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004885
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004886 // Scan the tokens that are at the beginning of the cursor, but are not
4887 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004888 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4889 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4890 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004891
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004892 Cursors[I] = cursor;
4893 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004894
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004895 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004896}
4897
Ted Kremenek6db61092010-05-05 00:55:15 +00004898static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4899 CXCursor parent,
4900 CXClientData client_data) {
4901 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4902}
4903
Ted Kremenek6628a612011-03-18 22:51:30 +00004904namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004905
4906/// \brief Uses the macro expansions in the preprocessing record to find
4907/// and mark tokens that are macro arguments. This info is used by the
4908/// AnnotateTokensWorker.
4909class MarkMacroArgTokensVisitor {
4910 SourceManager &SM;
4911 CXToken *Tokens;
4912 unsigned NumTokens;
4913 unsigned CurIdx;
4914
4915public:
4916 MarkMacroArgTokensVisitor(SourceManager &SM,
4917 CXToken *tokens, unsigned numTokens)
4918 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4919
4920 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4921 if (cursor.kind != CXCursor_MacroExpansion)
4922 return CXChildVisit_Continue;
4923
4924 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4925 if (macroRange.getBegin() == macroRange.getEnd())
4926 return CXChildVisit_Continue; // it's not a function macro.
4927
4928 for (; CurIdx < NumTokens; ++CurIdx) {
4929 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4930 macroRange.getBegin()))
4931 break;
4932 }
4933
4934 if (CurIdx == NumTokens)
4935 return CXChildVisit_Break;
4936
4937 for (; CurIdx < NumTokens; ++CurIdx) {
4938 SourceLocation tokLoc = getTokenLoc(CurIdx);
4939 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4940 break;
4941
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004942 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004943 }
4944
4945 if (CurIdx == NumTokens)
4946 return CXChildVisit_Break;
4947
4948 return CXChildVisit_Continue;
4949 }
4950
4951private:
4952 SourceLocation getTokenLoc(unsigned tokI) {
4953 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4954 }
4955
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004956 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004957 // The third field is reserved and currently not used. Use it here
4958 // to mark macro arg expanded tokens with their expanded locations.
4959 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4960 }
4961};
4962
4963} // end anonymous namespace
4964
4965static CXChildVisitResult
4966MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4967 CXClientData client_data) {
4968 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4969 parent);
4970}
4971
4972namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004973 struct clang_annotateTokens_Data {
4974 CXTranslationUnit TU;
4975 ASTUnit *CXXUnit;
4976 CXToken *Tokens;
4977 unsigned NumTokens;
4978 CXCursor *Cursors;
4979 };
4980}
4981
Ted Kremenekab979612010-11-11 08:05:23 +00004982// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004983static void clang_annotateTokensImpl(void *UserData) {
4984 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4985 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4986 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4987 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4988 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4989
4990 // Determine the region of interest, which contains all of the tokens.
4991 SourceRange RegionOfInterest;
4992 RegionOfInterest.setBegin(
4993 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4994 RegionOfInterest.setEnd(
4995 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4996 Tokens[NumTokens-1])));
4997
4998 // A mapping from the source locations found when re-lexing or traversing the
4999 // region of interest to the corresponding cursors.
5000 AnnotateTokensData Annotated;
5001
5002 // Relex the tokens within the source range to look for preprocessing
5003 // directives.
5004 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5005 std::pair<FileID, unsigned> BeginLocInfo
5006 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5007 std::pair<FileID, unsigned> EndLocInfo
5008 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5009
Chris Lattner5f9e2722011-07-23 10:55:15 +00005010 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00005011 bool Invalid = false;
5012 if (BeginLocInfo.first == EndLocInfo.first &&
5013 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
5014 !Invalid) {
5015 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5016 CXXUnit->getASTContext().getLangOptions(),
5017 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5018 Buffer.end());
5019 Lex.SetCommentRetentionState(true);
5020
5021 // Lex tokens in raw mode until we hit the end of the range, to avoid
5022 // entering #includes or expanding macros.
5023 while (true) {
5024 Token Tok;
5025 Lex.LexFromRawLexer(Tok);
5026
5027 reprocess:
5028 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5029 // We have found a preprocessing directive. Gobble it up so that we
5030 // don't see it while preprocessing these tokens later, but keep track
5031 // of all of the token locations inside this preprocessing directive so
5032 // that we can annotate them appropriately.
5033 //
5034 // FIXME: Some simple tests here could identify macro definitions and
5035 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005036 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00005037 do {
5038 Locations.push_back(Tok.getLocation());
5039 Lex.LexFromRawLexer(Tok);
5040 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5041
5042 using namespace cxcursor;
5043 CXCursor Cursor
5044 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5045 Locations.back()),
5046 TU);
5047 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5048 Annotated[Locations[I].getRawEncoding()] = Cursor;
5049 }
5050
5051 if (Tok.isAtStartOfLine())
5052 goto reprocess;
5053
5054 continue;
5055 }
5056
5057 if (Tok.is(tok::eof))
5058 break;
5059 }
5060 }
5061
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005062 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5063 // Search and mark tokens that are macro argument expansions.
5064 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5065 Tokens, NumTokens);
5066 CursorVisitor MacroArgMarker(TU,
5067 MarkMacroArgTokensVisitorDelegate, &Visitor,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00005068 true, RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005069 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5070 }
5071
Ted Kremenek6628a612011-03-18 22:51:30 +00005072 // Annotate all of the source locations in the region of interest that map to
5073 // a specific cursor.
5074 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5075 TU, RegionOfInterest);
5076
5077 // FIXME: We use a ridiculous stack size here because the data-recursion
5078 // algorithm uses a large stack frame than the non-data recursive version,
5079 // and AnnotationTokensWorker currently transforms the data-recursion
5080 // algorithm back into a traditional recursion by explicitly calling
5081 // VisitChildren(). We will need to remove this explicit recursive call.
5082 W.AnnotateTokens();
5083
5084 // If we ran into any entities that involve context-sensitive keywords,
5085 // take another pass through the tokens to mark them as such.
5086 if (W.hasContextSensitiveKeywords()) {
5087 for (unsigned I = 0; I != NumTokens; ++I) {
5088 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5089 continue;
5090
5091 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5092 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5093 if (ObjCPropertyDecl *Property
5094 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5095 if (Property->getPropertyAttributesAsWritten() != 0 &&
5096 llvm::StringSwitch<bool>(II->getName())
5097 .Case("readonly", true)
5098 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005099 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005100 .Case("readwrite", true)
5101 .Case("retain", true)
5102 .Case("copy", true)
5103 .Case("nonatomic", true)
5104 .Case("atomic", true)
5105 .Case("getter", true)
5106 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005107 .Case("strong", true)
5108 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005109 .Default(false))
5110 Tokens[I].int_data[0] = CXToken_Keyword;
5111 }
5112 continue;
5113 }
5114
5115 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5116 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5117 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5118 if (llvm::StringSwitch<bool>(II->getName())
5119 .Case("in", true)
5120 .Case("out", true)
5121 .Case("inout", true)
5122 .Case("oneway", true)
5123 .Case("bycopy", true)
5124 .Case("byref", true)
5125 .Default(false))
5126 Tokens[I].int_data[0] = CXToken_Keyword;
5127 continue;
5128 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005129
5130 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5131 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5132 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005133 continue;
5134 }
5135 }
5136 }
Ted Kremenekab979612010-11-11 08:05:23 +00005137}
5138
Ted Kremenek6db61092010-05-05 00:55:15 +00005139extern "C" {
5140
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005141void clang_annotateTokens(CXTranslationUnit TU,
5142 CXToken *Tokens, unsigned NumTokens,
5143 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005144
5145 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005146 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005147
Douglas Gregor4419b672010-10-21 06:10:04 +00005148 // Any token we don't specifically annotate will have a NULL cursor.
5149 CXCursor C = clang_getNullCursor();
5150 for (unsigned I = 0; I != NumTokens; ++I)
5151 Cursors[I] = C;
5152
Ted Kremeneka60ed472010-11-16 08:15:36 +00005153 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005154 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005155 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005156
Douglas Gregorbdf60622010-03-05 21:16:25 +00005157 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005158
5159 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005160 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005161 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005162 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005163 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5164 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005165}
Ted Kremenek6628a612011-03-18 22:51:30 +00005166
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005167} // end: extern "C"
5168
5169//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005170// Operations for querying linkage of a cursor.
5171//===----------------------------------------------------------------------===//
5172
5173extern "C" {
5174CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005175 if (!clang_isDeclaration(cursor.kind))
5176 return CXLinkage_Invalid;
5177
Ted Kremenek16b42592010-03-03 06:36:57 +00005178 Decl *D = cxcursor::getCursorDecl(cursor);
5179 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5180 switch (ND->getLinkage()) {
5181 case NoLinkage: return CXLinkage_NoLinkage;
5182 case InternalLinkage: return CXLinkage_Internal;
5183 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5184 case ExternalLinkage: return CXLinkage_External;
5185 };
5186
5187 return CXLinkage_Invalid;
5188}
5189} // end: extern "C"
5190
5191//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005192// Operations for querying language of a cursor.
5193//===----------------------------------------------------------------------===//
5194
5195static CXLanguageKind getDeclLanguage(const Decl *D) {
5196 switch (D->getKind()) {
5197 default:
5198 break;
5199 case Decl::ImplicitParam:
5200 case Decl::ObjCAtDefsField:
5201 case Decl::ObjCCategory:
5202 case Decl::ObjCCategoryImpl:
5203 case Decl::ObjCClass:
5204 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005205 case Decl::ObjCForwardProtocol:
5206 case Decl::ObjCImplementation:
5207 case Decl::ObjCInterface:
5208 case Decl::ObjCIvar:
5209 case Decl::ObjCMethod:
5210 case Decl::ObjCProperty:
5211 case Decl::ObjCPropertyImpl:
5212 case Decl::ObjCProtocol:
5213 return CXLanguage_ObjC;
5214 case Decl::CXXConstructor:
5215 case Decl::CXXConversion:
5216 case Decl::CXXDestructor:
5217 case Decl::CXXMethod:
5218 case Decl::CXXRecord:
5219 case Decl::ClassTemplate:
5220 case Decl::ClassTemplatePartialSpecialization:
5221 case Decl::ClassTemplateSpecialization:
5222 case Decl::Friend:
5223 case Decl::FriendTemplate:
5224 case Decl::FunctionTemplate:
5225 case Decl::LinkageSpec:
5226 case Decl::Namespace:
5227 case Decl::NamespaceAlias:
5228 case Decl::NonTypeTemplateParm:
5229 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005230 case Decl::TemplateTemplateParm:
5231 case Decl::TemplateTypeParm:
5232 case Decl::UnresolvedUsingTypename:
5233 case Decl::UnresolvedUsingValue:
5234 case Decl::Using:
5235 case Decl::UsingDirective:
5236 case Decl::UsingShadow:
5237 return CXLanguage_CPlusPlus;
5238 }
5239
5240 return CXLanguage_C;
5241}
5242
5243extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005244
5245enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5246 if (clang_isDeclaration(cursor.kind))
5247 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005248 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005249 return CXAvailability_Available;
5250
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005251 switch (D->getAvailability()) {
5252 case AR_Available:
5253 case AR_NotYetIntroduced:
5254 return CXAvailability_Available;
5255
5256 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005257 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005258
5259 case AR_Unavailable:
5260 return CXAvailability_NotAvailable;
5261 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005262 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005263
Douglas Gregor58ddb602010-08-23 23:00:57 +00005264 return CXAvailability_Available;
5265}
5266
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005267CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5268 if (clang_isDeclaration(cursor.kind))
5269 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5270
5271 return CXLanguage_Invalid;
5272}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005273
5274 /// \brief If the given cursor is the "templated" declaration
5275 /// descibing a class or function template, return the class or
5276 /// function template.
5277static Decl *maybeGetTemplateCursor(Decl *D) {
5278 if (!D)
5279 return 0;
5280
5281 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5282 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5283 return FunTmpl;
5284
5285 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5286 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5287 return ClassTmpl;
5288
5289 return D;
5290}
5291
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005292CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5293 if (clang_isDeclaration(cursor.kind)) {
5294 if (Decl *D = getCursorDecl(cursor)) {
5295 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005296 if (!DC)
5297 return clang_getNullCursor();
5298
5299 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5300 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005301 }
5302 }
5303
5304 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5305 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005306 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005307 }
5308
5309 return clang_getNullCursor();
5310}
5311
5312CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5313 if (clang_isDeclaration(cursor.kind)) {
5314 if (Decl *D = getCursorDecl(cursor)) {
5315 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005316 if (!DC)
5317 return clang_getNullCursor();
5318
5319 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5320 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005321 }
5322 }
5323
5324 // FIXME: Note that we can't easily compute the lexical context of a
5325 // statement or expression, so we return nothing.
5326 return clang_getNullCursor();
5327}
5328
Douglas Gregor9f592342010-10-01 20:25:15 +00005329static void CollectOverriddenMethods(DeclContext *Ctx,
5330 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005331 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005332 if (!Ctx)
5333 return;
5334
5335 // If we have a class or category implementation, jump straight to the
5336 // interface.
5337 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5338 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5339
5340 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5341 if (!Container)
5342 return;
5343
5344 // Check whether we have a matching method at this level.
5345 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5346 Method->isInstanceMethod()))
5347 if (Method != Overridden) {
5348 // We found an override at this level; there is no need to look
5349 // into other protocols or categories.
5350 Methods.push_back(Overridden);
5351 return;
5352 }
5353
5354 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5355 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5356 PEnd = Protocol->protocol_end();
5357 P != PEnd; ++P)
5358 CollectOverriddenMethods(*P, Method, Methods);
5359 }
5360
5361 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5362 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5363 PEnd = Category->protocol_end();
5364 P != PEnd; ++P)
5365 CollectOverriddenMethods(*P, Method, Methods);
5366 }
5367
5368 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5369 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5370 PEnd = Interface->protocol_end();
5371 P != PEnd; ++P)
5372 CollectOverriddenMethods(*P, Method, Methods);
5373
5374 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5375 Category; Category = Category->getNextClassCategory())
5376 CollectOverriddenMethods(Category, Method, Methods);
5377
5378 // We only look into the superclass if we haven't found anything yet.
5379 if (Methods.empty())
5380 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5381 return CollectOverriddenMethods(Super, Method, Methods);
5382 }
5383}
5384
5385void clang_getOverriddenCursors(CXCursor cursor,
5386 CXCursor **overridden,
5387 unsigned *num_overridden) {
5388 if (overridden)
5389 *overridden = 0;
5390 if (num_overridden)
5391 *num_overridden = 0;
5392 if (!overridden || !num_overridden)
5393 return;
5394
5395 if (!clang_isDeclaration(cursor.kind))
5396 return;
5397
5398 Decl *D = getCursorDecl(cursor);
5399 if (!D)
5400 return;
5401
5402 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005403 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005404 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5405 *num_overridden = CXXMethod->size_overridden_methods();
5406 if (!*num_overridden)
5407 return;
5408
5409 *overridden = new CXCursor [*num_overridden];
5410 unsigned I = 0;
5411 for (CXXMethodDecl::method_iterator
5412 M = CXXMethod->begin_overridden_methods(),
5413 MEnd = CXXMethod->end_overridden_methods();
5414 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005415 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005416 return;
5417 }
5418
5419 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5420 if (!Method)
5421 return;
5422
5423 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005424 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005425 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5426
5427 if (Methods.empty())
5428 return;
5429
5430 *num_overridden = Methods.size();
5431 *overridden = new CXCursor [Methods.size()];
5432 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005433 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005434}
5435
5436void clang_disposeOverriddenCursors(CXCursor *overridden) {
5437 delete [] overridden;
5438}
5439
Douglas Gregorecdcb882010-10-20 22:00:55 +00005440CXFile clang_getIncludedFile(CXCursor cursor) {
5441 if (cursor.kind != CXCursor_InclusionDirective)
5442 return 0;
5443
5444 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5445 return (void *)ID->getFile();
5446}
5447
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005448} // end: extern "C"
5449
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005450
5451//===----------------------------------------------------------------------===//
5452// C++ AST instrospection.
5453//===----------------------------------------------------------------------===//
5454
5455extern "C" {
5456unsigned clang_CXXMethod_isStatic(CXCursor C) {
5457 if (!clang_isDeclaration(C.kind))
5458 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005459
5460 CXXMethodDecl *Method = 0;
5461 Decl *D = cxcursor::getCursorDecl(C);
5462 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5463 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5464 else
5465 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5466 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005467}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005468
Douglas Gregor211924b2011-05-12 15:17:24 +00005469unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5470 if (!clang_isDeclaration(C.kind))
5471 return 0;
5472
5473 CXXMethodDecl *Method = 0;
5474 Decl *D = cxcursor::getCursorDecl(C);
5475 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5476 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5477 else
5478 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5479 return (Method && Method->isVirtual()) ? 1 : 0;
5480}
5481
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005482} // end: extern "C"
5483
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005484//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005485// Attribute introspection.
5486//===----------------------------------------------------------------------===//
5487
5488extern "C" {
5489CXType clang_getIBOutletCollectionType(CXCursor C) {
5490 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005491 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005492
5493 IBOutletCollectionAttr *A =
5494 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5495
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005496 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005497}
5498} // end: extern "C"
5499
5500//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005501// Inspecting memory usage.
5502//===----------------------------------------------------------------------===//
5503
Ted Kremenekf7870022011-04-20 16:41:07 +00005504typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005505
Ted Kremenekf7870022011-04-20 16:41:07 +00005506static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5507 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005508 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005509 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005510 entries.push_back(entry);
5511}
5512
5513extern "C" {
5514
Ted Kremenekf7870022011-04-20 16:41:07 +00005515const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005516 const char *str = "";
5517 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005518 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005519 str = "ASTContext: expressions, declarations, and types";
5520 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005521 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005522 str = "ASTContext: identifiers";
5523 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005524 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005525 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005526 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005527 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005528 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005529 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005530 case CXTUResourceUsage_SourceManagerContentCache:
5531 str = "SourceManager: content cache allocator";
5532 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005533 case CXTUResourceUsage_AST_SideTables:
5534 str = "ASTContext: side tables";
5535 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005536 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5537 str = "SourceManager: malloc'ed memory buffers";
5538 break;
5539 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5540 str = "SourceManager: mmap'ed memory buffers";
5541 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005542 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5543 str = "ExternalASTSource: malloc'ed memory buffers";
5544 break;
5545 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5546 str = "ExternalASTSource: mmap'ed memory buffers";
5547 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005548 case CXTUResourceUsage_Preprocessor:
5549 str = "Preprocessor: malloc'ed memory";
5550 break;
5551 case CXTUResourceUsage_PreprocessingRecord:
5552 str = "Preprocessor: PreprocessingRecord";
5553 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005554 case CXTUResourceUsage_SourceManager_DataStructures:
5555 str = "SourceManager: data structures and tables";
5556 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005557 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5558 str = "Preprocessor: header search tables";
5559 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005560 }
5561 return str;
5562}
5563
Ted Kremenekf7870022011-04-20 16:41:07 +00005564CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005565 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005566 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005567 return usage;
5568 }
5569
5570 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5571 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5572 ASTContext &astContext = astUnit->getASTContext();
5573
5574 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005575 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005576 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005577
5578 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005579 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005580 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5581
5582 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005583 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005584 (unsigned long) astContext.Selectors.getTotalMemory());
5585
Ted Kremenekba29bd22011-04-28 04:53:38 +00005586 // How much memory is used by ASTContext's side tables?
5587 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5588 (unsigned long) astContext.getSideTableAllocatedMemory());
5589
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005590 // How much memory is used for caching global code completion results?
5591 unsigned long completionBytes = 0;
5592 if (GlobalCodeCompletionAllocator *completionAllocator =
5593 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005594 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005595 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005596 createCXTUResourceUsageEntry(*entries,
5597 CXTUResourceUsage_GlobalCompletionResults,
5598 completionBytes);
5599
5600 // How much memory is being used by SourceManager's content cache?
5601 createCXTUResourceUsageEntry(*entries,
5602 CXTUResourceUsage_SourceManagerContentCache,
5603 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005604
5605 // How much memory is being used by the MemoryBuffer's in SourceManager?
5606 const SourceManager::MemoryBufferSizes &srcBufs =
5607 astUnit->getSourceManager().getMemoryBufferSizes();
5608
5609 createCXTUResourceUsageEntry(*entries,
5610 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5611 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005612 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005613 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5614 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005615 createCXTUResourceUsageEntry(*entries,
5616 CXTUResourceUsage_SourceManager_DataStructures,
5617 (unsigned long) astContext.getSourceManager()
5618 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005619
5620 // How much memory is being used by the ExternalASTSource?
5621 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5622 const ExternalASTSource::MemoryBufferSizes &sizes =
5623 esrc->getMemoryBufferSizes();
5624
5625 createCXTUResourceUsageEntry(*entries,
5626 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5627 (unsigned long) sizes.malloc_bytes);
5628 createCXTUResourceUsageEntry(*entries,
5629 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5630 (unsigned long) sizes.mmap_bytes);
5631 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005632
5633 // How much memory is being used by the Preprocessor?
5634 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005635 createCXTUResourceUsageEntry(*entries,
5636 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005637 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005638
5639 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5640 createCXTUResourceUsageEntry(*entries,
5641 CXTUResourceUsage_PreprocessingRecord,
5642 pRec->getTotalMemory());
5643 }
5644
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005645 createCXTUResourceUsageEntry(*entries,
5646 CXTUResourceUsage_Preprocessor_HeaderSearch,
5647 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005648
Ted Kremenekf7870022011-04-20 16:41:07 +00005649 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005650 (unsigned) entries->size(),
5651 entries->size() ? &(*entries)[0] : 0 };
5652 entries.take();
5653 return usage;
5654}
5655
Ted Kremenekf7870022011-04-20 16:41:07 +00005656void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005657 if (usage.data)
5658 delete (MemUsageEntries*) usage.data;
5659}
5660
5661} // end extern "C"
5662
Douglas Gregor6df78732011-05-05 20:27:22 +00005663void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5664 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5665 for (unsigned I = 0; I != Usage.numEntries; ++I)
5666 fprintf(stderr, " %s: %lu\n",
5667 clang_getTUResourceUsageName(Usage.entries[I].kind),
5668 Usage.entries[I].amount);
5669
5670 clang_disposeCXTUResourceUsage(Usage);
5671}
5672
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005673//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005674// Misc. utility functions.
5675//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005676
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005677/// Default to using an 8 MB stack size on "safety" threads.
5678static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005679
5680namespace clang {
5681
5682bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005683 void (*Fn)(void*), void *UserData,
5684 unsigned Size) {
5685 if (!Size)
5686 Size = GetSafetyThreadStackSize();
5687 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005688 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5689 return CRC.RunSafely(Fn, UserData);
5690}
5691
5692unsigned GetSafetyThreadStackSize() {
5693 return SafetyStackThreadSize;
5694}
5695
5696void SetSafetyThreadStackSize(unsigned Value) {
5697 SafetyStackThreadSize = Value;
5698}
5699
5700}
5701
Ted Kremenek04bb7162010-01-22 22:44:15 +00005702extern "C" {
5703
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005704CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005705 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005706}
5707
5708} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005709