blob: 5837e0412d92a049f8db4ad5d9ad659d69403054 [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 Gregor7d1d49d2009-10-16 20:01:17 +0000186 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
187 // to the visitor. Declarations with a PCH level greater than this value will
188 // be suppressed.
189 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000191 /// \brief Whether we should visit the preprocessing record entries last,
192 /// after visiting other declarations.
193 bool VisitPreprocessorLast;
194
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195 /// \brief When valid, a source range to which the cursor should restrict
196 /// its search.
197 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000198
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000199 // FIXME: Eventually remove. This part of a hack to support proper
200 // iteration over all Decls contained lexically within an ObjC container.
201 DeclContext::decl_iterator *DI_current;
202 DeclContext::decl_iterator DE_current;
203
Ted Kremenekd1ded662010-11-15 23:31:32 +0000204 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000205 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
206 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000207
Douglas Gregorb1373d02010-01-20 20:59:29 +0000208 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000209 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
211 /// \brief Determine whether this particular source range comes before, comes
212 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000214 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
216
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000217 class SetParentRAII {
218 CXCursor &Parent;
219 Decl *&StmtParent;
220 CXCursor OldParent;
221
222 public:
223 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
224 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
225 {
226 Parent = NewParent;
227 if (clang_isDeclaration(Parent.kind))
228 StmtParent = getCursorDecl(Parent);
229 }
230
231 ~SetParentRAII() {
232 Parent = OldParent;
233 if (clang_isDeclaration(Parent.kind))
234 StmtParent = getCursorDecl(Parent);
235 }
236 };
237
Steve Naroff89922f82009-08-31 00:59:03 +0000238public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000239 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
240 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000241 unsigned MaxPCHLevel,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000242 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000243 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000244 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
245 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000246 MaxPCHLevel(MaxPCHLevel), VisitPreprocessorLast(VisitPreprocessorLast),
247 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 {
249 Parent.kind = CXCursor_NoDeclFound;
250 Parent.data[0] = 0;
251 Parent.data[1] = 0;
252 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000253 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000254 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000255
Ted Kremenekd1ded662010-11-15 23:31:32 +0000256 ~CursorVisitor() {
257 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000258 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000259 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
260 delete *I;
261 }
262 }
263
Ted Kremeneka60ed472010-11-16 08:15:36 +0000264 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
265 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000266
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000267 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000268
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000269 bool visitPreprocessedEntitiesInRegion();
270
271 template<typename InputIterator>
272 bool visitPreprocessedEntitiesInRegion(InputIterator First,
273 InputIterator Last);
274
275 template<typename InputIterator>
276 bool visitPreprocessedEntities(InputIterator First, InputIterator Last);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000277
Douglas Gregorb1373d02010-01-20 20:59:29 +0000278 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000279
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000280 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000281 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000282 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000283 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000284 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000285 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000286 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000287 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
288 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000290 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000291 bool VisitClassTemplatePartialSpecializationDecl(
292 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000293 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitEnumConstantDecl(EnumConstantDecl *D);
295 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
296 bool VisitFunctionDecl(FunctionDecl *ND);
297 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000298 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000299 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000300 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000301 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000302 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000303 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
304 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
305 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
306 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000307 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000308 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
309 bool VisitObjCImplDecl(ObjCImplDecl *D);
310 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
311 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000312 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
313 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
314 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000315 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000316 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000317 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000318 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000319 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000320 bool VisitUsingDecl(UsingDecl *D);
321 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
322 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000323
Douglas Gregor01829d32010-08-31 14:41:23 +0000324 // Name visitor
325 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000326 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000327 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000328
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000329 // Template visitors
330 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000331 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000332 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
333
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000334 // Type visitors
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000335#define ABSTRACT_TYPELOC(CLASS, PARENT)
336#define TYPELOC(CLASS, PARENT) \
337 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
338#include "clang/AST/TypeLocNodes.def"
339
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000340 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000341 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000342 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
343
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000344 // Data-recursive visitor functions.
345 bool IsInRegionOfInterest(CXCursor C);
346 bool RunVisitorWorkList(VisitorWorkList &WL);
347 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000348 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000349};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000350
Ted Kremenekab188932010-01-05 19:32:54 +0000351} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000352
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000353static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000354static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
355
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000356
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000358 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359}
360
Douglas Gregorb1373d02010-01-20 20:59:29 +0000361/// \brief Visit the given cursor and, if requested by the visitor,
362/// its children.
363///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000364/// \param Cursor the cursor to visit.
365///
366/// \param CheckRegionOfInterest if true, then the caller already checked that
367/// this cursor is within the region of interest.
368///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369/// \returns true if the visitation should be aborted, false if it
370/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 if (clang_isInvalid(Cursor.kind))
373 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000374
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 if (clang_isDeclaration(Cursor.kind)) {
376 Decl *D = getCursorDecl(Cursor);
377 assert(D && "Invalid declaration cursor");
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +0000378 if (D->getPCHLevel() > MaxPCHLevel && !isa<TranslationUnitDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379 return false;
380
381 if (D->isImplicit())
382 return false;
383 }
384
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385 // If we have a range of interest, and this cursor doesn't intersect with it,
386 // we're done.
387 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000388 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000389 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390 return false;
391 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000392
Douglas Gregorb1373d02010-01-20 20:59:29 +0000393 switch (Visitor(Cursor, Parent, ClientData)) {
394 case CXChildVisit_Break:
395 return true;
396
397 case CXChildVisit_Continue:
398 return false;
399
400 case CXChildVisit_Recurse:
401 return VisitChildren(Cursor);
402 }
403
Douglas Gregorfd643772010-01-25 16:45:46 +0000404 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405}
406
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000407bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000408 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000409 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000410
411 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000412 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
413
414 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
415 // If we would only look at local declarations but we have a region of
416 // interest, check whether that region of interest is in the main file.
417 // If not, we should traverse all declarations.
418 // FIXME: My kingdom for a proper binary search approach to finding
419 // cursors!
420 std::pair<FileID, unsigned> Location
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000421 = AU->getSourceManager().getDecomposedExpansionLoc(
Douglas Gregor32038bb2010-12-21 19:07:48 +0000422 RegionOfInterest.getBegin());
423 if (Location.first != AU->getSourceManager().getMainFileID())
424 OnlyLocalDecls = false;
425 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000426
Douglas Gregor89d99802010-11-30 06:16:57 +0000427 PreprocessingRecord::iterator StartEntity, EndEntity;
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000428 if (OnlyLocalDecls && AU->pp_entity_begin() != AU->pp_entity_end())
429 return visitPreprocessedEntitiesInRegion(AU->pp_entity_begin(),
430 AU->pp_entity_end());
431 else
432 return visitPreprocessedEntitiesInRegion(PPRec.begin(), PPRec.end());
433}
434
435template<typename InputIterator>
436bool CursorVisitor::visitPreprocessedEntitiesInRegion(InputIterator First,
437 InputIterator Last) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000438 // There is no region of interest; we have to walk everything.
439 if (RegionOfInterest.isInvalid())
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000440 return visitPreprocessedEntities(First, Last);
441
Douglas Gregor788f5a12010-03-20 00:41:21 +0000442 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000443 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000444 std::pair<FileID, unsigned> Begin
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000445 = SM.getDecomposedExpansionLoc(RegionOfInterest.getBegin());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000446 std::pair<FileID, unsigned> End
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000447 = SM.getDecomposedExpansionLoc(RegionOfInterest.getEnd());
Douglas Gregor788f5a12010-03-20 00:41:21 +0000448
449 // The region of interest spans files; we have to walk everything.
450 if (Begin.first != End.first)
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000451 return visitPreprocessedEntities(First, Last);
452
Douglas Gregor788f5a12010-03-20 00:41:21 +0000453 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000454 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000455 if (ByFileMap.empty()) {
456 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000457 for (; First != Last; ++First) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000458 std::pair<FileID, unsigned> P
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000459 = SM.getDecomposedExpansionLoc((*First)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000460
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000461 ByFileMap[P.first].push_back(*First);
462 }
463 }
464
465 return visitPreprocessedEntities(ByFileMap[Begin.first].begin(),
466 ByFileMap[Begin.first].end());
467}
468
469template<typename InputIterator>
470bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
471 InputIterator Last) {
472 for (; First != Last; ++First) {
473 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
474 if (Visit(MakeMacroExpansionCursor(ME, TU)))
475 return true;
476
477 continue;
478 }
479
480 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
481 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
482 return true;
483
484 continue;
485 }
486
487 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
488 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
489 return true;
490
491 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000492 }
493 }
494
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000495 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000496}
497
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000499///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500/// \returns true if the visitation should be aborted, false if it
501/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000502bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000503 if (clang_isReference(Cursor.kind) &&
504 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000505 // By definition, references have no children.
506 return false;
507 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000508
509 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000510 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000511 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000512
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 if (clang_isDeclaration(Cursor.kind)) {
514 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000515 if (!D)
516 return false;
517
Ted Kremenek539311e2010-02-18 18:47:01 +0000518 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000519 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000520
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000521 if (clang_isStatement(Cursor.kind)) {
522 if (Stmt *S = getCursorStmt(Cursor))
523 return Visit(S);
524
525 return false;
526 }
527
528 if (clang_isExpression(Cursor.kind)) {
529 if (Expr *E = getCursorExpr(Cursor))
530 return Visit(E);
531
532 return false;
533 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000534
Douglas Gregorb1373d02010-01-20 20:59:29 +0000535 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000536 CXTranslationUnit tu = getCursorTU(Cursor);
537 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000538
539 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
540 for (unsigned I = 0; I != 2; ++I) {
541 if (VisitOrder[I]) {
542 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
543 RegionOfInterest.isInvalid()) {
544 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
545 TLEnd = CXXUnit->top_level_end();
546 TL != TLEnd; ++TL) {
547 if (Visit(MakeCXCursor(*TL, tu), true))
548 return true;
549 }
550 } else if (VisitDeclContext(
551 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000552 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000553 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000554 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000555
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000556 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000557 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
558 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000559 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000560
Douglas Gregor7b691f332010-01-20 21:13:59 +0000561 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000562 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000563
Douglas Gregorc314aa42011-03-02 19:17:03 +0000564 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
565 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
566 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
567 return Visit(BaseTSInfo->getTypeLoc());
568 }
569 }
570 }
571
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000573 return false;
574}
575
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000576bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000577 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
578 if (Visit(TSInfo->getTypeLoc()))
579 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000580
Ted Kremenek664cffd2010-07-22 11:30:19 +0000581 if (Stmt *Body = B->getBody())
582 return Visit(MakeCXCursor(Body, StmtParent, TU));
583
584 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000585}
586
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000587llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
588 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000589 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000590 if (Range.isInvalid())
591 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000592
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000593 switch (CompareRegionOfInterest(Range)) {
594 case RangeBefore:
595 // This declaration comes before the region of interest; skip it.
596 return llvm::Optional<bool>();
597
598 case RangeAfter:
599 // This declaration comes after the region of interest; we're done.
600 return false;
601
602 case RangeOverlap:
603 // This declaration overlaps the region of interest; visit it.
604 break;
605 }
606 }
607 return true;
608}
609
610bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
611 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
612
613 // FIXME: Eventually remove. This part of a hack to support proper
614 // iteration over all Decls contained lexically within an ObjC container.
615 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
616 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
617
618 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000619 Decl *D = *I;
620 if (D->getLexicalDeclContext() != DC)
621 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000622 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000623 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
624 if (!V.hasValue())
625 continue;
626 if (!V.getValue())
627 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000628 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000629 return true;
630 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000631 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000632}
633
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000634bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
635 llvm_unreachable("Translation units are visited directly by Visit()");
636 return false;
637}
638
Richard Smith162e1c12011-04-15 14:24:37 +0000639bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
640 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
641 return Visit(TSInfo->getTypeLoc());
642
643 return false;
644}
645
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000646bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
647 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
648 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000649
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000650 return false;
651}
652
653bool CursorVisitor::VisitTagDecl(TagDecl *D) {
654 return VisitDeclContext(D);
655}
656
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000657bool CursorVisitor::VisitClassTemplateSpecializationDecl(
658 ClassTemplateSpecializationDecl *D) {
659 bool ShouldVisitBody = false;
660 switch (D->getSpecializationKind()) {
661 case TSK_Undeclared:
662 case TSK_ImplicitInstantiation:
663 // Nothing to visit
664 return false;
665
666 case TSK_ExplicitInstantiationDeclaration:
667 case TSK_ExplicitInstantiationDefinition:
668 break;
669
670 case TSK_ExplicitSpecialization:
671 ShouldVisitBody = true;
672 break;
673 }
674
675 // Visit the template arguments used in the specialization.
676 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
677 TypeLoc TL = SpecType->getTypeLoc();
678 if (TemplateSpecializationTypeLoc *TSTLoc
679 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
680 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
681 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
682 return true;
683 }
684 }
685
686 if (ShouldVisitBody && VisitCXXRecordDecl(D))
687 return true;
688
689 return false;
690}
691
Douglas Gregor74dbe642010-08-31 19:31:58 +0000692bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
693 ClassTemplatePartialSpecializationDecl *D) {
694 // FIXME: Visit the "outer" template parameter lists on the TagDecl
695 // before visiting these template parameters.
696 if (VisitTemplateParameters(D->getTemplateParameters()))
697 return true;
698
699 // Visit the partial specialization arguments.
700 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
701 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
702 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
703 return true;
704
705 return VisitCXXRecordDecl(D);
706}
707
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000708bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000709 // Visit the default argument.
710 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
711 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
712 if (Visit(DefArg->getTypeLoc()))
713 return true;
714
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000715 return false;
716}
717
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000718bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
719 if (Expr *Init = D->getInitExpr())
720 return Visit(MakeCXCursor(Init, StmtParent, TU));
721 return false;
722}
723
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000724bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
725 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
726 if (Visit(TSInfo->getTypeLoc()))
727 return true;
728
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000729 // Visit the nested-name-specifier, if present.
730 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
731 if (VisitNestedNameSpecifierLoc(QualifierLoc))
732 return true;
733
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000734 return false;
735}
736
Douglas Gregora67e03f2010-09-09 21:42:20 +0000737/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000738static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
739 CXXCtorInitializer const * const *X
740 = static_cast<CXXCtorInitializer const * const *>(Xp);
741 CXXCtorInitializer const * const *Y
742 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000743
744 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
745 return -1;
746 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
747 return 1;
748 else
749 return 0;
750}
751
Douglas Gregorb1373d02010-01-20 20:59:29 +0000752bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000753 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
754 // Visit the function declaration's syntactic components in the order
755 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000756 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000757 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
758
759 // If we have a function declared directly (without the use of a typedef),
760 // visit just the return type. Otherwise, just visit the function's type
761 // now.
762 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
763 (!FTL && Visit(TL)))
764 return true;
765
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000766 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000767 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
768 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000769 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000770
771 // Visit the declaration name.
772 if (VisitDeclarationNameInfo(ND->getNameInfo()))
773 return true;
774
775 // FIXME: Visit explicitly-specified template arguments!
776
777 // Visit the function parameters, if we have a function type.
778 if (FTL && VisitFunctionTypeLoc(*FTL, true))
779 return true;
780
781 // FIXME: Attributes?
782 }
783
Sean Hunt10620eb2011-05-06 20:44:56 +0000784 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000785 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
786 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000787 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000788 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
789 IEnd = Constructor->init_end();
790 I != IEnd; ++I) {
791 if (!(*I)->isWritten())
792 continue;
793
794 WrittenInits.push_back(*I);
795 }
796
797 // Sort the initializers in source order
798 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000799 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000800
801 // Visit the initializers in source order
802 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000803 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000804 if (Init->isAnyMemberInitializer()) {
805 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000806 Init->getMemberLocation(), TU)))
807 return true;
808 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
809 if (Visit(BaseInfo->getTypeLoc()))
810 return true;
811 }
812
813 // Visit the initializer value.
814 if (Expr *Initializer = Init->getInit())
815 if (Visit(MakeCXCursor(Initializer, ND, TU)))
816 return true;
817 }
818 }
819
820 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
821 return true;
822 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000823
Douglas Gregorb1373d02010-01-20 20:59:29 +0000824 return false;
825}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000826
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000827bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
828 if (VisitDeclaratorDecl(D))
829 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000830
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000831 if (Expr *BitWidth = D->getBitWidth())
832 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000834 return false;
835}
836
837bool CursorVisitor::VisitVarDecl(VarDecl *D) {
838 if (VisitDeclaratorDecl(D))
839 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841 if (Expr *Init = D->getInit())
842 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000843
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000844 return false;
845}
846
Douglas Gregor84b51d72010-09-01 20:16:53 +0000847bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
848 if (VisitDeclaratorDecl(D))
849 return true;
850
851 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
852 if (Expr *DefArg = D->getDefaultArgument())
853 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
854
855 return false;
856}
857
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000858bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
859 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
860 // before visiting these template parameters.
861 if (VisitTemplateParameters(D->getTemplateParameters()))
862 return true;
863
864 return VisitFunctionDecl(D->getTemplatedDecl());
865}
866
Douglas Gregor39d6f072010-08-31 19:02:00 +0000867bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
868 // FIXME: Visit the "outer" template parameter lists on the TagDecl
869 // before visiting these template parameters.
870 if (VisitTemplateParameters(D->getTemplateParameters()))
871 return true;
872
873 return VisitCXXRecordDecl(D->getTemplatedDecl());
874}
875
Douglas Gregor84b51d72010-09-01 20:16:53 +0000876bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
877 if (VisitTemplateParameters(D->getTemplateParameters()))
878 return true;
879
880 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
881 VisitTemplateArgumentLoc(D->getDefaultArgument()))
882 return true;
883
884 return false;
885}
886
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000887bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000888 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
889 if (Visit(TSInfo->getTypeLoc()))
890 return true;
891
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000892 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000893 PEnd = ND->param_end();
894 P != PEnd; ++P) {
895 if (Visit(MakeCXCursor(*P, TU)))
896 return true;
897 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000898
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000899 if (ND->isThisDeclarationADefinition() &&
900 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
901 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000903 return false;
904}
905
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000906namespace {
907 struct ContainerDeclsSort {
908 SourceManager &SM;
909 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
910 bool operator()(Decl *A, Decl *B) {
911 SourceLocation L_A = A->getLocStart();
912 SourceLocation L_B = B->getLocStart();
913 assert(L_A.isValid() && L_B.isValid());
914 return SM.isBeforeInTranslationUnit(L_A, L_B);
915 }
916 };
917}
918
Douglas Gregora59e3902010-01-21 23:27:09 +0000919bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000920 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
921 // an @implementation can lexically contain Decls that are not properly
922 // nested in the AST. When we identify such cases, we need to retrofit
923 // this nesting here.
924 if (!DI_current)
925 return VisitDeclContext(D);
926
927 // Scan the Decls that immediately come after the container
928 // in the current DeclContext. If any fall within the
929 // container's lexical region, stash them into a vector
930 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000931 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000932 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000933 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000934 if (EndLoc.isValid()) {
935 DeclContext::decl_iterator next = *DI_current;
936 while (++next != DE_current) {
937 Decl *D_next = *next;
938 if (!D_next)
939 break;
940 SourceLocation L = D_next->getLocStart();
941 if (!L.isValid())
942 break;
943 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
944 *DI_current = next;
945 DeclsInContainer.push_back(D_next);
946 continue;
947 }
948 break;
949 }
950 }
951
952 // The common case.
953 if (DeclsInContainer.empty())
954 return VisitDeclContext(D);
955
956 // Get all the Decls in the DeclContext, and sort them with the
957 // additional ones we've collected. Then visit them.
958 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
959 I!=E; ++I) {
960 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000961 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
962 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000963 continue;
964 DeclsInContainer.push_back(subDecl);
965 }
966
967 // Now sort the Decls so that they appear in lexical order.
968 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
969 ContainerDeclsSort(SM));
970
971 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000972 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000973 E = DeclsInContainer.end(); I != E; ++I) {
974 CXCursor Cursor = MakeCXCursor(*I, TU);
975 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
976 if (!V.hasValue())
977 continue;
978 if (!V.getValue())
979 return false;
980 if (Visit(Cursor, true))
981 return true;
982 }
983 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000984}
985
Douglas Gregorb1373d02010-01-20 20:59:29 +0000986bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000987 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
988 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000989 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000991 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
992 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
993 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000994 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000995 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000996
Douglas Gregora59e3902010-01-21 23:27:09 +0000997 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000998}
999
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001000bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1001 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1002 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1003 E = PID->protocol_end(); I != E; ++I, ++PL)
1004 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1005 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001007 return VisitObjCContainerDecl(PID);
1008}
1009
Ted Kremenek23173d72010-05-18 21:09:07 +00001010bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001011 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001012 return true;
1013
Ted Kremenek23173d72010-05-18 21:09:07 +00001014 // FIXME: This implements a workaround with @property declarations also being
1015 // installed in the DeclContext for the @interface. Eventually this code
1016 // should be removed.
1017 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1018 if (!CDecl || !CDecl->IsClassExtension())
1019 return false;
1020
1021 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1022 if (!ID)
1023 return false;
1024
1025 IdentifierInfo *PropertyId = PD->getIdentifier();
1026 ObjCPropertyDecl *prevDecl =
1027 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1028
1029 if (!prevDecl)
1030 return false;
1031
1032 // Visit synthesized methods since they will be skipped when visiting
1033 // the @interface.
1034 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001035 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001036 if (Visit(MakeCXCursor(MD, TU)))
1037 return true;
1038
1039 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001040 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001041 if (Visit(MakeCXCursor(MD, TU)))
1042 return true;
1043
1044 return false;
1045}
1046
Douglas Gregorb1373d02010-01-20 20:59:29 +00001047bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001048 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001049 if (D->getSuperClass() &&
1050 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001051 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001052 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001053 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001054
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001055 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1056 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1057 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001058 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001059 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
Douglas Gregora59e3902010-01-21 23:27:09 +00001061 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001062}
1063
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001064bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1065 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001066}
1067
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001068bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001069 // 'ID' could be null when dealing with invalid code.
1070 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1071 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1072 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001073
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001074 return VisitObjCImplDecl(D);
1075}
1076
1077bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1078#if 0
1079 // Issue callbacks for super class.
1080 // FIXME: No source location information!
1081 if (D->getSuperClass() &&
1082 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001083 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001084 TU)))
1085 return true;
1086#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001087
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001088 return VisitObjCImplDecl(D);
1089}
1090
1091bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1092 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1093 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1094 E = D->protocol_end();
1095 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001096 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001097 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001098
1099 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001100}
1101
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001102bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1103 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1104 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1105 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001106
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001107 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001108}
1109
Douglas Gregora4ffd852010-11-17 01:03:52 +00001110bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1111 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1112 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1113
1114 return false;
1115}
1116
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001117bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1118 return VisitDeclContext(D);
1119}
1120
Douglas Gregor69319002010-08-31 23:48:11 +00001121bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001122 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001123 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1124 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001125 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001126
1127 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1128 D->getTargetNameLoc(), TU));
1129}
1130
Douglas Gregor7e242562010-09-01 19:52:22 +00001131bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001132 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001133 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1134 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001135 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001136 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001137
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001138 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1139 return true;
1140
Douglas Gregor7e242562010-09-01 19:52:22 +00001141 return VisitDeclarationNameInfo(D->getNameInfo());
1142}
1143
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001144bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001145 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001146 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1147 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001148 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001149
1150 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1151 D->getIdentLocation(), TU));
1152}
1153
Douglas Gregor7e242562010-09-01 19:52:22 +00001154bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001155 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001156 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1157 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001158 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001159 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001160
Douglas Gregor7e242562010-09-01 19:52:22 +00001161 return VisitDeclarationNameInfo(D->getNameInfo());
1162}
1163
1164bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1165 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001166 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001167 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1168 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001169 return true;
1170
Douglas Gregor7e242562010-09-01 19:52:22 +00001171 return false;
1172}
1173
Douglas Gregor01829d32010-08-31 14:41:23 +00001174bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1175 switch (Name.getName().getNameKind()) {
1176 case clang::DeclarationName::Identifier:
1177 case clang::DeclarationName::CXXLiteralOperatorName:
1178 case clang::DeclarationName::CXXOperatorName:
1179 case clang::DeclarationName::CXXUsingDirective:
1180 return false;
1181
1182 case clang::DeclarationName::CXXConstructorName:
1183 case clang::DeclarationName::CXXDestructorName:
1184 case clang::DeclarationName::CXXConversionFunctionName:
1185 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1186 return Visit(TSInfo->getTypeLoc());
1187 return false;
1188
1189 case clang::DeclarationName::ObjCZeroArgSelector:
1190 case clang::DeclarationName::ObjCOneArgSelector:
1191 case clang::DeclarationName::ObjCMultiArgSelector:
1192 // FIXME: Per-identifier location info?
1193 return false;
1194 }
1195
1196 return false;
1197}
1198
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001199bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1200 SourceRange Range) {
1201 // FIXME: This whole routine is a hack to work around the lack of proper
1202 // source information in nested-name-specifiers (PR5791). Since we do have
1203 // a beginning source location, we can visit the first component of the
1204 // nested-name-specifier, if it's a single-token component.
1205 if (!NNS)
1206 return false;
1207
1208 // Get the first component in the nested-name-specifier.
1209 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1210 NNS = Prefix;
1211
1212 switch (NNS->getKind()) {
1213 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001214 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1215 TU));
1216
Douglas Gregor14aba762011-02-24 02:36:08 +00001217 case NestedNameSpecifier::NamespaceAlias:
1218 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1219 Range.getBegin(), TU));
1220
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001221 case NestedNameSpecifier::TypeSpec: {
1222 // If the type has a form where we know that the beginning of the source
1223 // range matches up with a reference cursor. Visit the appropriate reference
1224 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001225 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001226 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1227 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1228 if (const TagType *Tag = dyn_cast<TagType>(T))
1229 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1230 if (const TemplateSpecializationType *TST
1231 = dyn_cast<TemplateSpecializationType>(T))
1232 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1233 break;
1234 }
1235
1236 case NestedNameSpecifier::TypeSpecWithTemplate:
1237 case NestedNameSpecifier::Global:
1238 case NestedNameSpecifier::Identifier:
1239 break;
1240 }
1241
1242 return false;
1243}
1244
Douglas Gregordc355712011-02-25 00:36:19 +00001245bool
1246CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001247 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001248 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1249 Qualifiers.push_back(Qualifier);
1250
1251 while (!Qualifiers.empty()) {
1252 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1253 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1254 switch (NNS->getKind()) {
1255 case NestedNameSpecifier::Namespace:
1256 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001257 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001258 TU)))
1259 return true;
1260
1261 break;
1262
1263 case NestedNameSpecifier::NamespaceAlias:
1264 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001265 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001266 TU)))
1267 return true;
1268
1269 break;
1270
1271 case NestedNameSpecifier::TypeSpec:
1272 case NestedNameSpecifier::TypeSpecWithTemplate:
1273 if (Visit(Q.getTypeLoc()))
1274 return true;
1275
1276 break;
1277
1278 case NestedNameSpecifier::Global:
1279 case NestedNameSpecifier::Identifier:
1280 break;
1281 }
1282 }
1283
1284 return false;
1285}
1286
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001287bool CursorVisitor::VisitTemplateParameters(
1288 const TemplateParameterList *Params) {
1289 if (!Params)
1290 return false;
1291
1292 for (TemplateParameterList::const_iterator P = Params->begin(),
1293 PEnd = Params->end();
1294 P != PEnd; ++P) {
1295 if (Visit(MakeCXCursor(*P, TU)))
1296 return true;
1297 }
1298
1299 return false;
1300}
1301
Douglas Gregor0b36e612010-08-31 20:37:03 +00001302bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1303 switch (Name.getKind()) {
1304 case TemplateName::Template:
1305 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1306
1307 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001308 // Visit the overloaded template set.
1309 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1310 return true;
1311
Douglas Gregor0b36e612010-08-31 20:37:03 +00001312 return false;
1313
1314 case TemplateName::DependentTemplate:
1315 // FIXME: Visit nested-name-specifier.
1316 return false;
1317
1318 case TemplateName::QualifiedTemplate:
1319 // FIXME: Visit nested-name-specifier.
1320 return Visit(MakeCursorTemplateRef(
1321 Name.getAsQualifiedTemplateName()->getDecl(),
1322 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001323
1324 case TemplateName::SubstTemplateTemplateParm:
1325 return Visit(MakeCursorTemplateRef(
1326 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1327 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001328
1329 case TemplateName::SubstTemplateTemplateParmPack:
1330 return Visit(MakeCursorTemplateRef(
1331 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1332 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001333 }
1334
1335 return false;
1336}
1337
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001338bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1339 switch (TAL.getArgument().getKind()) {
1340 case TemplateArgument::Null:
1341 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001342 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001343 return false;
1344
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001345 case TemplateArgument::Type:
1346 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1347 return Visit(TSInfo->getTypeLoc());
1348 return false;
1349
1350 case TemplateArgument::Declaration:
1351 if (Expr *E = TAL.getSourceDeclExpression())
1352 return Visit(MakeCXCursor(E, StmtParent, TU));
1353 return false;
1354
1355 case TemplateArgument::Expression:
1356 if (Expr *E = TAL.getSourceExpression())
1357 return Visit(MakeCXCursor(E, StmtParent, TU));
1358 return false;
1359
1360 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001361 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001362 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1363 return true;
1364
Douglas Gregora7fc9012011-01-05 18:58:31 +00001365 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001366 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001367 }
1368
1369 return false;
1370}
1371
Ted Kremeneka0536d82010-05-07 01:04:29 +00001372bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1373 return VisitDeclContext(D);
1374}
1375
Douglas Gregor01829d32010-08-31 14:41:23 +00001376bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1377 return Visit(TL.getUnqualifiedLoc());
1378}
1379
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001381 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001382
1383 // Some builtin types (such as Objective-C's "id", "sel", and
1384 // "Class") have associated declarations. Create cursors for those.
1385 QualType VisitType;
1386 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001387 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001389 case BuiltinType::Char_U:
1390 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001391 case BuiltinType::Char16:
1392 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001393 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394 case BuiltinType::UInt:
1395 case BuiltinType::ULong:
1396 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001397 case BuiltinType::UInt128:
1398 case BuiltinType::Char_S:
1399 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001400 case BuiltinType::WChar_U:
1401 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001402 case BuiltinType::Short:
1403 case BuiltinType::Int:
1404 case BuiltinType::Long:
1405 case BuiltinType::LongLong:
1406 case BuiltinType::Int128:
1407 case BuiltinType::Float:
1408 case BuiltinType::Double:
1409 case BuiltinType::LongDouble:
1410 case BuiltinType::NullPtr:
1411 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001412 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001413 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001414 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001415 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001416
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001417 case BuiltinType::ObjCId:
1418 VisitType = Context.getObjCIdType();
1419 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001420
1421 case BuiltinType::ObjCClass:
1422 VisitType = Context.getObjCClassType();
1423 break;
1424
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001425 case BuiltinType::ObjCSel:
1426 VisitType = Context.getObjCSelType();
1427 break;
1428 }
1429
1430 if (!VisitType.isNull()) {
1431 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001432 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001433 TU));
1434 }
1435
1436 return false;
1437}
1438
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001439bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001440 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001441}
1442
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001443bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1444 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1445}
1446
1447bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001448 if (TL.isDefinition())
1449 return Visit(MakeCXCursor(TL.getDecl(), TU));
1450
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001451 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1452}
1453
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001454bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001455 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001456}
1457
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001458bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1459 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1460 return true;
1461
John McCallc12c5bb2010-05-15 11:32:37 +00001462 return false;
1463}
1464
1465bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1466 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1467 return true;
1468
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001469 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1470 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1471 TU)))
1472 return true;
1473 }
1474
1475 return false;
1476}
1477
1478bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001479 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001480}
1481
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001482bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1483 return Visit(TL.getInnerLoc());
1484}
1485
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001486bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1487 return Visit(TL.getPointeeLoc());
1488}
1489
1490bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1491 return Visit(TL.getPointeeLoc());
1492}
1493
1494bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1495 return Visit(TL.getPointeeLoc());
1496}
1497
1498bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001499 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001500}
1501
1502bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001503 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001504}
1505
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001506bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1507 return Visit(TL.getModifiedLoc());
1508}
1509
Douglas Gregor01829d32010-08-31 14:41:23 +00001510bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1511 bool SkipResultType) {
1512 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001513 return true;
1514
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001515 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001516 if (Decl *D = TL.getArg(I))
1517 if (Visit(MakeCXCursor(D, TU)))
1518 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001519
1520 return false;
1521}
1522
1523bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1524 if (Visit(TL.getElementLoc()))
1525 return true;
1526
1527 if (Expr *Size = TL.getSizeExpr())
1528 return Visit(MakeCXCursor(Size, StmtParent, TU));
1529
1530 return false;
1531}
1532
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001533bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1534 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001535 // Visit the template name.
1536 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1537 TL.getTemplateNameLoc()))
1538 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001539
1540 // Visit the template arguments.
1541 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1542 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1543 return true;
1544
1545 return false;
1546}
1547
Douglas Gregor2332c112010-01-21 20:48:56 +00001548bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1549 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1550}
1551
1552bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1553 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1554 return Visit(TSInfo->getTypeLoc());
1555
1556 return false;
1557}
1558
Sean Huntca63c202011-05-24 22:41:36 +00001559bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1560 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1561 return Visit(TSInfo->getTypeLoc());
1562
1563 return false;
1564}
1565
Douglas Gregor2494dd02011-03-01 01:34:45 +00001566bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1567 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1568 return true;
1569
1570 return false;
1571}
1572
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001573bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1574 DependentTemplateSpecializationTypeLoc TL) {
1575 // Visit the nested-name-specifier, if there is one.
1576 if (TL.getQualifierLoc() &&
1577 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1578 return true;
1579
1580 // Visit the template arguments.
1581 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1582 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1583 return true;
1584
1585 return false;
1586}
1587
Douglas Gregor9e876872011-03-01 18:12:44 +00001588bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1589 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1590 return true;
1591
1592 return Visit(TL.getNamedTypeLoc());
1593}
1594
Douglas Gregor7536dd52010-12-20 02:24:11 +00001595bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1596 return Visit(TL.getPatternLoc());
1597}
1598
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001599bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1600 if (Expr *E = TL.getUnderlyingExpr())
1601 return Visit(MakeCXCursor(E, StmtParent, TU));
1602
1603 return false;
1604}
1605
1606bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1607 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1608}
1609
1610#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1611bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1612 return Visit##PARENT##Loc(TL); \
1613}
1614
1615DEFAULT_TYPELOC_IMPL(Complex, Type)
1616DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1617DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1618DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1619DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1620DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1621DEFAULT_TYPELOC_IMPL(Vector, Type)
1622DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1623DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1624DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1625DEFAULT_TYPELOC_IMPL(Record, TagType)
1626DEFAULT_TYPELOC_IMPL(Enum, TagType)
1627DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1628DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1629DEFAULT_TYPELOC_IMPL(Auto, Type)
1630
Ted Kremenek3064ef92010-08-27 21:34:58 +00001631bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001632 // Visit the nested-name-specifier, if present.
1633 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1634 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1635 return true;
1636
Ted Kremenek3064ef92010-08-27 21:34:58 +00001637 if (D->isDefinition()) {
1638 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1639 E = D->bases_end(); I != E; ++I) {
1640 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1641 return true;
1642 }
1643 }
1644
1645 return VisitTagDecl(D);
1646}
1647
Ted Kremenek09dfa372010-02-18 05:46:33 +00001648bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001649 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1650 i != e; ++i)
1651 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001652 return true;
1653
1654 return false;
1655}
1656
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001657//===----------------------------------------------------------------------===//
1658// Data-recursive visitor methods.
1659//===----------------------------------------------------------------------===//
1660
Ted Kremenek28a71942010-11-13 00:36:47 +00001661namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001662#define DEF_JOB(NAME, DATA, KIND)\
1663class NAME : public VisitorJob {\
1664public:\
1665 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1666 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001667 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001668};
1669
1670DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1671DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001672DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001673DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001674DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1675 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001676DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001677#undef DEF_JOB
1678
1679class DeclVisit : public VisitorJob {
1680public:
1681 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1682 VisitorJob(parent, VisitorJob::DeclVisitKind,
1683 d, isFirst ? (void*) 1 : (void*) 0) {}
1684 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001685 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001686 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001687 Decl *get() const { return static_cast<Decl*>(data[0]); }
1688 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001689};
Ted Kremenek035dc412010-11-13 00:36:50 +00001690class TypeLocVisit : public VisitorJob {
1691public:
1692 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1693 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1694 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1695
1696 static bool classof(const VisitorJob *VJ) {
1697 return VJ->getKind() == TypeLocVisitKind;
1698 }
1699
Ted Kremenek82f3c502010-11-15 22:23:26 +00001700 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001701 QualType T = QualType::getFromOpaquePtr(data[0]);
1702 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001703 }
1704};
1705
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001706class LabelRefVisit : public VisitorJob {
1707public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001708 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1709 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001710 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001711
1712 static bool classof(const VisitorJob *VJ) {
1713 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1714 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001715 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001716 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001717 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001718};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001719
1720class NestedNameSpecifierLocVisit : public VisitorJob {
1721public:
1722 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1723 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1724 Qualifier.getNestedNameSpecifier(),
1725 Qualifier.getOpaqueData()) { }
1726
1727 static bool classof(const VisitorJob *VJ) {
1728 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1729 }
1730
1731 NestedNameSpecifierLoc get() const {
1732 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1733 data[1]);
1734 }
1735};
1736
Ted Kremenekf64d8032010-11-18 00:02:32 +00001737class DeclarationNameInfoVisit : public VisitorJob {
1738public:
1739 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1740 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1741 static bool classof(const VisitorJob *VJ) {
1742 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1743 }
1744 DeclarationNameInfo get() const {
1745 Stmt *S = static_cast<Stmt*>(data[0]);
1746 switch (S->getStmtClass()) {
1747 default:
1748 llvm_unreachable("Unhandled Stmt");
1749 case Stmt::CXXDependentScopeMemberExprClass:
1750 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1751 case Stmt::DependentScopeDeclRefExprClass:
1752 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1753 }
1754 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001755};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001756class MemberRefVisit : public VisitorJob {
1757public:
1758 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1759 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001760 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001761 static bool classof(const VisitorJob *VJ) {
1762 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1763 }
1764 FieldDecl *get() const {
1765 return static_cast<FieldDecl*>(data[0]);
1766 }
1767 SourceLocation getLoc() const {
1768 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1769 }
1770};
Ted Kremenek28a71942010-11-13 00:36:47 +00001771class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1772 VisitorWorkList &WL;
1773 CXCursor Parent;
1774public:
1775 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1776 : WL(wl), Parent(parent) {}
1777
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001778 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001779 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001780 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001781 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001782 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001783 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001784 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001785 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001786 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001787 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001788 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001789 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001790 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001791 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001792 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001793 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001794 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001795 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001796 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1797 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001798 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001799 void VisitIfStmt(IfStmt *If);
1800 void VisitInitListExpr(InitListExpr *IE);
1801 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001802 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001803 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001804 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1805 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001806 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001807 void VisitStmt(Stmt *S);
1808 void VisitSwitchStmt(SwitchStmt *S);
1809 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001810 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001811 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001812 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001813 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001814 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001815 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001816 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001817
Ted Kremenek28a71942010-11-13 00:36:47 +00001818private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001819 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001820 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001821 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001822 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001823 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001824 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001825 void AddTypeLoc(TypeSourceInfo *TI);
1826 void EnqueueChildren(Stmt *S);
1827};
1828} // end anonyous namespace
1829
Ted Kremenekf64d8032010-11-18 00:02:32 +00001830void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1831 // 'S' should always be non-null, since it comes from the
1832 // statement we are visiting.
1833 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1834}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001835
1836void
1837EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1838 if (Qualifier)
1839 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1840}
1841
Ted Kremenek28a71942010-11-13 00:36:47 +00001842void EnqueueVisitor::AddStmt(Stmt *S) {
1843 if (S)
1844 WL.push_back(StmtVisit(S, Parent));
1845}
Ted Kremenek035dc412010-11-13 00:36:50 +00001846void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001847 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001848 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001849}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001850void EnqueueVisitor::
1851 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1852 if (A)
1853 WL.push_back(ExplicitTemplateArgsVisit(
1854 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1855}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001856void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1857 if (D)
1858 WL.push_back(MemberRefVisit(D, L, Parent));
1859}
Ted Kremenek28a71942010-11-13 00:36:47 +00001860void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1861 if (TI)
1862 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1863 }
1864void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001865 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001866 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001867 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001868 }
1869 if (size == WL.size())
1870 return;
1871 // Now reverse the entries we just added. This will match the DFS
1872 // ordering performed by the worklist.
1873 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1874 std::reverse(I, E);
1875}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001876void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1877 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1878}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001879void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1880 AddDecl(B->getBlockDecl());
1881}
Ted Kremenek28a71942010-11-13 00:36:47 +00001882void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1883 EnqueueChildren(E);
1884 AddTypeLoc(E->getTypeSourceInfo());
1885}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001886void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1887 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1888 E = S->body_rend(); I != E; ++I) {
1889 AddStmt(*I);
1890 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001891}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001892void EnqueueVisitor::
1893VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1894 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1895 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001896 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1897 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001898 if (!E->isImplicitAccess())
1899 AddStmt(E->getBase());
1900}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001901void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1902 // Enqueue the initializer or constructor arguments.
1903 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1904 AddStmt(E->getConstructorArg(I-1));
1905 // Enqueue the array size, if any.
1906 AddStmt(E->getArraySize());
1907 // Enqueue the allocated type.
1908 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1909 // Enqueue the placement arguments.
1910 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1911 AddStmt(E->getPlacementArg(I-1));
1912}
Ted Kremenek28a71942010-11-13 00:36:47 +00001913void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001914 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1915 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001916 AddStmt(CE->getCallee());
1917 AddStmt(CE->getArg(0));
1918}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001919void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1920 // Visit the name of the type being destroyed.
1921 AddTypeLoc(E->getDestroyedTypeInfo());
1922 // Visit the scope type that looks disturbingly like the nested-name-specifier
1923 // but isn't.
1924 AddTypeLoc(E->getScopeTypeInfo());
1925 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001926 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1927 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001928 // Visit base expression.
1929 AddStmt(E->getBase());
1930}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001931void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1932 AddTypeLoc(E->getTypeSourceInfo());
1933}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001934void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1935 EnqueueChildren(E);
1936 AddTypeLoc(E->getTypeSourceInfo());
1937}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001938void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1939 EnqueueChildren(E);
1940 if (E->isTypeOperand())
1941 AddTypeLoc(E->getTypeOperandSourceInfo());
1942}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001943
1944void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1945 *E) {
1946 EnqueueChildren(E);
1947 AddTypeLoc(E->getTypeSourceInfo());
1948}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001949void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1950 EnqueueChildren(E);
1951 if (E->isTypeOperand())
1952 AddTypeLoc(E->getTypeOperandSourceInfo());
1953}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001954void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001955 if (DR->hasExplicitTemplateArgs()) {
1956 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1957 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001958 WL.push_back(DeclRefExprParts(DR, Parent));
1959}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001960void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1961 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1962 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001963 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001964}
Ted Kremenek035dc412010-11-13 00:36:50 +00001965void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1966 unsigned size = WL.size();
1967 bool isFirst = true;
1968 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1969 D != DEnd; ++D) {
1970 AddDecl(*D, isFirst);
1971 isFirst = false;
1972 }
1973 if (size == WL.size())
1974 return;
1975 // Now reverse the entries we just added. This will match the DFS
1976 // ordering performed by the worklist.
1977 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1978 std::reverse(I, E);
1979}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001980void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1981 AddStmt(E->getInit());
1982 typedef DesignatedInitExpr::Designator Designator;
1983 for (DesignatedInitExpr::reverse_designators_iterator
1984 D = E->designators_rbegin(), DEnd = E->designators_rend();
1985 D != DEnd; ++D) {
1986 if (D->isFieldDesignator()) {
1987 if (FieldDecl *Field = D->getField())
1988 AddMemberRef(Field, D->getFieldLoc());
1989 continue;
1990 }
1991 if (D->isArrayDesignator()) {
1992 AddStmt(E->getArrayIndex(*D));
1993 continue;
1994 }
1995 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1996 AddStmt(E->getArrayRangeEnd(*D));
1997 AddStmt(E->getArrayRangeStart(*D));
1998 }
1999}
Ted Kremenek28a71942010-11-13 00:36:47 +00002000void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
2001 EnqueueChildren(E);
2002 AddTypeLoc(E->getTypeInfoAsWritten());
2003}
2004void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2005 AddStmt(FS->getBody());
2006 AddStmt(FS->getInc());
2007 AddStmt(FS->getCond());
2008 AddDecl(FS->getConditionVariable());
2009 AddStmt(FS->getInit());
2010}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002011void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2012 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2013}
Ted Kremenek28a71942010-11-13 00:36:47 +00002014void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2015 AddStmt(If->getElse());
2016 AddStmt(If->getThen());
2017 AddStmt(If->getCond());
2018 AddDecl(If->getConditionVariable());
2019}
2020void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2021 // We care about the syntactic form of the initializer list, only.
2022 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2023 IE = Syntactic;
2024 EnqueueChildren(IE);
2025}
2026void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002027 WL.push_back(MemberExprParts(M, Parent));
2028
2029 // If the base of the member access expression is an implicit 'this', don't
2030 // visit it.
2031 // FIXME: If we ever want to show these implicit accesses, this will be
2032 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002033 if (!M->isImplicitAccess())
2034 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002035}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002036void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2037 AddTypeLoc(E->getEncodedTypeSourceInfo());
2038}
Ted Kremenek28a71942010-11-13 00:36:47 +00002039void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2040 EnqueueChildren(M);
2041 AddTypeLoc(M->getClassReceiverTypeInfo());
2042}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002043void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2044 // Visit the components of the offsetof expression.
2045 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2046 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2047 const OffsetOfNode &Node = E->getComponent(I-1);
2048 switch (Node.getKind()) {
2049 case OffsetOfNode::Array:
2050 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2051 break;
2052 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002053 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002054 break;
2055 case OffsetOfNode::Identifier:
2056 case OffsetOfNode::Base:
2057 continue;
2058 }
2059 }
2060 // Visit the type into which we're computing the offset.
2061 AddTypeLoc(E->getTypeSourceInfo());
2062}
Ted Kremenek28a71942010-11-13 00:36:47 +00002063void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002064 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002065 WL.push_back(OverloadExprParts(E, Parent));
2066}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002067void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2068 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002069 EnqueueChildren(E);
2070 if (E->isArgumentType())
2071 AddTypeLoc(E->getArgumentTypeInfo());
2072}
Ted Kremenek28a71942010-11-13 00:36:47 +00002073void EnqueueVisitor::VisitStmt(Stmt *S) {
2074 EnqueueChildren(S);
2075}
2076void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2077 AddStmt(S->getBody());
2078 AddStmt(S->getCond());
2079 AddDecl(S->getConditionVariable());
2080}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002081
Ted Kremenek28a71942010-11-13 00:36:47 +00002082void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2083 AddStmt(W->getBody());
2084 AddStmt(W->getCond());
2085 AddDecl(W->getConditionVariable());
2086}
John Wiegley21ff2e52011-04-28 00:16:57 +00002087
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002088void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2089 AddTypeLoc(E->getQueriedTypeSourceInfo());
2090}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002091
2092void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002093 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002094 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002095}
2096
John Wiegley21ff2e52011-04-28 00:16:57 +00002097void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2098 AddTypeLoc(E->getQueriedTypeSourceInfo());
2099}
2100
John Wiegley55262202011-04-25 06:54:41 +00002101void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2102 EnqueueChildren(E);
2103}
2104
Ted Kremenek28a71942010-11-13 00:36:47 +00002105void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2106 VisitOverloadExpr(U);
2107 if (!U->isImplicitAccess())
2108 AddStmt(U->getBase());
2109}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002110void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2111 AddStmt(E->getSubExpr());
2112 AddTypeLoc(E->getWrittenTypeInfo());
2113}
Douglas Gregor94d96292011-01-19 20:34:17 +00002114void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2115 WL.push_back(SizeOfPackExprParts(E, Parent));
2116}
Ted Kremenek60458782010-11-12 21:34:16 +00002117
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002118void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002119 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002120}
2121
2122bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2123 if (RegionOfInterest.isValid()) {
2124 SourceRange Range = getRawCursorExtent(C);
2125 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2126 return false;
2127 }
2128 return true;
2129}
2130
2131bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2132 while (!WL.empty()) {
2133 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002134 VisitorJob LI = WL.back();
2135 WL.pop_back();
2136
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002137 // Set the Parent field, then back to its old value once we're done.
2138 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2139
2140 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002141 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002142 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002143 if (!D)
2144 continue;
2145
2146 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002147 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002148 return true;
2149
2150 continue;
2151 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002152 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2153 const ExplicitTemplateArgumentList *ArgList =
2154 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2155 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2156 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2157 Arg != ArgEnd; ++Arg) {
2158 if (VisitTemplateArgumentLoc(*Arg))
2159 return true;
2160 }
2161 continue;
2162 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002163 case VisitorJob::TypeLocVisitKind: {
2164 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002165 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002166 return true;
2167 continue;
2168 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002169 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002170 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002171 if (LabelStmt *stmt = LS->getStmt()) {
2172 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2173 TU))) {
2174 return true;
2175 }
2176 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002177 continue;
2178 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002179
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002180 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2181 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2182 if (VisitNestedNameSpecifierLoc(V->get()))
2183 return true;
2184 continue;
2185 }
2186
Ted Kremenekf64d8032010-11-18 00:02:32 +00002187 case VisitorJob::DeclarationNameInfoVisitKind: {
2188 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2189 ->get()))
2190 return true;
2191 continue;
2192 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002193 case VisitorJob::MemberRefVisitKind: {
2194 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2195 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2196 return true;
2197 continue;
2198 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002199 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002200 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002201 if (!S)
2202 continue;
2203
Ted Kremenekf1107452010-11-12 18:26:56 +00002204 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002205 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002206 if (!IsInRegionOfInterest(Cursor))
2207 continue;
2208 switch (Visitor(Cursor, Parent, ClientData)) {
2209 case CXChildVisit_Break: return true;
2210 case CXChildVisit_Continue: break;
2211 case CXChildVisit_Recurse:
2212 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002213 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002214 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002215 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002216 }
2217 case VisitorJob::MemberExprPartsKind: {
2218 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002219 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002220
2221 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002222 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2223 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002224 return true;
2225
2226 // Visit the declaration name.
2227 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2228 return true;
2229
2230 // Visit the explicitly-specified template arguments, if any.
2231 if (M->hasExplicitTemplateArgs()) {
2232 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2233 *ArgEnd = Arg + M->getNumTemplateArgs();
2234 Arg != ArgEnd; ++Arg) {
2235 if (VisitTemplateArgumentLoc(*Arg))
2236 return true;
2237 }
2238 }
2239 continue;
2240 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002241 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002242 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002243 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002244 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2245 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002246 return true;
2247 // Visit declaration name.
2248 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2249 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002250 continue;
2251 }
Ted Kremenek60458782010-11-12 21:34:16 +00002252 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002253 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002254 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002255 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2256 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002257 return true;
2258 // Visit the declaration name.
2259 if (VisitDeclarationNameInfo(O->getNameInfo()))
2260 return true;
2261 // Visit the overloaded declaration reference.
2262 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2263 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002264 continue;
2265 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002266 case VisitorJob::SizeOfPackExprPartsKind: {
2267 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2268 NamedDecl *Pack = E->getPack();
2269 if (isa<TemplateTypeParmDecl>(Pack)) {
2270 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2271 E->getPackLoc(), TU)))
2272 return true;
2273
2274 continue;
2275 }
2276
2277 if (isa<TemplateTemplateParmDecl>(Pack)) {
2278 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2279 E->getPackLoc(), TU)))
2280 return true;
2281
2282 continue;
2283 }
2284
2285 // Non-type template parameter packs and function parameter packs are
2286 // treated like DeclRefExpr cursors.
2287 continue;
2288 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002289 }
2290 }
2291 return false;
2292}
2293
Ted Kremenekcdba6592010-11-18 00:42:18 +00002294bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002295 VisitorWorkList *WL = 0;
2296 if (!WorkListFreeList.empty()) {
2297 WL = WorkListFreeList.back();
2298 WL->clear();
2299 WorkListFreeList.pop_back();
2300 }
2301 else {
2302 WL = new VisitorWorkList();
2303 WorkListCache.push_back(WL);
2304 }
2305 EnqueueWorkList(*WL, S);
2306 bool result = RunVisitorWorkList(*WL);
2307 WorkListFreeList.push_back(WL);
2308 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002309}
2310
Francois Pichet48a8d142011-07-25 22:00:44 +00002311namespace {
2312typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2313RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2314 const DeclarationNameInfo &NI,
2315 const SourceRange &QLoc,
2316 const ExplicitTemplateArgumentList *TemplateArgs = 0){
2317 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2318 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2319 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2320
2321 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2322
2323 RefNamePieces Pieces;
2324
2325 if (WantQualifier && QLoc.isValid())
2326 Pieces.push_back(QLoc);
2327
2328 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2329 Pieces.push_back(NI.getLoc());
2330
2331 if (WantTemplateArgs && TemplateArgs)
2332 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2333 TemplateArgs->RAngleLoc));
2334
2335 if (Kind == DeclarationName::CXXOperatorName) {
2336 Pieces.push_back(SourceLocation::getFromRawEncoding(
2337 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2338 Pieces.push_back(SourceLocation::getFromRawEncoding(
2339 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2340 }
2341
2342 if (WantSinglePiece) {
2343 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2344 Pieces.clear();
2345 Pieces.push_back(R);
2346 }
2347
2348 return Pieces;
2349}
2350}
2351
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002352//===----------------------------------------------------------------------===//
2353// Misc. API hooks.
2354//===----------------------------------------------------------------------===//
2355
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002356static llvm::sys::Mutex EnableMultithreadingMutex;
2357static bool EnabledMultithreading;
2358
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002359extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002360CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2361 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002362 // Disable pretty stack trace functionality, which will otherwise be a very
2363 // poor citizen of the world and set up all sorts of signal handlers.
2364 llvm::DisablePrettyStackTrace = true;
2365
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002366 // We use crash recovery to make some of our APIs more reliable, implicitly
2367 // enable it.
2368 llvm::CrashRecoveryContext::Enable();
2369
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002370 // Enable support for multithreading in LLVM.
2371 {
2372 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2373 if (!EnabledMultithreading) {
2374 llvm::llvm_start_multithreaded();
2375 EnabledMultithreading = true;
2376 }
2377 }
2378
Douglas Gregora030b7c2010-01-22 20:35:53 +00002379 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002380 if (excludeDeclarationsFromPCH)
2381 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002382 if (displayDiagnostics)
2383 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002384 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002385}
2386
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002387void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002388 if (CIdx)
2389 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002390}
2391
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002392void clang_toggleCrashRecovery(unsigned isEnabled) {
2393 if (isEnabled)
2394 llvm::CrashRecoveryContext::Enable();
2395 else
2396 llvm::CrashRecoveryContext::Disable();
2397}
2398
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002399CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002400 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002401 if (!CIdx)
2402 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002403
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002404 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002405 FileSystemOptions FileSystemOpts;
2406 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002407
Douglas Gregor28019772010-04-05 23:52:57 +00002408 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002409 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002410 CXXIdx->getOnlyLocalDecls(),
2411 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002412 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002413}
2414
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002415unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002416 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002417 CXTranslationUnit_CacheCompletionResults |
John McCallf85e1932011-06-15 23:02:42 +00002418 CXTranslationUnit_CXXPrecompiledPreamble |
2419 CXTranslationUnit_CXXChainedPCH;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002420}
2421
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002422CXTranslationUnit
2423clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2424 const char *source_filename,
2425 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002426 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002427 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002428 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002429 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002430 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002431 return clang_parseTranslationUnit(CIdx, source_filename,
2432 command_line_args, num_command_line_args,
2433 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002434 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002435}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002436
2437struct ParseTranslationUnitInfo {
2438 CXIndex CIdx;
2439 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002440 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002441 int num_command_line_args;
2442 struct CXUnsavedFile *unsaved_files;
2443 unsigned num_unsaved_files;
2444 unsigned options;
2445 CXTranslationUnit result;
2446};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002447static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002448 ParseTranslationUnitInfo *PTUI =
2449 static_cast<ParseTranslationUnitInfo*>(UserData);
2450 CXIndex CIdx = PTUI->CIdx;
2451 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002452 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002453 int num_command_line_args = PTUI->num_command_line_args;
2454 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2455 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2456 unsigned options = PTUI->options;
2457 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002458
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002459 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002460 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002461
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002462 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2463
Douglas Gregor44c181a2010-07-23 00:33:23 +00002464 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002465 // FIXME: Add a flag for modules.
2466 TranslationUnitKind TUKind
2467 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002468 bool CacheCodeCompetionResults
2469 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002470 bool CXXPrecompilePreamble
2471 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2472 bool CXXChainedPCH
2473 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002474
Douglas Gregor5352ac02010-01-28 00:27:43 +00002475 // Configure the diagnostics.
2476 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002477 llvm::IntrusiveRefCntPtr<Diagnostic>
2478 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2479 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002480
Ted Kremenek25a11e12011-03-22 01:15:24 +00002481 // Recover resources if we crash before exiting this function.
2482 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2483 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2484 DiagCleanup(Diags.getPtr());
2485
2486 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2487 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2488
2489 // Recover resources if we crash before exiting this function.
2490 llvm::CrashRecoveryContextCleanupRegistrar<
2491 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2492
Douglas Gregor4db64a42010-01-23 00:14:00 +00002493 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002494 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002495 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002496 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002497 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2498 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002499 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002500
Ted Kremenek25a11e12011-03-22 01:15:24 +00002501 llvm::OwningPtr<std::vector<const char *> >
2502 Args(new std::vector<const char*>());
2503
2504 // Recover resources if we crash before exiting this method.
2505 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2506 ArgsCleanup(Args.get());
2507
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002508 // Since the Clang C library is primarily used by batch tools dealing with
2509 // (often very broken) source code, where spell-checking can have a
2510 // significant negative impact on performance (particularly when
2511 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002512 // Only do this if we haven't found a spell-checking-related argument.
2513 bool FoundSpellCheckingArgument = false;
2514 for (int I = 0; I != num_command_line_args; ++I) {
2515 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2516 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2517 FoundSpellCheckingArgument = true;
2518 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002519 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002520 }
2521 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002522 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002523
Ted Kremenek25a11e12011-03-22 01:15:24 +00002524 Args->insert(Args->end(), command_line_args,
2525 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002526
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002527 // The 'source_filename' argument is optional. If the caller does not
2528 // specify it then it is assumed that the source file is specified
2529 // in the actual argument list.
2530 // Put the source file after command_line_args otherwise if '-x' flag is
2531 // present it will be unused.
2532 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002533 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002534
Douglas Gregor44c181a2010-07-23 00:33:23 +00002535 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002536 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002537 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002538 Args->push_back("-Xclang");
2539 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002540 NestedMacroExpansions
2541 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002542 }
2543
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002544 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002545 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002546 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2547 /* vector::data() not portable */,
2548 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002549 Diags,
2550 CXXIdx->getClangResourcesPath(),
2551 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002552 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002553 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002554 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002555 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002556 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002557 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002558 CacheCodeCompetionResults,
2559 CXXPrecompilePreamble,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002560 CXXChainedPCH,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002561 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002562
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002563 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002564 // Make sure to check that 'Unit' is non-NULL.
2565 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2566 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2567 DEnd = Unit->stored_diag_end();
2568 D != DEnd; ++D) {
2569 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2570 CXString Msg = clang_formatDiagnostic(&Diag,
2571 clang_defaultDiagnosticDisplayOptions());
2572 fprintf(stderr, "%s\n", clang_getCString(Msg));
2573 clang_disposeString(Msg);
2574 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002575#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002576 // On Windows, force a flush, since there may be multiple copies of
2577 // stderr and stdout in the file system, all with different buffers
2578 // but writing to the same device.
2579 fflush(stderr);
2580#endif
2581 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002582 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002583
Ted Kremeneka60ed472010-11-16 08:15:36 +00002584 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002585}
2586CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2587 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002588 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002589 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002590 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002591 unsigned num_unsaved_files,
2592 unsigned options) {
2593 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002594 num_command_line_args, unsaved_files,
2595 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002596 llvm::CrashRecoveryContext CRC;
2597
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002598 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002599 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2600 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2601 fprintf(stderr, " 'command_line_args' : [");
2602 for (int i = 0; i != num_command_line_args; ++i) {
2603 if (i)
2604 fprintf(stderr, ", ");
2605 fprintf(stderr, "'%s'", command_line_args[i]);
2606 }
2607 fprintf(stderr, "],\n");
2608 fprintf(stderr, " 'unsaved_files' : [");
2609 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2610 if (i)
2611 fprintf(stderr, ", ");
2612 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2613 unsaved_files[i].Length);
2614 }
2615 fprintf(stderr, "],\n");
2616 fprintf(stderr, " 'options' : %d,\n", options);
2617 fprintf(stderr, "}\n");
2618
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002619 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002620 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2621 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002622 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002623
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002624 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002625}
2626
Douglas Gregor19998442010-08-13 15:35:05 +00002627unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2628 return CXSaveTranslationUnit_None;
2629}
2630
2631int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2632 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002633 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002634 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002635
Douglas Gregor39c411f2011-07-06 16:43:36 +00002636 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002637 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2638 PrintLibclangResourceUsage(TU);
2639 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002640}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002641
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002642void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002643 if (CTUnit) {
2644 // If the translation unit has been marked as unsafe to free, just discard
2645 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002646 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002647 return;
2648
Ted Kremeneka60ed472010-11-16 08:15:36 +00002649 delete static_cast<ASTUnit *>(CTUnit->TUData);
2650 disposeCXStringPool(CTUnit->StringPool);
2651 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002652 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002653}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002654
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002655unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2656 return CXReparse_None;
2657}
2658
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002659struct ReparseTranslationUnitInfo {
2660 CXTranslationUnit TU;
2661 unsigned num_unsaved_files;
2662 struct CXUnsavedFile *unsaved_files;
2663 unsigned options;
2664 int result;
2665};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002666
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002667static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002668 ReparseTranslationUnitInfo *RTUI =
2669 static_cast<ReparseTranslationUnitInfo*>(UserData);
2670 CXTranslationUnit TU = RTUI->TU;
2671 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2672 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2673 unsigned options = RTUI->options;
2674 (void) options;
2675 RTUI->result = 1;
2676
Douglas Gregorabc563f2010-07-19 21:46:24 +00002677 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002678 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002679
Ted Kremeneka60ed472010-11-16 08:15:36 +00002680 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002681 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002682
Ted Kremenek25a11e12011-03-22 01:15:24 +00002683 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2684 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2685
2686 // Recover resources if we crash before exiting this function.
2687 llvm::CrashRecoveryContextCleanupRegistrar<
2688 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2689
Douglas Gregorabc563f2010-07-19 21:46:24 +00002690 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002691 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002692 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002693 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002694 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2695 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002696 }
2697
Ted Kremenek4ee99262011-03-22 20:16:19 +00002698 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2699 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002700 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002701}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002702
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002703int clang_reparseTranslationUnit(CXTranslationUnit TU,
2704 unsigned num_unsaved_files,
2705 struct CXUnsavedFile *unsaved_files,
2706 unsigned options) {
2707 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2708 options, 0 };
2709 llvm::CrashRecoveryContext CRC;
2710
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002711 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002712 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002713 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002714 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002715 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2716 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002717
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002718 return RTUI.result;
2719}
2720
Douglas Gregordf95a132010-08-09 20:45:32 +00002721
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002722CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002723 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002724 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002725
Ted Kremeneka60ed472010-11-16 08:15:36 +00002726 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002727 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002728}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002729
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002730CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002731 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002732 return Result;
2733}
2734
Ted Kremenekfb480492010-01-13 21:46:36 +00002735} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002736
Ted Kremenekfb480492010-01-13 21:46:36 +00002737//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002738// CXSourceLocation and CXSourceRange Operations.
2739//===----------------------------------------------------------------------===//
2740
Douglas Gregorb9790342010-01-22 21:44:22 +00002741extern "C" {
2742CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002743 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002744 return Result;
2745}
2746
2747unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002748 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2749 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2750 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002751}
2752
2753CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2754 CXFile file,
2755 unsigned line,
2756 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002757 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002758 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002759
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002760 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002761 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002762 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002763 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002764 = CXXUnit->getSourceManager().getLocation(File, line, column);
2765 if (SLoc.isInvalid()) {
2766 if (Logging)
2767 llvm::errs() << "clang_getLocation(\"" << File->getName()
2768 << "\", " << line << ", " << column << ") = invalid\n";
2769 return clang_getNullLocation();
2770 }
2771
2772 if (Logging)
2773 llvm::errs() << "clang_getLocation(\"" << File->getName()
2774 << "\", " << line << ", " << column << ") = "
2775 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002776
2777 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2778}
2779
2780CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2781 CXFile file,
2782 unsigned offset) {
2783 if (!tu || !file)
2784 return clang_getNullLocation();
2785
Ted Kremeneka60ed472010-11-16 08:15:36 +00002786 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002787 SourceLocation Start
2788 = CXXUnit->getSourceManager().getLocation(
2789 static_cast<const FileEntry *>(file),
2790 1, 1);
2791 if (Start.isInvalid()) return clang_getNullLocation();
2792
2793 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2794
2795 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002796
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002797 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002798}
2799
Douglas Gregor5352ac02010-01-28 00:27:43 +00002800CXSourceRange clang_getNullRange() {
2801 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2802 return Result;
2803}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002804
Douglas Gregor5352ac02010-01-28 00:27:43 +00002805CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2806 if (begin.ptr_data[0] != end.ptr_data[0] ||
2807 begin.ptr_data[1] != end.ptr_data[1])
2808 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002809
2810 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002811 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002812 return Result;
2813}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002814
2815unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2816{
2817 return range1.ptr_data[0] == range2.ptr_data[0]
2818 && range1.ptr_data[1] == range2.ptr_data[1]
2819 && range1.begin_int_data == range2.begin_int_data
2820 && range1.end_int_data == range2.end_int_data;
2821}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002822} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002823
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002824static void createNullLocation(CXFile *file, unsigned *line,
2825 unsigned *column, unsigned *offset) {
2826 if (file)
2827 *file = 0;
2828 if (line)
2829 *line = 0;
2830 if (column)
2831 *column = 0;
2832 if (offset)
2833 *offset = 0;
2834 return;
2835}
2836
2837extern "C" {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002838void clang_getInstantiationLocation(CXSourceLocation location,
2839 CXFile *file,
2840 unsigned *line,
2841 unsigned *column,
2842 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002843 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2844
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002845 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002846 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002847 return;
2848 }
2849
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002850 const SourceManager &SM =
2851 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth40278532011-07-25 16:49:02 +00002852 SourceLocation InstLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002853
Chandler Carruthcea731a2011-07-14 16:07:57 +00002854 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002855 // This can manifest in invalid code.
2856 FileID fileID = SM.getFileID(InstLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002857 bool Invalid = false;
2858 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2859 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002860 createNullLocation(file, line, column, offset);
2861 return;
2862 }
2863
Douglas Gregor1db19de2010-01-19 21:36:55 +00002864 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002865 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002866 if (line)
Chandler Carruth64211622011-07-25 21:09:52 +00002867 *line = SM.getExpansionLineNumber(InstLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002868 if (column)
Chandler Carrutha77c0312011-07-25 20:57:57 +00002869 *column = SM.getExpansionColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002870 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002871 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002872}
2873
Douglas Gregora9b06d42010-11-09 06:24:54 +00002874void clang_getSpellingLocation(CXSourceLocation location,
2875 CXFile *file,
2876 unsigned *line,
2877 unsigned *column,
2878 unsigned *offset) {
2879 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2880
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002881 if (!location.ptr_data[0] || Loc.isInvalid())
2882 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002883
2884 const SourceManager &SM =
2885 *static_cast<const SourceManager*>(location.ptr_data[0]);
2886 SourceLocation SpellLoc = Loc;
2887 if (SpellLoc.isMacroID()) {
2888 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2889 if (SimpleSpellingLoc.isFileID() &&
2890 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2891 SpellLoc = SimpleSpellingLoc;
2892 else
Chandler Carruth40278532011-07-25 16:49:02 +00002893 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002894 }
2895
2896 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2897 FileID FID = LocInfo.first;
2898 unsigned FileOffset = LocInfo.second;
2899
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002900 if (FID.isInvalid())
2901 return createNullLocation(file, line, column, offset);
2902
Douglas Gregora9b06d42010-11-09 06:24:54 +00002903 if (file)
2904 *file = (void *)SM.getFileEntryForID(FID);
2905 if (line)
2906 *line = SM.getLineNumber(FID, FileOffset);
2907 if (column)
2908 *column = SM.getColumnNumber(FID, FileOffset);
2909 if (offset)
2910 *offset = FileOffset;
2911}
2912
Douglas Gregor1db19de2010-01-19 21:36:55 +00002913CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002914 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002915 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002916 return Result;
2917}
2918
2919CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002920 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002921 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002922 return Result;
2923}
2924
Douglas Gregorb9790342010-01-22 21:44:22 +00002925} // end: extern "C"
2926
Douglas Gregor1db19de2010-01-19 21:36:55 +00002927//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002928// CXFile Operations.
2929//===----------------------------------------------------------------------===//
2930
2931extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002932CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002933 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002934 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002935
Steve Naroff88145032009-10-27 14:35:18 +00002936 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002937 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002938}
2939
2940time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002941 if (!SFile)
2942 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002943
Steve Naroff88145032009-10-27 14:35:18 +00002944 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2945 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002946}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002947
Douglas Gregorb9790342010-01-22 21:44:22 +00002948CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2949 if (!tu)
2950 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002951
Ted Kremeneka60ed472010-11-16 08:15:36 +00002952 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002953
Douglas Gregorb9790342010-01-22 21:44:22 +00002954 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002955 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002956}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002957
Douglas Gregordd3e5542011-05-04 00:14:37 +00002958unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2959 if (!tu || !file)
2960 return 0;
2961
2962 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2963 FileEntry *FEnt = static_cast<FileEntry *>(file);
2964 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2965 .isFileMultipleIncludeGuarded(FEnt);
2966}
2967
Ted Kremenekfb480492010-01-13 21:46:36 +00002968} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002969
Ted Kremenekfb480492010-01-13 21:46:36 +00002970//===----------------------------------------------------------------------===//
2971// CXCursor Operations.
2972//===----------------------------------------------------------------------===//
2973
Ted Kremenekfb480492010-01-13 21:46:36 +00002974static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002975 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2976 return getDeclFromExpr(CE->getSubExpr());
2977
Ted Kremenekfb480492010-01-13 21:46:36 +00002978 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2979 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002980 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2981 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002982 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2983 return ME->getMemberDecl();
2984 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2985 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002986 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002987 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002988
Ted Kremenekfb480492010-01-13 21:46:36 +00002989 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2990 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002991 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002992 if (!CE->isElidable())
2993 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002994 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2995 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002996
Douglas Gregordb1314e2010-10-01 21:11:22 +00002997 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2998 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002999 if (SubstNonTypeTemplateParmPackExpr *NTTP
3000 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3001 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00003002 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3003 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
3004 isa<ParmVarDecl>(SizeOfPack->getPack()))
3005 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00003006
Ted Kremenekfb480492010-01-13 21:46:36 +00003007 return 0;
3008}
3009
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003010static SourceLocation getLocationFromExpr(Expr *E) {
3011 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3012 return /*FIXME:*/Msg->getLeftLoc();
3013 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3014 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003015 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3016 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003017 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3018 return Member->getMemberLoc();
3019 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3020 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003021 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3022 return SizeOfPack->getPackLoc();
3023
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003024 return E->getLocStart();
3025}
3026
Ted Kremenekfb480492010-01-13 21:46:36 +00003027extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003028
3029unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003030 CXCursorVisitor visitor,
3031 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003032 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003033 getCursorASTUnit(parent)->getMaxPCHLevel(),
3034 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003035 return CursorVis.VisitChildren(parent);
3036}
3037
David Chisnall3387c652010-11-03 14:12:26 +00003038#ifndef __has_feature
3039#define __has_feature(x) 0
3040#endif
3041#if __has_feature(blocks)
3042typedef enum CXChildVisitResult
3043 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3044
3045static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3046 CXClientData client_data) {
3047 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3048 return block(cursor, parent);
3049}
3050#else
3051// If we are compiled with a compiler that doesn't have native blocks support,
3052// define and call the block manually, so the
3053typedef struct _CXChildVisitResult
3054{
3055 void *isa;
3056 int flags;
3057 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003058 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3059 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003060} *CXCursorVisitorBlock;
3061
3062static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3063 CXClientData client_data) {
3064 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3065 return block->invoke(block, cursor, parent);
3066}
3067#endif
3068
3069
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003070unsigned clang_visitChildrenWithBlock(CXCursor parent,
3071 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003072 return clang_visitChildren(parent, visitWithBlock, block);
3073}
3074
Douglas Gregor78205d42010-01-20 21:45:58 +00003075static CXString getDeclSpelling(Decl *D) {
3076 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003077 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003078 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003079 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3080 return createCXString(Property->getIdentifier()->getName());
3081
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003082 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003083 }
3084
Douglas Gregor78205d42010-01-20 21:45:58 +00003085 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003086 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003087
Douglas Gregor78205d42010-01-20 21:45:58 +00003088 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3089 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3090 // and returns different names. NamedDecl returns the class name and
3091 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003092 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003093
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003094 if (isa<UsingDirectiveDecl>(D))
3095 return createCXString("");
3096
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003097 llvm::SmallString<1024> S;
3098 llvm::raw_svector_ostream os(S);
3099 ND->printName(os);
3100
3101 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003102}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003103
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003104CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003105 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003106 return clang_getTranslationUnitSpelling(
3107 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003108
Steve Narofff334b4e2009-09-02 18:26:48 +00003109 if (clang_isReference(C.kind)) {
3110 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003111 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003112 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003113 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003114 }
3115 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003116 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003117 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003118 }
3119 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003120 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003121 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003122 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003123 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003124 case CXCursor_CXXBaseSpecifier: {
3125 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3126 return createCXString(B->getType().getAsString());
3127 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003128 case CXCursor_TypeRef: {
3129 TypeDecl *Type = getCursorTypeRef(C).first;
3130 assert(Type && "Missing type decl");
3131
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003132 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3133 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003134 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003135 case CXCursor_TemplateRef: {
3136 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003137 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003138
3139 return createCXString(Template->getNameAsString());
3140 }
Douglas Gregor69319002010-08-31 23:48:11 +00003141
3142 case CXCursor_NamespaceRef: {
3143 NamedDecl *NS = getCursorNamespaceRef(C).first;
3144 assert(NS && "Missing namespace decl");
3145
3146 return createCXString(NS->getNameAsString());
3147 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003148
Douglas Gregora67e03f2010-09-09 21:42:20 +00003149 case CXCursor_MemberRef: {
3150 FieldDecl *Field = getCursorMemberRef(C).first;
3151 assert(Field && "Missing member decl");
3152
3153 return createCXString(Field->getNameAsString());
3154 }
3155
Douglas Gregor36897b02010-09-10 00:22:18 +00003156 case CXCursor_LabelRef: {
3157 LabelStmt *Label = getCursorLabelRef(C).first;
3158 assert(Label && "Missing label");
3159
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003160 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003161 }
3162
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003163 case CXCursor_OverloadedDeclRef: {
3164 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3165 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3166 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3167 return createCXString(ND->getNameAsString());
3168 return createCXString("");
3169 }
3170 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3171 return createCXString(E->getName().getAsString());
3172 OverloadedTemplateStorage *Ovl
3173 = Storage.get<OverloadedTemplateStorage*>();
3174 if (Ovl->size() == 0)
3175 return createCXString("");
3176 return createCXString((*Ovl->begin())->getNameAsString());
3177 }
3178
Daniel Dunbaracca7252009-11-30 20:42:49 +00003179 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003180 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003181 }
3182 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003183
3184 if (clang_isExpression(C.kind)) {
3185 Decl *D = getDeclFromExpr(getCursorExpr(C));
3186 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003187 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003188 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003189 }
3190
Douglas Gregor36897b02010-09-10 00:22:18 +00003191 if (clang_isStatement(C.kind)) {
3192 Stmt *S = getCursorStmt(C);
3193 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003194 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003195
3196 return createCXString("");
3197 }
3198
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003199 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003200 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003201 ->getNameStart());
3202
Douglas Gregor572feb22010-03-18 18:04:21 +00003203 if (C.kind == CXCursor_MacroDefinition)
3204 return createCXString(getCursorMacroDefinition(C)->getName()
3205 ->getNameStart());
3206
Douglas Gregorecdcb882010-10-20 22:00:55 +00003207 if (C.kind == CXCursor_InclusionDirective)
3208 return createCXString(getCursorInclusionDirective(C)->getFileName());
3209
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003210 if (clang_isDeclaration(C.kind))
3211 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003212
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003213 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003214}
3215
Douglas Gregor358559d2010-10-02 22:49:11 +00003216CXString clang_getCursorDisplayName(CXCursor C) {
3217 if (!clang_isDeclaration(C.kind))
3218 return clang_getCursorSpelling(C);
3219
3220 Decl *D = getCursorDecl(C);
3221 if (!D)
3222 return createCXString("");
3223
3224 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3225 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3226 D = FunTmpl->getTemplatedDecl();
3227
3228 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3229 llvm::SmallString<64> Str;
3230 llvm::raw_svector_ostream OS(Str);
3231 OS << Function->getNameAsString();
3232 if (Function->getPrimaryTemplate())
3233 OS << "<>";
3234 OS << "(";
3235 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3236 if (I)
3237 OS << ", ";
3238 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3239 }
3240
3241 if (Function->isVariadic()) {
3242 if (Function->getNumParams())
3243 OS << ", ";
3244 OS << "...";
3245 }
3246 OS << ")";
3247 return createCXString(OS.str());
3248 }
3249
3250 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3251 llvm::SmallString<64> Str;
3252 llvm::raw_svector_ostream OS(Str);
3253 OS << ClassTemplate->getNameAsString();
3254 OS << "<";
3255 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3256 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3257 if (I)
3258 OS << ", ";
3259
3260 NamedDecl *Param = Params->getParam(I);
3261 if (Param->getIdentifier()) {
3262 OS << Param->getIdentifier()->getName();
3263 continue;
3264 }
3265
3266 // There is no parameter name, which makes this tricky. Try to come up
3267 // with something useful that isn't too long.
3268 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3269 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3270 else if (NonTypeTemplateParmDecl *NTTP
3271 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3272 OS << NTTP->getType().getAsString(Policy);
3273 else
3274 OS << "template<...> class";
3275 }
3276
3277 OS << ">";
3278 return createCXString(OS.str());
3279 }
3280
3281 if (ClassTemplateSpecializationDecl *ClassSpec
3282 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3283 // If the type was explicitly written, use that.
3284 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3285 return createCXString(TSInfo->getType().getAsString(Policy));
3286
3287 llvm::SmallString<64> Str;
3288 llvm::raw_svector_ostream OS(Str);
3289 OS << ClassSpec->getNameAsString();
3290 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003291 ClassSpec->getTemplateArgs().data(),
3292 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003293 Policy);
3294 return createCXString(OS.str());
3295 }
3296
3297 return clang_getCursorSpelling(C);
3298}
3299
Ted Kremeneke68fff62010-02-17 00:41:32 +00003300CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003301 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003302 case CXCursor_FunctionDecl:
3303 return createCXString("FunctionDecl");
3304 case CXCursor_TypedefDecl:
3305 return createCXString("TypedefDecl");
3306 case CXCursor_EnumDecl:
3307 return createCXString("EnumDecl");
3308 case CXCursor_EnumConstantDecl:
3309 return createCXString("EnumConstantDecl");
3310 case CXCursor_StructDecl:
3311 return createCXString("StructDecl");
3312 case CXCursor_UnionDecl:
3313 return createCXString("UnionDecl");
3314 case CXCursor_ClassDecl:
3315 return createCXString("ClassDecl");
3316 case CXCursor_FieldDecl:
3317 return createCXString("FieldDecl");
3318 case CXCursor_VarDecl:
3319 return createCXString("VarDecl");
3320 case CXCursor_ParmDecl:
3321 return createCXString("ParmDecl");
3322 case CXCursor_ObjCInterfaceDecl:
3323 return createCXString("ObjCInterfaceDecl");
3324 case CXCursor_ObjCCategoryDecl:
3325 return createCXString("ObjCCategoryDecl");
3326 case CXCursor_ObjCProtocolDecl:
3327 return createCXString("ObjCProtocolDecl");
3328 case CXCursor_ObjCPropertyDecl:
3329 return createCXString("ObjCPropertyDecl");
3330 case CXCursor_ObjCIvarDecl:
3331 return createCXString("ObjCIvarDecl");
3332 case CXCursor_ObjCInstanceMethodDecl:
3333 return createCXString("ObjCInstanceMethodDecl");
3334 case CXCursor_ObjCClassMethodDecl:
3335 return createCXString("ObjCClassMethodDecl");
3336 case CXCursor_ObjCImplementationDecl:
3337 return createCXString("ObjCImplementationDecl");
3338 case CXCursor_ObjCCategoryImplDecl:
3339 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003340 case CXCursor_CXXMethod:
3341 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003342 case CXCursor_UnexposedDecl:
3343 return createCXString("UnexposedDecl");
3344 case CXCursor_ObjCSuperClassRef:
3345 return createCXString("ObjCSuperClassRef");
3346 case CXCursor_ObjCProtocolRef:
3347 return createCXString("ObjCProtocolRef");
3348 case CXCursor_ObjCClassRef:
3349 return createCXString("ObjCClassRef");
3350 case CXCursor_TypeRef:
3351 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003352 case CXCursor_TemplateRef:
3353 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003354 case CXCursor_NamespaceRef:
3355 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003356 case CXCursor_MemberRef:
3357 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003358 case CXCursor_LabelRef:
3359 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003360 case CXCursor_OverloadedDeclRef:
3361 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003362 case CXCursor_UnexposedExpr:
3363 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003364 case CXCursor_BlockExpr:
3365 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003366 case CXCursor_DeclRefExpr:
3367 return createCXString("DeclRefExpr");
3368 case CXCursor_MemberRefExpr:
3369 return createCXString("MemberRefExpr");
3370 case CXCursor_CallExpr:
3371 return createCXString("CallExpr");
3372 case CXCursor_ObjCMessageExpr:
3373 return createCXString("ObjCMessageExpr");
3374 case CXCursor_UnexposedStmt:
3375 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003376 case CXCursor_LabelStmt:
3377 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003378 case CXCursor_InvalidFile:
3379 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003380 case CXCursor_InvalidCode:
3381 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003382 case CXCursor_NoDeclFound:
3383 return createCXString("NoDeclFound");
3384 case CXCursor_NotImplemented:
3385 return createCXString("NotImplemented");
3386 case CXCursor_TranslationUnit:
3387 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003388 case CXCursor_UnexposedAttr:
3389 return createCXString("UnexposedAttr");
3390 case CXCursor_IBActionAttr:
3391 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003392 case CXCursor_IBOutletAttr:
3393 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003394 case CXCursor_IBOutletCollectionAttr:
3395 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003396 case CXCursor_PreprocessingDirective:
3397 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003398 case CXCursor_MacroDefinition:
3399 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003400 case CXCursor_MacroExpansion:
3401 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003402 case CXCursor_InclusionDirective:
3403 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003404 case CXCursor_Namespace:
3405 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003406 case CXCursor_LinkageSpec:
3407 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003408 case CXCursor_CXXBaseSpecifier:
3409 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003410 case CXCursor_Constructor:
3411 return createCXString("CXXConstructor");
3412 case CXCursor_Destructor:
3413 return createCXString("CXXDestructor");
3414 case CXCursor_ConversionFunction:
3415 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003416 case CXCursor_TemplateTypeParameter:
3417 return createCXString("TemplateTypeParameter");
3418 case CXCursor_NonTypeTemplateParameter:
3419 return createCXString("NonTypeTemplateParameter");
3420 case CXCursor_TemplateTemplateParameter:
3421 return createCXString("TemplateTemplateParameter");
3422 case CXCursor_FunctionTemplate:
3423 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003424 case CXCursor_ClassTemplate:
3425 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003426 case CXCursor_ClassTemplatePartialSpecialization:
3427 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003428 case CXCursor_NamespaceAlias:
3429 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003430 case CXCursor_UsingDirective:
3431 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003432 case CXCursor_UsingDeclaration:
3433 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003434 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003435 return createCXString("TypeAliasDecl");
3436 case CXCursor_ObjCSynthesizeDecl:
3437 return createCXString("ObjCSynthesizeDecl");
3438 case CXCursor_ObjCDynamicDecl:
3439 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003440 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003441
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003442 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003443 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003444}
Steve Naroff89922f82009-08-31 00:59:03 +00003445
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003446struct GetCursorData {
3447 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003448 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003449 CXCursor &BestCursor;
3450
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003451 GetCursorData(SourceManager &SM,
3452 SourceLocation tokenBegin, CXCursor &outputCursor)
3453 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3454 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3455 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003456};
3457
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003458static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3459 CXCursor parent,
3460 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003461 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3462 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003463
3464 // If we point inside a macro argument we should provide info of what the
3465 // token is so use the actual cursor, don't replace it with a macro expansion
3466 // cursor.
3467 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3468 return CXChildVisit_Recurse;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003469
3470 if (clang_isExpression(cursor.kind) &&
3471 clang_isDeclaration(BestCursor->kind)) {
3472 Decl *D = getCursorDecl(*BestCursor);
3473
3474 // Avoid having the cursor of an expression replace the declaration cursor
3475 // when the expression source range overlaps the declaration range.
3476 // This can happen for C++ constructor expressions whose range generally
3477 // include the variable declaration, e.g.:
3478 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3479 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3480 D->getLocation() == Data->TokenBeginLoc)
3481 return CXChildVisit_Break;
3482 }
3483
Douglas Gregor93798e22010-11-05 21:11:19 +00003484 // If our current best cursor is the construction of a temporary object,
3485 // don't replace that cursor with a type reference, because we want
3486 // clang_getCursor() to point at the constructor.
3487 if (clang_isExpression(BestCursor->kind) &&
3488 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3489 cursor.kind == CXCursor_TypeRef)
3490 return CXChildVisit_Recurse;
3491
Douglas Gregor85fe1562010-12-10 07:23:11 +00003492 // Don't override a preprocessing cursor with another preprocessing
3493 // cursor; we want the outermost preprocessing cursor.
3494 if (clang_isPreprocessing(cursor.kind) &&
3495 clang_isPreprocessing(BestCursor->kind))
3496 return CXChildVisit_Recurse;
3497
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003498 *BestCursor = cursor;
3499 return CXChildVisit_Recurse;
3500}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003501
Douglas Gregorb9790342010-01-22 21:44:22 +00003502CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3503 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003504 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003505
Ted Kremeneka60ed472010-11-16 08:15:36 +00003506 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003507 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3508
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003509 // Translate the given source location to make it point at the beginning of
3510 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003511 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003512
3513 // Guard against an invalid SourceLocation, or we may assert in one
3514 // of the following calls.
3515 if (SLoc.isInvalid())
3516 return clang_getNullCursor();
3517
Douglas Gregor40749ee2010-11-03 00:35:38 +00003518 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003519 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3520 CXXUnit->getASTContext().getLangOptions());
3521
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003522 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3523 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003524 // FIXME: Would be great to have a "hint" cursor, then walk from that
3525 // hint cursor upward until we find a cursor whose source range encloses
3526 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003527 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003528 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003529 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003530 Decl::MaxPCHLevel, true, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003531 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003532 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003533
3534 if (Logging) {
3535 CXFile SearchFile;
3536 unsigned SearchLine, SearchColumn;
3537 CXFile ResultFile;
3538 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003539 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3540 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003541 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3542
3543 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3544 0);
3545 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3546 &ResultColumn, 0);
3547 SearchFileName = clang_getFileName(SearchFile);
3548 ResultFileName = clang_getFileName(ResultFile);
3549 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003550 USR = clang_getCursorUSR(Result);
3551 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003552 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3553 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003554 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3555 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003556 clang_disposeString(SearchFileName);
3557 clang_disposeString(ResultFileName);
3558 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003559 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003560
3561 CXCursor Definition = clang_getCursorDefinition(Result);
3562 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3563 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3564 CXString DefinitionKindSpelling
3565 = clang_getCursorKindSpelling(Definition.kind);
3566 CXFile DefinitionFile;
3567 unsigned DefinitionLine, DefinitionColumn;
3568 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3569 &DefinitionLine, &DefinitionColumn, 0);
3570 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3571 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3572 clang_getCString(DefinitionKindSpelling),
3573 clang_getCString(DefinitionFileName),
3574 DefinitionLine, DefinitionColumn);
3575 clang_disposeString(DefinitionFileName);
3576 clang_disposeString(DefinitionKindSpelling);
3577 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003578 }
3579
Ted Kremeneke68fff62010-02-17 00:41:32 +00003580 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003581}
3582
Ted Kremenek73885552009-11-17 19:28:59 +00003583CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003584 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003585}
3586
3587unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003588 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003589}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003590
Douglas Gregor9ce55842010-11-20 00:09:34 +00003591unsigned clang_hashCursor(CXCursor C) {
3592 unsigned Index = 0;
3593 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3594 Index = 1;
3595
3596 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3597 std::make_pair(C.kind, C.data[Index]));
3598}
3599
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003600unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003601 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3602}
3603
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003604unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003605 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3606}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003607
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003608unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003609 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3610}
3611
Douglas Gregor97b98722010-01-19 23:20:36 +00003612unsigned clang_isExpression(enum CXCursorKind K) {
3613 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3614}
3615
3616unsigned clang_isStatement(enum CXCursorKind K) {
3617 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3618}
3619
Douglas Gregor8be80e12011-07-06 03:00:34 +00003620unsigned clang_isAttribute(enum CXCursorKind K) {
3621 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3622}
3623
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003624unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3625 return K == CXCursor_TranslationUnit;
3626}
3627
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003628unsigned clang_isPreprocessing(enum CXCursorKind K) {
3629 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3630}
3631
Ted Kremenekad6eff62010-03-08 21:17:29 +00003632unsigned clang_isUnexposed(enum CXCursorKind K) {
3633 switch (K) {
3634 case CXCursor_UnexposedDecl:
3635 case CXCursor_UnexposedExpr:
3636 case CXCursor_UnexposedStmt:
3637 case CXCursor_UnexposedAttr:
3638 return true;
3639 default:
3640 return false;
3641 }
3642}
3643
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003644CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003645 return C.kind;
3646}
3647
Douglas Gregor98258af2010-01-18 22:46:11 +00003648CXSourceLocation clang_getCursorLocation(CXCursor C) {
3649 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003650 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003651 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003652 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3653 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003654 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003655 }
3656
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003657 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003658 std::pair<ObjCProtocolDecl *, SourceLocation> P
3659 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003660 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003661 }
3662
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003663 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003664 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3665 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003666 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003667 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003668
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003669 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003670 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003671 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003672 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003673
3674 case CXCursor_TemplateRef: {
3675 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3676 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3677 }
3678
Douglas Gregor69319002010-08-31 23:48:11 +00003679 case CXCursor_NamespaceRef: {
3680 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3681 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3682 }
3683
Douglas Gregora67e03f2010-09-09 21:42:20 +00003684 case CXCursor_MemberRef: {
3685 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3686 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3687 }
3688
Ted Kremenek3064ef92010-08-27 21:34:58 +00003689 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003690 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3691 if (!BaseSpec)
3692 return clang_getNullLocation();
3693
3694 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3695 return cxloc::translateSourceLocation(getCursorContext(C),
3696 TSInfo->getTypeLoc().getBeginLoc());
3697
3698 return cxloc::translateSourceLocation(getCursorContext(C),
3699 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003700 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003701
Douglas Gregor36897b02010-09-10 00:22:18 +00003702 case CXCursor_LabelRef: {
3703 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3704 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3705 }
3706
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003707 case CXCursor_OverloadedDeclRef:
3708 return cxloc::translateSourceLocation(getCursorContext(C),
3709 getCursorOverloadedDeclRef(C).second);
3710
Douglas Gregorf46034a2010-01-18 23:41:10 +00003711 default:
3712 // FIXME: Need a way to enumerate all non-reference cases.
3713 llvm_unreachable("Missed a reference kind");
3714 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003715 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003716
3717 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003718 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003719 getLocationFromExpr(getCursorExpr(C)));
3720
Douglas Gregor36897b02010-09-10 00:22:18 +00003721 if (clang_isStatement(C.kind))
3722 return cxloc::translateSourceLocation(getCursorContext(C),
3723 getCursorStmt(C)->getLocStart());
3724
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003725 if (C.kind == CXCursor_PreprocessingDirective) {
3726 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3727 return cxloc::translateSourceLocation(getCursorContext(C), L);
3728 }
Douglas Gregor48072312010-03-18 15:23:44 +00003729
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003730 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003731 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003732 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003733 return cxloc::translateSourceLocation(getCursorContext(C), L);
3734 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003735
3736 if (C.kind == CXCursor_MacroDefinition) {
3737 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3738 return cxloc::translateSourceLocation(getCursorContext(C), L);
3739 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003740
3741 if (C.kind == CXCursor_InclusionDirective) {
3742 SourceLocation L
3743 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3744 return cxloc::translateSourceLocation(getCursorContext(C), L);
3745 }
3746
Ted Kremenek9a700d22010-05-12 06:16:13 +00003747 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003748 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003749
Douglas Gregorf46034a2010-01-18 23:41:10 +00003750 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003751 SourceLocation Loc = D->getLocation();
3752 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3753 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003754 // FIXME: Multiple variables declared in a single declaration
3755 // currently lack the information needed to correctly determine their
3756 // ranges when accounting for the type-specifier. We use context
3757 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3758 // and if so, whether it is the first decl.
3759 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3760 if (!cxcursor::isFirstInDeclGroup(C))
3761 Loc = VD->getLocation();
3762 }
3763
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003764 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003765}
Douglas Gregora7bde202010-01-19 00:34:46 +00003766
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003767} // end extern "C"
3768
3769static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003770 if (clang_isReference(C.kind)) {
3771 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003772 case CXCursor_ObjCSuperClassRef:
3773 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003774
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003775 case CXCursor_ObjCProtocolRef:
3776 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003777
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003778 case CXCursor_ObjCClassRef:
3779 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003780
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003781 case CXCursor_TypeRef:
3782 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003783
3784 case CXCursor_TemplateRef:
3785 return getCursorTemplateRef(C).second;
3786
Douglas Gregor69319002010-08-31 23:48:11 +00003787 case CXCursor_NamespaceRef:
3788 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003789
3790 case CXCursor_MemberRef:
3791 return getCursorMemberRef(C).second;
3792
Ted Kremenek3064ef92010-08-27 21:34:58 +00003793 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003794 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003795
Douglas Gregor36897b02010-09-10 00:22:18 +00003796 case CXCursor_LabelRef:
3797 return getCursorLabelRef(C).second;
3798
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003799 case CXCursor_OverloadedDeclRef:
3800 return getCursorOverloadedDeclRef(C).second;
3801
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003802 default:
3803 // FIXME: Need a way to enumerate all non-reference cases.
3804 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003805 }
3806 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003807
3808 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003809 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003810
3811 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003812 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003813
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003814 if (C.kind == CXCursor_PreprocessingDirective)
3815 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003816
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003817 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003818 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003819
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003820 if (C.kind == CXCursor_MacroDefinition)
3821 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003822
3823 if (C.kind == CXCursor_InclusionDirective)
3824 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3825
Ted Kremenek007a7c92010-11-01 23:26:51 +00003826 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3827 Decl *D = cxcursor::getCursorDecl(C);
3828 SourceRange R = D->getSourceRange();
3829 // FIXME: Multiple variables declared in a single declaration
3830 // currently lack the information needed to correctly determine their
3831 // ranges when accounting for the type-specifier. We use context
3832 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3833 // and if so, whether it is the first decl.
3834 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3835 if (!cxcursor::isFirstInDeclGroup(C))
3836 R.setBegin(VD->getLocation());
3837 }
3838 return R;
3839 }
Douglas Gregor66537982010-11-17 17:14:07 +00003840 return SourceRange();
3841}
3842
3843/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3844/// the decl-specifier-seq for declarations.
3845static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3846 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3847 Decl *D = cxcursor::getCursorDecl(C);
3848 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003849
Douglas Gregor2494dd02011-03-01 01:34:45 +00003850 // Adjust the start of the location for declarations preceded by
3851 // declaration specifiers.
3852 SourceLocation StartLoc;
3853 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3854 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3855 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3856 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3857 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3858 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3859 }
3860
3861 if (StartLoc.isValid() && R.getBegin().isValid() &&
3862 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3863 R.setBegin(StartLoc);
3864
3865 // FIXME: Multiple variables declared in a single declaration
3866 // currently lack the information needed to correctly determine their
3867 // ranges when accounting for the type-specifier. We use context
3868 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3869 // and if so, whether it is the first decl.
3870 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3871 if (!cxcursor::isFirstInDeclGroup(C))
3872 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003873 }
3874
3875 return R;
3876 }
3877
3878 return getRawCursorExtent(C);
3879}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003880
3881extern "C" {
3882
3883CXSourceRange clang_getCursorExtent(CXCursor C) {
3884 SourceRange R = getRawCursorExtent(C);
3885 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003886 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003888 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003889}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003890
3891CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003892 if (clang_isInvalid(C.kind))
3893 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003896 if (clang_isDeclaration(C.kind)) {
3897 Decl *D = getCursorDecl(C);
3898 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003899 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003900 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003901 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003902 if (ObjCForwardProtocolDecl *Protocols
3903 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003904 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003905 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003906 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3907 return MakeCXCursor(Property, tu);
3908
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003909 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003910 }
3911
Douglas Gregor97b98722010-01-19 23:20:36 +00003912 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003913 Expr *E = getCursorExpr(C);
3914 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003915 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003916 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003917
3918 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003919 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003920
Douglas Gregor97b98722010-01-19 23:20:36 +00003921 return clang_getNullCursor();
3922 }
3923
Douglas Gregor36897b02010-09-10 00:22:18 +00003924 if (clang_isStatement(C.kind)) {
3925 Stmt *S = getCursorStmt(C);
3926 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003927 if (LabelDecl *label = Goto->getLabel())
3928 if (LabelStmt *labelS = label->getStmt())
3929 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003930
3931 return clang_getNullCursor();
3932 }
3933
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003934 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003935 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003936 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003937 }
3938
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003939 if (!clang_isReference(C.kind))
3940 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003941
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003942 switch (C.kind) {
3943 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003944 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003945
3946 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003947 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003948
3949 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003950 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003951
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003952 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003953 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003954
3955 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003956 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003957
Douglas Gregor69319002010-08-31 23:48:11 +00003958 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003959 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003960
Douglas Gregora67e03f2010-09-09 21:42:20 +00003961 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003962 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003963
Ted Kremenek3064ef92010-08-27 21:34:58 +00003964 case CXCursor_CXXBaseSpecifier: {
3965 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3966 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003967 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003968 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003969
Douglas Gregor36897b02010-09-10 00:22:18 +00003970 case CXCursor_LabelRef:
3971 // FIXME: We end up faking the "parent" declaration here because we
3972 // don't want to make CXCursor larger.
3973 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003974 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3975 .getTranslationUnitDecl(),
3976 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003977
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003978 case CXCursor_OverloadedDeclRef:
3979 return C;
3980
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003981 default:
3982 // We would prefer to enumerate all non-reference cursor kinds here.
3983 llvm_unreachable("Unhandled reference cursor kind");
3984 break;
3985 }
3986 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003987
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003988 return clang_getNullCursor();
3989}
3990
Douglas Gregorb6998662010-01-19 19:34:47 +00003991CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003992 if (clang_isInvalid(C.kind))
3993 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003994
Ted Kremeneka60ed472010-11-16 08:15:36 +00003995 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003996
Douglas Gregorb6998662010-01-19 19:34:47 +00003997 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003998 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003999 C = clang_getCursorReferenced(C);
4000 WasReference = true;
4001 }
4002
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004003 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004004 return clang_getCursorReferenced(C);
4005
Douglas Gregorb6998662010-01-19 19:34:47 +00004006 if (!clang_isDeclaration(C.kind))
4007 return clang_getNullCursor();
4008
4009 Decl *D = getCursorDecl(C);
4010 if (!D)
4011 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004012
Douglas Gregorb6998662010-01-19 19:34:47 +00004013 switch (D->getKind()) {
4014 // Declaration kinds that don't really separate the notions of
4015 // declaration and definition.
4016 case Decl::Namespace:
4017 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004018 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004019 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004020 case Decl::TemplateTypeParm:
4021 case Decl::EnumConstant:
4022 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004023 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004024 case Decl::ObjCIvar:
4025 case Decl::ObjCAtDefsField:
4026 case Decl::ImplicitParam:
4027 case Decl::ParmVar:
4028 case Decl::NonTypeTemplateParm:
4029 case Decl::TemplateTemplateParm:
4030 case Decl::ObjCCategoryImpl:
4031 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004032 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004033 case Decl::LinkageSpec:
4034 case Decl::ObjCPropertyImpl:
4035 case Decl::FileScopeAsm:
4036 case Decl::StaticAssert:
4037 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004038 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004039 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004040 return C;
4041
4042 // Declaration kinds that don't make any sense here, but are
4043 // nonetheless harmless.
4044 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004045 break;
4046
4047 // Declaration kinds for which the definition is not resolvable.
4048 case Decl::UnresolvedUsingTypename:
4049 case Decl::UnresolvedUsingValue:
4050 break;
4051
4052 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004053 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004054 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004055
4056 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004057 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004058
4059 case Decl::Enum:
4060 case Decl::Record:
4061 case Decl::CXXRecord:
4062 case Decl::ClassTemplateSpecialization:
4063 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004064 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004065 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004066 return clang_getNullCursor();
4067
4068 case Decl::Function:
4069 case Decl::CXXMethod:
4070 case Decl::CXXConstructor:
4071 case Decl::CXXDestructor:
4072 case Decl::CXXConversion: {
4073 const FunctionDecl *Def = 0;
4074 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004075 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004076 return clang_getNullCursor();
4077 }
4078
4079 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004080 // Ask the variable if it has a definition.
4081 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004083 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004084 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004085
Douglas Gregorb6998662010-01-19 19:34:47 +00004086 case Decl::FunctionTemplate: {
4087 const FunctionDecl *Def = 0;
4088 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004089 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004090 return clang_getNullCursor();
4091 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004092
Douglas Gregorb6998662010-01-19 19:34:47 +00004093 case Decl::ClassTemplate: {
4094 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004095 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004096 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004097 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004098 return clang_getNullCursor();
4099 }
4100
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004101 case Decl::Using:
4102 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004103 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004104
4105 case Decl::UsingShadow:
4106 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004107 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004108 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004109
4110 case Decl::ObjCMethod: {
4111 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4112 if (Method->isThisDeclarationADefinition())
4113 return C;
4114
4115 // Dig out the method definition in the associated
4116 // @implementation, if we have it.
4117 // FIXME: The ASTs should make finding the definition easier.
4118 if (ObjCInterfaceDecl *Class
4119 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4120 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4121 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4122 Method->isInstanceMethod()))
4123 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004124 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004125
4126 return clang_getNullCursor();
4127 }
4128
4129 case Decl::ObjCCategory:
4130 if (ObjCCategoryImplDecl *Impl
4131 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004132 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004133 return clang_getNullCursor();
4134
4135 case Decl::ObjCProtocol:
4136 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4137 return C;
4138 return clang_getNullCursor();
4139
4140 case Decl::ObjCInterface:
4141 // There are two notions of a "definition" for an Objective-C
4142 // class: the interface and its implementation. When we resolved a
4143 // reference to an Objective-C class, produce the @interface as
4144 // the definition; when we were provided with the interface,
4145 // produce the @implementation as the definition.
4146 if (WasReference) {
4147 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4148 return C;
4149 } else if (ObjCImplementationDecl *Impl
4150 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004151 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004152 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004153
Douglas Gregorb6998662010-01-19 19:34:47 +00004154 case Decl::ObjCProperty:
4155 // FIXME: We don't really know where to find the
4156 // ObjCPropertyImplDecls that implement this property.
4157 return clang_getNullCursor();
4158
4159 case Decl::ObjCCompatibleAlias:
4160 if (ObjCInterfaceDecl *Class
4161 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4162 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004163 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004164
Douglas Gregorb6998662010-01-19 19:34:47 +00004165 return clang_getNullCursor();
4166
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004167 case Decl::ObjCForwardProtocol:
4168 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004169 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004170
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004171 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004172 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004173 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004174
4175 case Decl::Friend:
4176 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004177 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004178 return clang_getNullCursor();
4179
4180 case Decl::FriendTemplate:
4181 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004182 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004183 return clang_getNullCursor();
4184 }
4185
4186 return clang_getNullCursor();
4187}
4188
4189unsigned clang_isCursorDefinition(CXCursor C) {
4190 if (!clang_isDeclaration(C.kind))
4191 return 0;
4192
4193 return clang_getCursorDefinition(C) == C;
4194}
4195
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004196CXCursor clang_getCanonicalCursor(CXCursor C) {
4197 if (!clang_isDeclaration(C.kind))
4198 return C;
4199
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004200 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004201 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4202 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4203 return MakeCXCursor(CatD, getCursorTU(C));
4204
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004205 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4206 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4207 return MakeCXCursor(IFD, getCursorTU(C));
4208
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004209 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004210 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004211
4212 return C;
4213}
4214
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004215unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004216 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004217 return 0;
4218
4219 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4220 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4221 return E->getNumDecls();
4222
4223 if (OverloadedTemplateStorage *S
4224 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4225 return S->size();
4226
4227 Decl *D = Storage.get<Decl*>();
4228 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004229 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004230 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4231 return Classes->size();
4232 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4233 return Protocols->protocol_size();
4234
4235 return 0;
4236}
4237
4238CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004239 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004240 return clang_getNullCursor();
4241
4242 if (index >= clang_getNumOverloadedDecls(cursor))
4243 return clang_getNullCursor();
4244
Ted Kremeneka60ed472010-11-16 08:15:36 +00004245 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004246 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4247 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004248 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004249
4250 if (OverloadedTemplateStorage *S
4251 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004252 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004253
4254 Decl *D = Storage.get<Decl*>();
4255 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4256 // FIXME: This is, unfortunately, linear time.
4257 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4258 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004259 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004260 }
4261
4262 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004263 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004264
4265 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004266 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004267
4268 return clang_getNullCursor();
4269}
4270
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004271void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004272 const char **startBuf,
4273 const char **endBuf,
4274 unsigned *startLine,
4275 unsigned *startColumn,
4276 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004277 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004278 assert(getCursorDecl(C) && "CXCursor has null decl");
4279 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004280 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4281 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004282
Steve Naroff4ade6d62009-09-23 17:52:52 +00004283 SourceManager &SM = FD->getASTContext().getSourceManager();
4284 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4285 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4286 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4287 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4288 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4289 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4290}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004291
Douglas Gregor430d7a12011-07-25 17:48:11 +00004292
4293CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4294 unsigned PieceIndex) {
4295 RefNamePieces Pieces;
4296
4297 switch (C.kind) {
4298 case CXCursor_MemberRefExpr:
4299 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4300 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4301 E->getQualifierLoc().getSourceRange());
4302 break;
4303
4304 case CXCursor_DeclRefExpr:
4305 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4306 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4307 E->getQualifierLoc().getSourceRange(),
4308 E->getExplicitTemplateArgsOpt());
4309 break;
4310
4311 case CXCursor_CallExpr:
4312 if (CXXOperatorCallExpr *OCE =
4313 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4314 Expr *Callee = OCE->getCallee();
4315 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4316 Callee = ICE->getSubExpr();
4317
4318 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4319 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4320 DRE->getQualifierLoc().getSourceRange());
4321 }
4322 break;
4323
4324 default:
4325 break;
4326 }
4327
4328 if (Pieces.empty()) {
4329 if (PieceIndex == 0)
4330 return clang_getCursorExtent(C);
4331 } else if (PieceIndex < Pieces.size()) {
4332 SourceRange R = Pieces[PieceIndex];
4333 if (R.isValid())
4334 return cxloc::translateSourceRange(getCursorContext(C), R);
4335 }
4336
4337 return clang_getNullRange();
4338}
4339
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004340void clang_enableStackTraces(void) {
4341 llvm::sys::PrintStackTraceOnErrorSignal();
4342}
4343
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004344void clang_executeOnThread(void (*fn)(void*), void *user_data,
4345 unsigned stack_size) {
4346 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4347}
4348
Ted Kremenekfb480492010-01-13 21:46:36 +00004349} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004350
Ted Kremenekfb480492010-01-13 21:46:36 +00004351//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004352// Token-based Operations.
4353//===----------------------------------------------------------------------===//
4354
4355/* CXToken layout:
4356 * int_data[0]: a CXTokenKind
4357 * int_data[1]: starting token location
4358 * int_data[2]: token length
4359 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004360 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004361 * otherwise unused.
4362 */
4363extern "C" {
4364
4365CXTokenKind clang_getTokenKind(CXToken CXTok) {
4366 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4367}
4368
4369CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4370 switch (clang_getTokenKind(CXTok)) {
4371 case CXToken_Identifier:
4372 case CXToken_Keyword:
4373 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004374 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4375 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004376
4377 case CXToken_Literal: {
4378 // We have stashed the starting pointer in the ptr_data field. Use it.
4379 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004380 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004381 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004382
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004383 case CXToken_Punctuation:
4384 case CXToken_Comment:
4385 break;
4386 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004387
4388 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004389 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004390 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004391 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004392 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004393
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004394 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4395 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004396 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004397 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004398 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004399 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4400 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004401 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004402
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004403 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004404}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004405
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004406CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004407 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004408 if (!CXXUnit)
4409 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004410
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004411 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4412 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4413}
4414
4415CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004416 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004417 if (!CXXUnit)
4418 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004419
4420 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004421 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4422}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004423
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004424void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4425 CXToken **Tokens, unsigned *NumTokens) {
4426 if (Tokens)
4427 *Tokens = 0;
4428 if (NumTokens)
4429 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004430
Ted Kremeneka60ed472010-11-16 08:15:36 +00004431 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004432 if (!CXXUnit || !Tokens || !NumTokens)
4433 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004434
Douglas Gregorbdf60622010-03-05 21:16:25 +00004435 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4436
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004437 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004438 if (R.isInvalid())
4439 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004440
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004441 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4442 std::pair<FileID, unsigned> BeginLocInfo
4443 = SourceMgr.getDecomposedLoc(R.getBegin());
4444 std::pair<FileID, unsigned> EndLocInfo
4445 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004446
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004447 // Cannot tokenize across files.
4448 if (BeginLocInfo.first != EndLocInfo.first)
4449 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004450
4451 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004452 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004453 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004454 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004455 if (Invalid)
4456 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004457
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004458 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4459 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004460 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004461 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004462
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004463 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004464 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004465 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004466 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004467 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004468 do {
4469 // Lex the next token
4470 Lex.LexFromRawLexer(Tok);
4471 if (Tok.is(tok::eof))
4472 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004473
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004474 // Initialize the CXToken.
4475 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004476
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004477 // - Common fields
4478 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4479 CXTok.int_data[2] = Tok.getLength();
4480 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004481
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004482 // - Kind-specific fields
4483 if (Tok.isLiteral()) {
4484 CXTok.int_data[0] = CXToken_Literal;
4485 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004486 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004487 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004488 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004489 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004490
David Chisnall096428b2010-10-13 21:44:48 +00004491 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004492 CXTok.int_data[0] = CXToken_Keyword;
4493 }
4494 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004495 CXTok.int_data[0] = Tok.is(tok::identifier)
4496 ? CXToken_Identifier
4497 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004498 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004499 CXTok.ptr_data = II;
4500 } else if (Tok.is(tok::comment)) {
4501 CXTok.int_data[0] = CXToken_Comment;
4502 CXTok.ptr_data = 0;
4503 } else {
4504 CXTok.int_data[0] = CXToken_Punctuation;
4505 CXTok.ptr_data = 0;
4506 }
4507 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004508 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004509 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004510
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004511 if (CXTokens.empty())
4512 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004513
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004514 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4515 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4516 *NumTokens = CXTokens.size();
4517}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004518
Ted Kremenek6db61092010-05-05 00:55:15 +00004519void clang_disposeTokens(CXTranslationUnit TU,
4520 CXToken *Tokens, unsigned NumTokens) {
4521 free(Tokens);
4522}
4523
4524} // end: extern "C"
4525
4526//===----------------------------------------------------------------------===//
4527// Token annotation APIs.
4528//===----------------------------------------------------------------------===//
4529
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004530typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004531static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4532 CXCursor parent,
4533 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004534namespace {
4535class AnnotateTokensWorker {
4536 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004537 CXToken *Tokens;
4538 CXCursor *Cursors;
4539 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004540 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004541 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004542 CursorVisitor AnnotateVis;
4543 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004544 bool HasContextSensitiveKeywords;
4545
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004546 bool MoreTokens() const { return TokIdx < NumTokens; }
4547 unsigned NextToken() const { return TokIdx; }
4548 void AdvanceToken() { ++TokIdx; }
4549 SourceLocation GetTokenLoc(unsigned tokI) {
4550 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4551 }
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004552 bool isMacroArgToken(unsigned tokI) const {
4553 return Tokens[tokI].int_data[3] != 0;
4554 }
4555 SourceLocation getMacroArgLoc(unsigned tokI) const {
4556 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4557 }
4558
4559 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4560 void annotateAndAdvanceMacroArgTokens(CXCursor, RangeComparisonResult,
4561 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004562
Ted Kremenek6db61092010-05-05 00:55:15 +00004563public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004564 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004565 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004566 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004567 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004568 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004569 AnnotateVis(tu,
4570 AnnotateTokensVisitor, this,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00004571 Decl::MaxPCHLevel, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004572 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4573 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004574
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004575 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004576 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004577 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004578 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004579 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004580 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004581
4582 /// \brief Determine whether the annotator saw any cursors that have
4583 /// context-sensitive keywords.
4584 bool hasContextSensitiveKeywords() const {
4585 return HasContextSensitiveKeywords;
4586 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004587};
4588}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004589
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004590void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4591 // Walk the AST within the region of interest, annotating tokens
4592 // along the way.
4593 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004594
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004595 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4596 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004597 if (Pos != Annotated.end() &&
4598 (clang_isInvalid(Cursors[I].kind) ||
4599 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004600 Cursors[I] = Pos->second;
4601 }
4602
4603 // Finish up annotating any tokens left.
4604 if (!MoreTokens())
4605 return;
4606
4607 const CXCursor &C = clang_getNullCursor();
4608 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4609 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4610 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004611 }
4612}
4613
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004614/// \brief It annotates and advances tokens with a cursor until the comparison
4615//// between the cursor location and the source range is the same as
4616/// \arg compResult.
4617///
4618/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4619/// Pass RangeOverlap to annotate tokens inside a range.
4620void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4621 RangeComparisonResult compResult,
4622 SourceRange range) {
4623 while (MoreTokens()) {
4624 const unsigned I = NextToken();
4625 if (isMacroArgToken(I))
4626 return annotateAndAdvanceMacroArgTokens(updateC, compResult, range);
4627
4628 SourceLocation TokLoc = GetTokenLoc(I);
4629 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4630 Cursors[I] = updateC;
4631 AdvanceToken();
4632 continue;
4633 }
4634 break;
4635 }
4636}
4637
4638/// \brief Special annotation handling for macro argument tokens.
4639void AnnotateTokensWorker::annotateAndAdvanceMacroArgTokens(CXCursor updateC,
4640 RangeComparisonResult compResult,
4641 SourceRange range) {
4642 assert(isMacroArgToken(NextToken()) &&
4643 "Should be called only for macro arg tokens");
4644
4645 // This works differently than annotateAndAdvanceTokens; because expanded
4646 // macro arguments can have arbitrary translation-unit source order, we do not
4647 // advance the token index one by one until a token fails the range test.
4648 // We only advance once past all of the macro arg tokens if all of them
4649 // pass the range test. If one of them fails we keep the token index pointing
4650 // at the start of the macro arg tokens so that the failing token will be
4651 // annotated by a subsequent annotation try.
4652
4653 bool atLeastOneCompFail = false;
4654
4655 unsigned I = NextToken();
4656 for (; isMacroArgToken(I); ++I) {
4657 SourceLocation TokLoc = getMacroArgLoc(I);
4658 if (TokLoc.isFileID())
4659 continue; // not macro arg token, it's parens or comma.
4660 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4661 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4662 Cursors[I] = updateC;
4663 } else
4664 atLeastOneCompFail = true;
4665 }
4666
4667 if (!atLeastOneCompFail)
4668 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4669}
4670
Ted Kremenek6db61092010-05-05 00:55:15 +00004671enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004672AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004673 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004674 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004675 if (cursorRange.isInvalid())
4676 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004677
4678 if (!HasContextSensitiveKeywords) {
4679 // Objective-C properties can have context-sensitive keywords.
4680 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4681 if (ObjCPropertyDecl *Property
4682 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4683 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4684 }
4685 // Objective-C methods can have context-sensitive keywords.
4686 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4687 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4688 if (ObjCMethodDecl *Method
4689 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4690 if (Method->getObjCDeclQualifier())
4691 HasContextSensitiveKeywords = true;
4692 else {
4693 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4694 PEnd = Method->param_end();
4695 P != PEnd; ++P) {
4696 if ((*P)->getObjCDeclQualifier()) {
4697 HasContextSensitiveKeywords = true;
4698 break;
4699 }
4700 }
4701 }
4702 }
4703 }
4704 // C++ methods can have context-sensitive keywords.
4705 else if (cursor.kind == CXCursor_CXXMethod) {
4706 if (CXXMethodDecl *Method
4707 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4708 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4709 HasContextSensitiveKeywords = true;
4710 }
4711 }
4712 // C++ classes can have context-sensitive keywords.
4713 else if (cursor.kind == CXCursor_StructDecl ||
4714 cursor.kind == CXCursor_ClassDecl ||
4715 cursor.kind == CXCursor_ClassTemplate ||
4716 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4717 if (Decl *D = getCursorDecl(cursor))
4718 if (D->hasAttr<FinalAttr>())
4719 HasContextSensitiveKeywords = true;
4720 }
4721 }
4722
Douglas Gregor4419b672010-10-21 06:10:04 +00004723 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004724 // For macro expansions, just note where the beginning of the macro
4725 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004726 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004727 Annotated[Loc.int_data] = cursor;
4728 return CXChildVisit_Recurse;
4729 }
4730
Douglas Gregor4419b672010-10-21 06:10:04 +00004731 // Items in the preprocessing record are kept separate from items in
4732 // declarations, so we keep a separate token index.
4733 unsigned SavedTokIdx = TokIdx;
4734 TokIdx = PreprocessingTokIdx;
4735
4736 // Skip tokens up until we catch up to the beginning of the preprocessing
4737 // entry.
4738 while (MoreTokens()) {
4739 const unsigned I = NextToken();
4740 SourceLocation TokLoc = GetTokenLoc(I);
4741 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4742 case RangeBefore:
4743 AdvanceToken();
4744 continue;
4745 case RangeAfter:
4746 case RangeOverlap:
4747 break;
4748 }
4749 break;
4750 }
4751
4752 // Look at all of the tokens within this range.
4753 while (MoreTokens()) {
4754 const unsigned I = NextToken();
4755 SourceLocation TokLoc = GetTokenLoc(I);
4756 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4757 case RangeBefore:
4758 assert(0 && "Infeasible");
4759 case RangeAfter:
4760 break;
4761 case RangeOverlap:
4762 Cursors[I] = cursor;
4763 AdvanceToken();
4764 continue;
4765 }
4766 break;
4767 }
4768
4769 // Save the preprocessing token index; restore the non-preprocessing
4770 // token index.
4771 PreprocessingTokIdx = TokIdx;
4772 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004773 return CXChildVisit_Recurse;
4774 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004775
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004776 if (cursorRange.isInvalid())
4777 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004778
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004779 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4780
Ted Kremeneka333c662010-05-12 05:29:33 +00004781 // Adjust the annotated range based specific declarations.
4782 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4783 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004784 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004785
4786 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004787 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004788 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4789 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4790 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4791 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4792 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004793 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004794
4795 if (StartLoc.isValid() && L.isValid() &&
4796 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4797 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004798 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004799
Ted Kremenek3f404602010-08-14 01:14:06 +00004800 // If the location of the cursor occurs within a macro instantiation, record
4801 // the spelling location of the cursor in our annotation map. We can then
4802 // paper over the token labelings during a post-processing step to try and
4803 // get cursor mappings for tokens that are the *arguments* of a macro
4804 // instantiation.
4805 if (L.isMacroID()) {
4806 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4807 // Only invalidate the old annotation if it isn't part of a preprocessing
4808 // directive. Here we assume that the default construction of CXCursor
4809 // results in CXCursor.kind being an initialized value (i.e., 0). If
4810 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004811
Ted Kremenek3f404602010-08-14 01:14:06 +00004812 CXCursor &oldC = Annotated[rawEncoding];
4813 if (!clang_isPreprocessing(oldC.kind))
4814 oldC = cursor;
4815 }
4816
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004817 const enum CXCursorKind K = clang_getCursorKind(parent);
4818 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004819 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4820 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004821
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004822 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004823
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004824 // Avoid having the cursor of an expression "overwrite" the annotation of the
4825 // variable declaration that it belongs to.
4826 // This can happen for C++ constructor expressions whose range generally
4827 // include the variable declaration, e.g.:
4828 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4829 if (clang_isExpression(cursorK)) {
4830 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004831 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004832 const unsigned I = NextToken();
4833 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4834 E->getLocStart() == D->getLocation() &&
4835 E->getLocStart() == GetTokenLoc(I)) {
4836 Cursors[I] = updateC;
4837 AdvanceToken();
4838 }
4839 }
4840 }
4841
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004842 // Visit children to get their cursor information.
4843 const unsigned BeforeChildren = NextToken();
4844 VisitChildren(cursor);
4845 const unsigned AfterChildren = NextToken();
4846
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004847 // Scan the tokens that are at the end of the cursor, but are not captured
4848 // but the child cursors.
4849 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004850
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004851 // Scan the tokens that are at the beginning of the cursor, but are not
4852 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004853 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4854 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4855 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004856
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004857 Cursors[I] = cursor;
4858 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004859
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004860 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004861}
4862
Ted Kremenek6db61092010-05-05 00:55:15 +00004863static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4864 CXCursor parent,
4865 CXClientData client_data) {
4866 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4867}
4868
Ted Kremenek6628a612011-03-18 22:51:30 +00004869namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004870
4871/// \brief Uses the macro expansions in the preprocessing record to find
4872/// and mark tokens that are macro arguments. This info is used by the
4873/// AnnotateTokensWorker.
4874class MarkMacroArgTokensVisitor {
4875 SourceManager &SM;
4876 CXToken *Tokens;
4877 unsigned NumTokens;
4878 unsigned CurIdx;
4879
4880public:
4881 MarkMacroArgTokensVisitor(SourceManager &SM,
4882 CXToken *tokens, unsigned numTokens)
4883 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4884
4885 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4886 if (cursor.kind != CXCursor_MacroExpansion)
4887 return CXChildVisit_Continue;
4888
4889 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4890 if (macroRange.getBegin() == macroRange.getEnd())
4891 return CXChildVisit_Continue; // it's not a function macro.
4892
4893 for (; CurIdx < NumTokens; ++CurIdx) {
4894 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4895 macroRange.getBegin()))
4896 break;
4897 }
4898
4899 if (CurIdx == NumTokens)
4900 return CXChildVisit_Break;
4901
4902 for (; CurIdx < NumTokens; ++CurIdx) {
4903 SourceLocation tokLoc = getTokenLoc(CurIdx);
4904 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4905 break;
4906
4907 setMacroArgExpandedLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
4908 }
4909
4910 if (CurIdx == NumTokens)
4911 return CXChildVisit_Break;
4912
4913 return CXChildVisit_Continue;
4914 }
4915
4916private:
4917 SourceLocation getTokenLoc(unsigned tokI) {
4918 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4919 }
4920
4921 void setMacroArgExpandedLoc(unsigned tokI, SourceLocation loc) {
4922 // The third field is reserved and currently not used. Use it here
4923 // to mark macro arg expanded tokens with their expanded locations.
4924 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4925 }
4926};
4927
4928} // end anonymous namespace
4929
4930static CXChildVisitResult
4931MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4932 CXClientData client_data) {
4933 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4934 parent);
4935}
4936
4937namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004938 struct clang_annotateTokens_Data {
4939 CXTranslationUnit TU;
4940 ASTUnit *CXXUnit;
4941 CXToken *Tokens;
4942 unsigned NumTokens;
4943 CXCursor *Cursors;
4944 };
4945}
4946
Ted Kremenekab979612010-11-11 08:05:23 +00004947// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004948static void clang_annotateTokensImpl(void *UserData) {
4949 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4950 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4951 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4952 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4953 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4954
4955 // Determine the region of interest, which contains all of the tokens.
4956 SourceRange RegionOfInterest;
4957 RegionOfInterest.setBegin(
4958 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4959 RegionOfInterest.setEnd(
4960 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4961 Tokens[NumTokens-1])));
4962
4963 // A mapping from the source locations found when re-lexing or traversing the
4964 // region of interest to the corresponding cursors.
4965 AnnotateTokensData Annotated;
4966
4967 // Relex the tokens within the source range to look for preprocessing
4968 // directives.
4969 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4970 std::pair<FileID, unsigned> BeginLocInfo
4971 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4972 std::pair<FileID, unsigned> EndLocInfo
4973 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4974
Chris Lattner5f9e2722011-07-23 10:55:15 +00004975 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00004976 bool Invalid = false;
4977 if (BeginLocInfo.first == EndLocInfo.first &&
4978 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4979 !Invalid) {
4980 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4981 CXXUnit->getASTContext().getLangOptions(),
4982 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4983 Buffer.end());
4984 Lex.SetCommentRetentionState(true);
4985
4986 // Lex tokens in raw mode until we hit the end of the range, to avoid
4987 // entering #includes or expanding macros.
4988 while (true) {
4989 Token Tok;
4990 Lex.LexFromRawLexer(Tok);
4991
4992 reprocess:
4993 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4994 // We have found a preprocessing directive. Gobble it up so that we
4995 // don't see it while preprocessing these tokens later, but keep track
4996 // of all of the token locations inside this preprocessing directive so
4997 // that we can annotate them appropriately.
4998 //
4999 // FIXME: Some simple tests here could identify macro definitions and
5000 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005001 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00005002 do {
5003 Locations.push_back(Tok.getLocation());
5004 Lex.LexFromRawLexer(Tok);
5005 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5006
5007 using namespace cxcursor;
5008 CXCursor Cursor
5009 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5010 Locations.back()),
5011 TU);
5012 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5013 Annotated[Locations[I].getRawEncoding()] = Cursor;
5014 }
5015
5016 if (Tok.isAtStartOfLine())
5017 goto reprocess;
5018
5019 continue;
5020 }
5021
5022 if (Tok.is(tok::eof))
5023 break;
5024 }
5025 }
5026
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005027 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5028 // Search and mark tokens that are macro argument expansions.
5029 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5030 Tokens, NumTokens);
5031 CursorVisitor MacroArgMarker(TU,
5032 MarkMacroArgTokensVisitorDelegate, &Visitor,
5033 Decl::MaxPCHLevel, true, RegionOfInterest);
5034 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5035 }
5036
Ted Kremenek6628a612011-03-18 22:51:30 +00005037 // Annotate all of the source locations in the region of interest that map to
5038 // a specific cursor.
5039 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5040 TU, RegionOfInterest);
5041
5042 // FIXME: We use a ridiculous stack size here because the data-recursion
5043 // algorithm uses a large stack frame than the non-data recursive version,
5044 // and AnnotationTokensWorker currently transforms the data-recursion
5045 // algorithm back into a traditional recursion by explicitly calling
5046 // VisitChildren(). We will need to remove this explicit recursive call.
5047 W.AnnotateTokens();
5048
5049 // If we ran into any entities that involve context-sensitive keywords,
5050 // take another pass through the tokens to mark them as such.
5051 if (W.hasContextSensitiveKeywords()) {
5052 for (unsigned I = 0; I != NumTokens; ++I) {
5053 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5054 continue;
5055
5056 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5057 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5058 if (ObjCPropertyDecl *Property
5059 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5060 if (Property->getPropertyAttributesAsWritten() != 0 &&
5061 llvm::StringSwitch<bool>(II->getName())
5062 .Case("readonly", true)
5063 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005064 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005065 .Case("readwrite", true)
5066 .Case("retain", true)
5067 .Case("copy", true)
5068 .Case("nonatomic", true)
5069 .Case("atomic", true)
5070 .Case("getter", true)
5071 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005072 .Case("strong", true)
5073 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005074 .Default(false))
5075 Tokens[I].int_data[0] = CXToken_Keyword;
5076 }
5077 continue;
5078 }
5079
5080 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5081 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5082 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5083 if (llvm::StringSwitch<bool>(II->getName())
5084 .Case("in", true)
5085 .Case("out", true)
5086 .Case("inout", true)
5087 .Case("oneway", true)
5088 .Case("bycopy", true)
5089 .Case("byref", true)
5090 .Default(false))
5091 Tokens[I].int_data[0] = CXToken_Keyword;
5092 continue;
5093 }
5094
5095 if (Cursors[I].kind == CXCursor_CXXMethod) {
5096 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5097 if (CXXMethodDecl *Method
5098 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
5099 if ((Method->hasAttr<FinalAttr>() ||
5100 Method->hasAttr<OverrideAttr>()) &&
5101 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
5102 llvm::StringSwitch<bool>(II->getName())
5103 .Case("final", true)
5104 .Case("override", true)
5105 .Default(false))
5106 Tokens[I].int_data[0] = CXToken_Keyword;
5107 }
5108 continue;
5109 }
5110
5111 if (Cursors[I].kind == CXCursor_ClassDecl ||
5112 Cursors[I].kind == CXCursor_StructDecl ||
5113 Cursors[I].kind == CXCursor_ClassTemplate) {
5114 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5115 if (II->getName() == "final") {
5116 // We have to be careful with 'final', since it could be the name
5117 // of a member class rather than the context-sensitive keyword.
5118 // So, check whether the cursor associated with this
5119 Decl *D = getCursorDecl(Cursors[I]);
5120 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
5121 if ((Record->hasAttr<FinalAttr>()) &&
5122 Record->getIdentifier() != II)
5123 Tokens[I].int_data[0] = CXToken_Keyword;
5124 } else if (ClassTemplateDecl *ClassTemplate
5125 = dyn_cast_or_null<ClassTemplateDecl>(D)) {
5126 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
5127 if ((Record->hasAttr<FinalAttr>()) &&
5128 Record->getIdentifier() != II)
5129 Tokens[I].int_data[0] = CXToken_Keyword;
5130 }
5131 }
5132 continue;
5133 }
5134 }
5135 }
Ted Kremenekab979612010-11-11 08:05:23 +00005136}
5137
Ted Kremenek6db61092010-05-05 00:55:15 +00005138extern "C" {
5139
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005140void clang_annotateTokens(CXTranslationUnit TU,
5141 CXToken *Tokens, unsigned NumTokens,
5142 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005143
5144 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005145 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005146
Douglas Gregor4419b672010-10-21 06:10:04 +00005147 // Any token we don't specifically annotate will have a NULL cursor.
5148 CXCursor C = clang_getNullCursor();
5149 for (unsigned I = 0; I != NumTokens; ++I)
5150 Cursors[I] = C;
5151
Ted Kremeneka60ed472010-11-16 08:15:36 +00005152 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005153 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005154 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005155
Douglas Gregorbdf60622010-03-05 21:16:25 +00005156 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005157
5158 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005159 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005160 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005161 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005162 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5163 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005164}
Ted Kremenek6628a612011-03-18 22:51:30 +00005165
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005166} // end: extern "C"
5167
5168//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005169// Operations for querying linkage of a cursor.
5170//===----------------------------------------------------------------------===//
5171
5172extern "C" {
5173CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005174 if (!clang_isDeclaration(cursor.kind))
5175 return CXLinkage_Invalid;
5176
Ted Kremenek16b42592010-03-03 06:36:57 +00005177 Decl *D = cxcursor::getCursorDecl(cursor);
5178 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5179 switch (ND->getLinkage()) {
5180 case NoLinkage: return CXLinkage_NoLinkage;
5181 case InternalLinkage: return CXLinkage_Internal;
5182 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5183 case ExternalLinkage: return CXLinkage_External;
5184 };
5185
5186 return CXLinkage_Invalid;
5187}
5188} // end: extern "C"
5189
5190//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005191// Operations for querying language of a cursor.
5192//===----------------------------------------------------------------------===//
5193
5194static CXLanguageKind getDeclLanguage(const Decl *D) {
5195 switch (D->getKind()) {
5196 default:
5197 break;
5198 case Decl::ImplicitParam:
5199 case Decl::ObjCAtDefsField:
5200 case Decl::ObjCCategory:
5201 case Decl::ObjCCategoryImpl:
5202 case Decl::ObjCClass:
5203 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005204 case Decl::ObjCForwardProtocol:
5205 case Decl::ObjCImplementation:
5206 case Decl::ObjCInterface:
5207 case Decl::ObjCIvar:
5208 case Decl::ObjCMethod:
5209 case Decl::ObjCProperty:
5210 case Decl::ObjCPropertyImpl:
5211 case Decl::ObjCProtocol:
5212 return CXLanguage_ObjC;
5213 case Decl::CXXConstructor:
5214 case Decl::CXXConversion:
5215 case Decl::CXXDestructor:
5216 case Decl::CXXMethod:
5217 case Decl::CXXRecord:
5218 case Decl::ClassTemplate:
5219 case Decl::ClassTemplatePartialSpecialization:
5220 case Decl::ClassTemplateSpecialization:
5221 case Decl::Friend:
5222 case Decl::FriendTemplate:
5223 case Decl::FunctionTemplate:
5224 case Decl::LinkageSpec:
5225 case Decl::Namespace:
5226 case Decl::NamespaceAlias:
5227 case Decl::NonTypeTemplateParm:
5228 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005229 case Decl::TemplateTemplateParm:
5230 case Decl::TemplateTypeParm:
5231 case Decl::UnresolvedUsingTypename:
5232 case Decl::UnresolvedUsingValue:
5233 case Decl::Using:
5234 case Decl::UsingDirective:
5235 case Decl::UsingShadow:
5236 return CXLanguage_CPlusPlus;
5237 }
5238
5239 return CXLanguage_C;
5240}
5241
5242extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005243
5244enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5245 if (clang_isDeclaration(cursor.kind))
5246 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005247 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005248 return CXAvailability_Available;
5249
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005250 switch (D->getAvailability()) {
5251 case AR_Available:
5252 case AR_NotYetIntroduced:
5253 return CXAvailability_Available;
5254
5255 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005256 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005257
5258 case AR_Unavailable:
5259 return CXAvailability_NotAvailable;
5260 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005261 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005262
Douglas Gregor58ddb602010-08-23 23:00:57 +00005263 return CXAvailability_Available;
5264}
5265
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005266CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5267 if (clang_isDeclaration(cursor.kind))
5268 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5269
5270 return CXLanguage_Invalid;
5271}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005272
5273 /// \brief If the given cursor is the "templated" declaration
5274 /// descibing a class or function template, return the class or
5275 /// function template.
5276static Decl *maybeGetTemplateCursor(Decl *D) {
5277 if (!D)
5278 return 0;
5279
5280 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5281 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5282 return FunTmpl;
5283
5284 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5285 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5286 return ClassTmpl;
5287
5288 return D;
5289}
5290
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005291CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5292 if (clang_isDeclaration(cursor.kind)) {
5293 if (Decl *D = getCursorDecl(cursor)) {
5294 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005295 if (!DC)
5296 return clang_getNullCursor();
5297
5298 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5299 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005300 }
5301 }
5302
5303 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5304 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005305 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005306 }
5307
5308 return clang_getNullCursor();
5309}
5310
5311CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5312 if (clang_isDeclaration(cursor.kind)) {
5313 if (Decl *D = getCursorDecl(cursor)) {
5314 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005315 if (!DC)
5316 return clang_getNullCursor();
5317
5318 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5319 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005320 }
5321 }
5322
5323 // FIXME: Note that we can't easily compute the lexical context of a
5324 // statement or expression, so we return nothing.
5325 return clang_getNullCursor();
5326}
5327
Douglas Gregor9f592342010-10-01 20:25:15 +00005328static void CollectOverriddenMethods(DeclContext *Ctx,
5329 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005330 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005331 if (!Ctx)
5332 return;
5333
5334 // If we have a class or category implementation, jump straight to the
5335 // interface.
5336 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5337 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5338
5339 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5340 if (!Container)
5341 return;
5342
5343 // Check whether we have a matching method at this level.
5344 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5345 Method->isInstanceMethod()))
5346 if (Method != Overridden) {
5347 // We found an override at this level; there is no need to look
5348 // into other protocols or categories.
5349 Methods.push_back(Overridden);
5350 return;
5351 }
5352
5353 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5354 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5355 PEnd = Protocol->protocol_end();
5356 P != PEnd; ++P)
5357 CollectOverriddenMethods(*P, Method, Methods);
5358 }
5359
5360 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5361 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5362 PEnd = Category->protocol_end();
5363 P != PEnd; ++P)
5364 CollectOverriddenMethods(*P, Method, Methods);
5365 }
5366
5367 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5368 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5369 PEnd = Interface->protocol_end();
5370 P != PEnd; ++P)
5371 CollectOverriddenMethods(*P, Method, Methods);
5372
5373 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5374 Category; Category = Category->getNextClassCategory())
5375 CollectOverriddenMethods(Category, Method, Methods);
5376
5377 // We only look into the superclass if we haven't found anything yet.
5378 if (Methods.empty())
5379 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5380 return CollectOverriddenMethods(Super, Method, Methods);
5381 }
5382}
5383
5384void clang_getOverriddenCursors(CXCursor cursor,
5385 CXCursor **overridden,
5386 unsigned *num_overridden) {
5387 if (overridden)
5388 *overridden = 0;
5389 if (num_overridden)
5390 *num_overridden = 0;
5391 if (!overridden || !num_overridden)
5392 return;
5393
5394 if (!clang_isDeclaration(cursor.kind))
5395 return;
5396
5397 Decl *D = getCursorDecl(cursor);
5398 if (!D)
5399 return;
5400
5401 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005402 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005403 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5404 *num_overridden = CXXMethod->size_overridden_methods();
5405 if (!*num_overridden)
5406 return;
5407
5408 *overridden = new CXCursor [*num_overridden];
5409 unsigned I = 0;
5410 for (CXXMethodDecl::method_iterator
5411 M = CXXMethod->begin_overridden_methods(),
5412 MEnd = CXXMethod->end_overridden_methods();
5413 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005414 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005415 return;
5416 }
5417
5418 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5419 if (!Method)
5420 return;
5421
5422 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005423 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005424 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5425
5426 if (Methods.empty())
5427 return;
5428
5429 *num_overridden = Methods.size();
5430 *overridden = new CXCursor [Methods.size()];
5431 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005432 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005433}
5434
5435void clang_disposeOverriddenCursors(CXCursor *overridden) {
5436 delete [] overridden;
5437}
5438
Douglas Gregorecdcb882010-10-20 22:00:55 +00005439CXFile clang_getIncludedFile(CXCursor cursor) {
5440 if (cursor.kind != CXCursor_InclusionDirective)
5441 return 0;
5442
5443 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5444 return (void *)ID->getFile();
5445}
5446
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005447} // end: extern "C"
5448
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005449
5450//===----------------------------------------------------------------------===//
5451// C++ AST instrospection.
5452//===----------------------------------------------------------------------===//
5453
5454extern "C" {
5455unsigned clang_CXXMethod_isStatic(CXCursor C) {
5456 if (!clang_isDeclaration(C.kind))
5457 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005458
5459 CXXMethodDecl *Method = 0;
5460 Decl *D = cxcursor::getCursorDecl(C);
5461 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5462 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5463 else
5464 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5465 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005466}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005467
Douglas Gregor211924b2011-05-12 15:17:24 +00005468unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5469 if (!clang_isDeclaration(C.kind))
5470 return 0;
5471
5472 CXXMethodDecl *Method = 0;
5473 Decl *D = cxcursor::getCursorDecl(C);
5474 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5475 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5476 else
5477 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5478 return (Method && Method->isVirtual()) ? 1 : 0;
5479}
5480
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005481} // end: extern "C"
5482
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005483//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005484// Attribute introspection.
5485//===----------------------------------------------------------------------===//
5486
5487extern "C" {
5488CXType clang_getIBOutletCollectionType(CXCursor C) {
5489 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005490 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005491
5492 IBOutletCollectionAttr *A =
5493 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5494
Douglas Gregor841b2382011-03-06 18:55:32 +00005495 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005496}
5497} // end: extern "C"
5498
5499//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005500// Inspecting memory usage.
5501//===----------------------------------------------------------------------===//
5502
Ted Kremenekf7870022011-04-20 16:41:07 +00005503typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005504
Ted Kremenekf7870022011-04-20 16:41:07 +00005505static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5506 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005507 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005508 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005509 entries.push_back(entry);
5510}
5511
5512extern "C" {
5513
Ted Kremenekf7870022011-04-20 16:41:07 +00005514const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005515 const char *str = "";
5516 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005517 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005518 str = "ASTContext: expressions, declarations, and types";
5519 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005520 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005521 str = "ASTContext: identifiers";
5522 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005523 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005524 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005525 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005526 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005527 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005528 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005529 case CXTUResourceUsage_SourceManagerContentCache:
5530 str = "SourceManager: content cache allocator";
5531 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005532 case CXTUResourceUsage_AST_SideTables:
5533 str = "ASTContext: side tables";
5534 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005535 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5536 str = "SourceManager: malloc'ed memory buffers";
5537 break;
5538 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5539 str = "SourceManager: mmap'ed memory buffers";
5540 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005541 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5542 str = "ExternalASTSource: malloc'ed memory buffers";
5543 break;
5544 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5545 str = "ExternalASTSource: mmap'ed memory buffers";
5546 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005547 case CXTUResourceUsage_Preprocessor:
5548 str = "Preprocessor: malloc'ed memory";
5549 break;
5550 case CXTUResourceUsage_PreprocessingRecord:
5551 str = "Preprocessor: PreprocessingRecord";
5552 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005553 case CXTUResourceUsage_SourceManager_DataStructures:
5554 str = "SourceManager: data structures and tables";
5555 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005556 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5557 str = "Preprocessor: header search tables";
5558 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005559 }
5560 return str;
5561}
5562
Ted Kremenekf7870022011-04-20 16:41:07 +00005563CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005564 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005565 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005566 return usage;
5567 }
5568
5569 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5570 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5571 ASTContext &astContext = astUnit->getASTContext();
5572
5573 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005574 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005575 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005576
5577 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005578 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005579 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5580
5581 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005582 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005583 (unsigned long) astContext.Selectors.getTotalMemory());
5584
Ted Kremenekba29bd22011-04-28 04:53:38 +00005585 // How much memory is used by ASTContext's side tables?
5586 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5587 (unsigned long) astContext.getSideTableAllocatedMemory());
5588
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005589 // How much memory is used for caching global code completion results?
5590 unsigned long completionBytes = 0;
5591 if (GlobalCodeCompletionAllocator *completionAllocator =
5592 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005593 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005594 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005595 createCXTUResourceUsageEntry(*entries,
5596 CXTUResourceUsage_GlobalCompletionResults,
5597 completionBytes);
5598
5599 // How much memory is being used by SourceManager's content cache?
5600 createCXTUResourceUsageEntry(*entries,
5601 CXTUResourceUsage_SourceManagerContentCache,
5602 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005603
5604 // How much memory is being used by the MemoryBuffer's in SourceManager?
5605 const SourceManager::MemoryBufferSizes &srcBufs =
5606 astUnit->getSourceManager().getMemoryBufferSizes();
5607
5608 createCXTUResourceUsageEntry(*entries,
5609 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5610 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005611 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005612 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5613 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005614 createCXTUResourceUsageEntry(*entries,
5615 CXTUResourceUsage_SourceManager_DataStructures,
5616 (unsigned long) astContext.getSourceManager()
5617 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005618
5619 // How much memory is being used by the ExternalASTSource?
5620 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5621 const ExternalASTSource::MemoryBufferSizes &sizes =
5622 esrc->getMemoryBufferSizes();
5623
5624 createCXTUResourceUsageEntry(*entries,
5625 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5626 (unsigned long) sizes.malloc_bytes);
5627 createCXTUResourceUsageEntry(*entries,
5628 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5629 (unsigned long) sizes.mmap_bytes);
5630 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005631
5632 // How much memory is being used by the Preprocessor?
5633 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005634 createCXTUResourceUsageEntry(*entries,
5635 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005636 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005637
5638 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5639 createCXTUResourceUsageEntry(*entries,
5640 CXTUResourceUsage_PreprocessingRecord,
5641 pRec->getTotalMemory());
5642 }
5643
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005644 createCXTUResourceUsageEntry(*entries,
5645 CXTUResourceUsage_Preprocessor_HeaderSearch,
5646 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005647
Ted Kremenekf7870022011-04-20 16:41:07 +00005648 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005649 (unsigned) entries->size(),
5650 entries->size() ? &(*entries)[0] : 0 };
5651 entries.take();
5652 return usage;
5653}
5654
Ted Kremenekf7870022011-04-20 16:41:07 +00005655void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005656 if (usage.data)
5657 delete (MemUsageEntries*) usage.data;
5658}
5659
5660} // end extern "C"
5661
Douglas Gregor6df78732011-05-05 20:27:22 +00005662void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5663 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5664 for (unsigned I = 0; I != Usage.numEntries; ++I)
5665 fprintf(stderr, " %s: %lu\n",
5666 clang_getTUResourceUsageName(Usage.entries[I].kind),
5667 Usage.entries[I].amount);
5668
5669 clang_disposeCXTUResourceUsage(Usage);
5670}
5671
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005672//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005673// Misc. utility functions.
5674//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005675
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005676/// Default to using an 8 MB stack size on "safety" threads.
5677static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005678
5679namespace clang {
5680
5681bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005682 void (*Fn)(void*), void *UserData,
5683 unsigned Size) {
5684 if (!Size)
5685 Size = GetSafetyThreadStackSize();
5686 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005687 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5688 return CRC.RunSafely(Fn, UserData);
5689}
5690
5691unsigned GetSafetyThreadStackSize() {
5692 return SafetyStackThreadSize;
5693}
5694
5695void SetSafetyThreadStackSize(unsigned Value) {
5696 SafetyStackThreadSize = Value;
5697}
5698
5699}
5700
Ted Kremenek04bb7162010-01-22 22:44:15 +00005701extern "C" {
5702
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005703CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005704 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005705}
5706
5707} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005708