blob: 274a6c4aac12e00d4e69ccc7588b5a8f84e46fdc [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) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001103 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1104 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001105 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001106 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001107}
1108
Douglas Gregora4ffd852010-11-17 01:03:52 +00001109bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1110 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1111 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1112
1113 return false;
1114}
1115
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001116bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1117 return VisitDeclContext(D);
1118}
1119
Douglas Gregor69319002010-08-31 23:48:11 +00001120bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001122 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1123 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001124 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001125
1126 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1127 D->getTargetNameLoc(), TU));
1128}
1129
Douglas Gregor7e242562010-09-01 19:52:22 +00001130bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001131 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001132 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1133 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001134 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001135 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001136
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001137 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1138 return true;
1139
Douglas Gregor7e242562010-09-01 19:52:22 +00001140 return VisitDeclarationNameInfo(D->getNameInfo());
1141}
1142
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001143bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001144 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001145 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1146 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001147 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001148
1149 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1150 D->getIdentLocation(), TU));
1151}
1152
Douglas Gregor7e242562010-09-01 19:52:22 +00001153bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001154 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001155 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1156 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001157 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001158 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001159
Douglas Gregor7e242562010-09-01 19:52:22 +00001160 return VisitDeclarationNameInfo(D->getNameInfo());
1161}
1162
1163bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1164 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001165 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001166 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1167 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001168 return true;
1169
Douglas Gregor7e242562010-09-01 19:52:22 +00001170 return false;
1171}
1172
Douglas Gregor01829d32010-08-31 14:41:23 +00001173bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1174 switch (Name.getName().getNameKind()) {
1175 case clang::DeclarationName::Identifier:
1176 case clang::DeclarationName::CXXLiteralOperatorName:
1177 case clang::DeclarationName::CXXOperatorName:
1178 case clang::DeclarationName::CXXUsingDirective:
1179 return false;
1180
1181 case clang::DeclarationName::CXXConstructorName:
1182 case clang::DeclarationName::CXXDestructorName:
1183 case clang::DeclarationName::CXXConversionFunctionName:
1184 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1185 return Visit(TSInfo->getTypeLoc());
1186 return false;
1187
1188 case clang::DeclarationName::ObjCZeroArgSelector:
1189 case clang::DeclarationName::ObjCOneArgSelector:
1190 case clang::DeclarationName::ObjCMultiArgSelector:
1191 // FIXME: Per-identifier location info?
1192 return false;
1193 }
1194
1195 return false;
1196}
1197
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001198bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1199 SourceRange Range) {
1200 // FIXME: This whole routine is a hack to work around the lack of proper
1201 // source information in nested-name-specifiers (PR5791). Since we do have
1202 // a beginning source location, we can visit the first component of the
1203 // nested-name-specifier, if it's a single-token component.
1204 if (!NNS)
1205 return false;
1206
1207 // Get the first component in the nested-name-specifier.
1208 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1209 NNS = Prefix;
1210
1211 switch (NNS->getKind()) {
1212 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001213 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1214 TU));
1215
Douglas Gregor14aba762011-02-24 02:36:08 +00001216 case NestedNameSpecifier::NamespaceAlias:
1217 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1218 Range.getBegin(), TU));
1219
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001220 case NestedNameSpecifier::TypeSpec: {
1221 // If the type has a form where we know that the beginning of the source
1222 // range matches up with a reference cursor. Visit the appropriate reference
1223 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001224 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001225 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1226 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1227 if (const TagType *Tag = dyn_cast<TagType>(T))
1228 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1229 if (const TemplateSpecializationType *TST
1230 = dyn_cast<TemplateSpecializationType>(T))
1231 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1232 break;
1233 }
1234
1235 case NestedNameSpecifier::TypeSpecWithTemplate:
1236 case NestedNameSpecifier::Global:
1237 case NestedNameSpecifier::Identifier:
1238 break;
1239 }
1240
1241 return false;
1242}
1243
Douglas Gregordc355712011-02-25 00:36:19 +00001244bool
1245CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001246 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001247 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1248 Qualifiers.push_back(Qualifier);
1249
1250 while (!Qualifiers.empty()) {
1251 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1252 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1253 switch (NNS->getKind()) {
1254 case NestedNameSpecifier::Namespace:
1255 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001256 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001257 TU)))
1258 return true;
1259
1260 break;
1261
1262 case NestedNameSpecifier::NamespaceAlias:
1263 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001264 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001265 TU)))
1266 return true;
1267
1268 break;
1269
1270 case NestedNameSpecifier::TypeSpec:
1271 case NestedNameSpecifier::TypeSpecWithTemplate:
1272 if (Visit(Q.getTypeLoc()))
1273 return true;
1274
1275 break;
1276
1277 case NestedNameSpecifier::Global:
1278 case NestedNameSpecifier::Identifier:
1279 break;
1280 }
1281 }
1282
1283 return false;
1284}
1285
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001286bool CursorVisitor::VisitTemplateParameters(
1287 const TemplateParameterList *Params) {
1288 if (!Params)
1289 return false;
1290
1291 for (TemplateParameterList::const_iterator P = Params->begin(),
1292 PEnd = Params->end();
1293 P != PEnd; ++P) {
1294 if (Visit(MakeCXCursor(*P, TU)))
1295 return true;
1296 }
1297
1298 return false;
1299}
1300
Douglas Gregor0b36e612010-08-31 20:37:03 +00001301bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1302 switch (Name.getKind()) {
1303 case TemplateName::Template:
1304 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1305
1306 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001307 // Visit the overloaded template set.
1308 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1309 return true;
1310
Douglas Gregor0b36e612010-08-31 20:37:03 +00001311 return false;
1312
1313 case TemplateName::DependentTemplate:
1314 // FIXME: Visit nested-name-specifier.
1315 return false;
1316
1317 case TemplateName::QualifiedTemplate:
1318 // FIXME: Visit nested-name-specifier.
1319 return Visit(MakeCursorTemplateRef(
1320 Name.getAsQualifiedTemplateName()->getDecl(),
1321 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001322
1323 case TemplateName::SubstTemplateTemplateParm:
1324 return Visit(MakeCursorTemplateRef(
1325 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1326 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001327
1328 case TemplateName::SubstTemplateTemplateParmPack:
1329 return Visit(MakeCursorTemplateRef(
1330 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1331 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001332 }
1333
1334 return false;
1335}
1336
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001337bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1338 switch (TAL.getArgument().getKind()) {
1339 case TemplateArgument::Null:
1340 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001341 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001342 return false;
1343
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001344 case TemplateArgument::Type:
1345 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1346 return Visit(TSInfo->getTypeLoc());
1347 return false;
1348
1349 case TemplateArgument::Declaration:
1350 if (Expr *E = TAL.getSourceDeclExpression())
1351 return Visit(MakeCXCursor(E, StmtParent, TU));
1352 return false;
1353
1354 case TemplateArgument::Expression:
1355 if (Expr *E = TAL.getSourceExpression())
1356 return Visit(MakeCXCursor(E, StmtParent, TU));
1357 return false;
1358
1359 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001360 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001361 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1362 return true;
1363
Douglas Gregora7fc9012011-01-05 18:58:31 +00001364 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001365 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001366 }
1367
1368 return false;
1369}
1370
Ted Kremeneka0536d82010-05-07 01:04:29 +00001371bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1372 return VisitDeclContext(D);
1373}
1374
Douglas Gregor01829d32010-08-31 14:41:23 +00001375bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1376 return Visit(TL.getUnqualifiedLoc());
1377}
1378
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001379bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001380 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381
1382 // Some builtin types (such as Objective-C's "id", "sel", and
1383 // "Class") have associated declarations. Create cursors for those.
1384 QualType VisitType;
1385 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001386 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001388 case BuiltinType::Char_U:
1389 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390 case BuiltinType::Char16:
1391 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001392 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393 case BuiltinType::UInt:
1394 case BuiltinType::ULong:
1395 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001396 case BuiltinType::UInt128:
1397 case BuiltinType::Char_S:
1398 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001399 case BuiltinType::WChar_U:
1400 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001401 case BuiltinType::Short:
1402 case BuiltinType::Int:
1403 case BuiltinType::Long:
1404 case BuiltinType::LongLong:
1405 case BuiltinType::Int128:
1406 case BuiltinType::Float:
1407 case BuiltinType::Double:
1408 case BuiltinType::LongDouble:
1409 case BuiltinType::NullPtr:
1410 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001411 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001412 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001413 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001414 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001415
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001416 case BuiltinType::ObjCId:
1417 VisitType = Context.getObjCIdType();
1418 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001419
1420 case BuiltinType::ObjCClass:
1421 VisitType = Context.getObjCClassType();
1422 break;
1423
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001424 case BuiltinType::ObjCSel:
1425 VisitType = Context.getObjCSelType();
1426 break;
1427 }
1428
1429 if (!VisitType.isNull()) {
1430 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001431 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001432 TU));
1433 }
1434
1435 return false;
1436}
1437
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001438bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001439 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001440}
1441
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001442bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1443 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1444}
1445
1446bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001447 if (TL.isDefinition())
1448 return Visit(MakeCXCursor(TL.getDecl(), TU));
1449
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001450 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1451}
1452
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001453bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001454 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001455}
1456
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001457bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1458 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1459 return true;
1460
John McCallc12c5bb2010-05-15 11:32:37 +00001461 return false;
1462}
1463
1464bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1465 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1466 return true;
1467
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001468 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1469 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1470 TU)))
1471 return true;
1472 }
1473
1474 return false;
1475}
1476
1477bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001478 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001479}
1480
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001481bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1482 return Visit(TL.getInnerLoc());
1483}
1484
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001485bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1486 return Visit(TL.getPointeeLoc());
1487}
1488
1489bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1490 return Visit(TL.getPointeeLoc());
1491}
1492
1493bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1494 return Visit(TL.getPointeeLoc());
1495}
1496
1497bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001498 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001499}
1500
1501bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001502 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001503}
1504
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001505bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1506 return Visit(TL.getModifiedLoc());
1507}
1508
Douglas Gregor01829d32010-08-31 14:41:23 +00001509bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1510 bool SkipResultType) {
1511 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001512 return true;
1513
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001514 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001515 if (Decl *D = TL.getArg(I))
1516 if (Visit(MakeCXCursor(D, TU)))
1517 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001518
1519 return false;
1520}
1521
1522bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1523 if (Visit(TL.getElementLoc()))
1524 return true;
1525
1526 if (Expr *Size = TL.getSizeExpr())
1527 return Visit(MakeCXCursor(Size, StmtParent, TU));
1528
1529 return false;
1530}
1531
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001532bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1533 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001534 // Visit the template name.
1535 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1536 TL.getTemplateNameLoc()))
1537 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001538
1539 // Visit the template arguments.
1540 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1541 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1542 return true;
1543
1544 return false;
1545}
1546
Douglas Gregor2332c112010-01-21 20:48:56 +00001547bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1548 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1549}
1550
1551bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1552 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1553 return Visit(TSInfo->getTypeLoc());
1554
1555 return false;
1556}
1557
Sean Huntca63c202011-05-24 22:41:36 +00001558bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1559 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1560 return Visit(TSInfo->getTypeLoc());
1561
1562 return false;
1563}
1564
Douglas Gregor2494dd02011-03-01 01:34:45 +00001565bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1566 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1567 return true;
1568
1569 return false;
1570}
1571
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001572bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1573 DependentTemplateSpecializationTypeLoc TL) {
1574 // Visit the nested-name-specifier, if there is one.
1575 if (TL.getQualifierLoc() &&
1576 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1577 return true;
1578
1579 // Visit the template arguments.
1580 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1581 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1582 return true;
1583
1584 return false;
1585}
1586
Douglas Gregor9e876872011-03-01 18:12:44 +00001587bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1588 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1589 return true;
1590
1591 return Visit(TL.getNamedTypeLoc());
1592}
1593
Douglas Gregor7536dd52010-12-20 02:24:11 +00001594bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1595 return Visit(TL.getPatternLoc());
1596}
1597
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001598bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1599 if (Expr *E = TL.getUnderlyingExpr())
1600 return Visit(MakeCXCursor(E, StmtParent, TU));
1601
1602 return false;
1603}
1604
1605bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1606 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1607}
1608
1609#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1610bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1611 return Visit##PARENT##Loc(TL); \
1612}
1613
1614DEFAULT_TYPELOC_IMPL(Complex, Type)
1615DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1616DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1617DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1618DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1619DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1620DEFAULT_TYPELOC_IMPL(Vector, Type)
1621DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1622DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1623DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1624DEFAULT_TYPELOC_IMPL(Record, TagType)
1625DEFAULT_TYPELOC_IMPL(Enum, TagType)
1626DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1627DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1628DEFAULT_TYPELOC_IMPL(Auto, Type)
1629
Ted Kremenek3064ef92010-08-27 21:34:58 +00001630bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001631 // Visit the nested-name-specifier, if present.
1632 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1633 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1634 return true;
1635
Ted Kremenek3064ef92010-08-27 21:34:58 +00001636 if (D->isDefinition()) {
1637 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1638 E = D->bases_end(); I != E; ++I) {
1639 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1640 return true;
1641 }
1642 }
1643
1644 return VisitTagDecl(D);
1645}
1646
Ted Kremenek09dfa372010-02-18 05:46:33 +00001647bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001648 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1649 i != e; ++i)
1650 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001651 return true;
1652
1653 return false;
1654}
1655
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001656//===----------------------------------------------------------------------===//
1657// Data-recursive visitor methods.
1658//===----------------------------------------------------------------------===//
1659
Ted Kremenek28a71942010-11-13 00:36:47 +00001660namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001661#define DEF_JOB(NAME, DATA, KIND)\
1662class NAME : public VisitorJob {\
1663public:\
1664 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1665 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001666 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001667};
1668
1669DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1670DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001671DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001672DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001673DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1674 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001675DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001676#undef DEF_JOB
1677
1678class DeclVisit : public VisitorJob {
1679public:
1680 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1681 VisitorJob(parent, VisitorJob::DeclVisitKind,
1682 d, isFirst ? (void*) 1 : (void*) 0) {}
1683 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001684 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001685 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001686 Decl *get() const { return static_cast<Decl*>(data[0]); }
1687 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001688};
Ted Kremenek035dc412010-11-13 00:36:50 +00001689class TypeLocVisit : public VisitorJob {
1690public:
1691 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1692 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1693 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1694
1695 static bool classof(const VisitorJob *VJ) {
1696 return VJ->getKind() == TypeLocVisitKind;
1697 }
1698
Ted Kremenek82f3c502010-11-15 22:23:26 +00001699 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001700 QualType T = QualType::getFromOpaquePtr(data[0]);
1701 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001702 }
1703};
1704
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001705class LabelRefVisit : public VisitorJob {
1706public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001707 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1708 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001709 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001710
1711 static bool classof(const VisitorJob *VJ) {
1712 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1713 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001714 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001715 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001716 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001717};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001718
1719class NestedNameSpecifierLocVisit : public VisitorJob {
1720public:
1721 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1722 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1723 Qualifier.getNestedNameSpecifier(),
1724 Qualifier.getOpaqueData()) { }
1725
1726 static bool classof(const VisitorJob *VJ) {
1727 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1728 }
1729
1730 NestedNameSpecifierLoc get() const {
1731 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1732 data[1]);
1733 }
1734};
1735
Ted Kremenekf64d8032010-11-18 00:02:32 +00001736class DeclarationNameInfoVisit : public VisitorJob {
1737public:
1738 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1739 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1740 static bool classof(const VisitorJob *VJ) {
1741 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1742 }
1743 DeclarationNameInfo get() const {
1744 Stmt *S = static_cast<Stmt*>(data[0]);
1745 switch (S->getStmtClass()) {
1746 default:
1747 llvm_unreachable("Unhandled Stmt");
1748 case Stmt::CXXDependentScopeMemberExprClass:
1749 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1750 case Stmt::DependentScopeDeclRefExprClass:
1751 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1752 }
1753 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001754};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001755class MemberRefVisit : public VisitorJob {
1756public:
1757 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1758 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001759 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001760 static bool classof(const VisitorJob *VJ) {
1761 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1762 }
1763 FieldDecl *get() const {
1764 return static_cast<FieldDecl*>(data[0]);
1765 }
1766 SourceLocation getLoc() const {
1767 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1768 }
1769};
Ted Kremenek28a71942010-11-13 00:36:47 +00001770class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1771 VisitorWorkList &WL;
1772 CXCursor Parent;
1773public:
1774 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1775 : WL(wl), Parent(parent) {}
1776
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001777 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001778 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001779 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001780 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001781 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001782 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001783 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001784 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001785 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001786 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001787 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001788 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001789 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001790 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001791 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001792 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001793 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001794 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001795 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1796 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001797 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001798 void VisitIfStmt(IfStmt *If);
1799 void VisitInitListExpr(InitListExpr *IE);
1800 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001801 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001802 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001803 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1804 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001805 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001806 void VisitStmt(Stmt *S);
1807 void VisitSwitchStmt(SwitchStmt *S);
1808 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001809 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001810 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001811 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001812 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001813 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001814 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001815 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001816
Ted Kremenek28a71942010-11-13 00:36:47 +00001817private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001818 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001819 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001820 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001821 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001822 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001823 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001824 void AddTypeLoc(TypeSourceInfo *TI);
1825 void EnqueueChildren(Stmt *S);
1826};
1827} // end anonyous namespace
1828
Ted Kremenekf64d8032010-11-18 00:02:32 +00001829void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1830 // 'S' should always be non-null, since it comes from the
1831 // statement we are visiting.
1832 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1833}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001834
1835void
1836EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1837 if (Qualifier)
1838 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1839}
1840
Ted Kremenek28a71942010-11-13 00:36:47 +00001841void EnqueueVisitor::AddStmt(Stmt *S) {
1842 if (S)
1843 WL.push_back(StmtVisit(S, Parent));
1844}
Ted Kremenek035dc412010-11-13 00:36:50 +00001845void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001846 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001847 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001848}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001849void EnqueueVisitor::
1850 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1851 if (A)
1852 WL.push_back(ExplicitTemplateArgsVisit(
1853 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1854}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001855void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1856 if (D)
1857 WL.push_back(MemberRefVisit(D, L, Parent));
1858}
Ted Kremenek28a71942010-11-13 00:36:47 +00001859void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1860 if (TI)
1861 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1862 }
1863void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001864 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001865 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001866 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001867 }
1868 if (size == WL.size())
1869 return;
1870 // Now reverse the entries we just added. This will match the DFS
1871 // ordering performed by the worklist.
1872 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1873 std::reverse(I, E);
1874}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001875void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1876 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1877}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001878void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1879 AddDecl(B->getBlockDecl());
1880}
Ted Kremenek28a71942010-11-13 00:36:47 +00001881void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1882 EnqueueChildren(E);
1883 AddTypeLoc(E->getTypeSourceInfo());
1884}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001885void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1886 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1887 E = S->body_rend(); I != E; ++I) {
1888 AddStmt(*I);
1889 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001890}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001891void EnqueueVisitor::
1892VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1893 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1894 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001895 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1896 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001897 if (!E->isImplicitAccess())
1898 AddStmt(E->getBase());
1899}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001900void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1901 // Enqueue the initializer or constructor arguments.
1902 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1903 AddStmt(E->getConstructorArg(I-1));
1904 // Enqueue the array size, if any.
1905 AddStmt(E->getArraySize());
1906 // Enqueue the allocated type.
1907 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1908 // Enqueue the placement arguments.
1909 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1910 AddStmt(E->getPlacementArg(I-1));
1911}
Ted Kremenek28a71942010-11-13 00:36:47 +00001912void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001913 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1914 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001915 AddStmt(CE->getCallee());
1916 AddStmt(CE->getArg(0));
1917}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001918void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1919 // Visit the name of the type being destroyed.
1920 AddTypeLoc(E->getDestroyedTypeInfo());
1921 // Visit the scope type that looks disturbingly like the nested-name-specifier
1922 // but isn't.
1923 AddTypeLoc(E->getScopeTypeInfo());
1924 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001925 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1926 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001927 // Visit base expression.
1928 AddStmt(E->getBase());
1929}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001930void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1931 AddTypeLoc(E->getTypeSourceInfo());
1932}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001933void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1934 EnqueueChildren(E);
1935 AddTypeLoc(E->getTypeSourceInfo());
1936}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001937void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1938 EnqueueChildren(E);
1939 if (E->isTypeOperand())
1940 AddTypeLoc(E->getTypeOperandSourceInfo());
1941}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001942
1943void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1944 *E) {
1945 EnqueueChildren(E);
1946 AddTypeLoc(E->getTypeSourceInfo());
1947}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001948void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1949 EnqueueChildren(E);
1950 if (E->isTypeOperand())
1951 AddTypeLoc(E->getTypeOperandSourceInfo());
1952}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001953void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001954 if (DR->hasExplicitTemplateArgs()) {
1955 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1956 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001957 WL.push_back(DeclRefExprParts(DR, Parent));
1958}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001959void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1960 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1961 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001962 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001963}
Ted Kremenek035dc412010-11-13 00:36:50 +00001964void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1965 unsigned size = WL.size();
1966 bool isFirst = true;
1967 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1968 D != DEnd; ++D) {
1969 AddDecl(*D, isFirst);
1970 isFirst = false;
1971 }
1972 if (size == WL.size())
1973 return;
1974 // Now reverse the entries we just added. This will match the DFS
1975 // ordering performed by the worklist.
1976 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1977 std::reverse(I, E);
1978}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001979void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1980 AddStmt(E->getInit());
1981 typedef DesignatedInitExpr::Designator Designator;
1982 for (DesignatedInitExpr::reverse_designators_iterator
1983 D = E->designators_rbegin(), DEnd = E->designators_rend();
1984 D != DEnd; ++D) {
1985 if (D->isFieldDesignator()) {
1986 if (FieldDecl *Field = D->getField())
1987 AddMemberRef(Field, D->getFieldLoc());
1988 continue;
1989 }
1990 if (D->isArrayDesignator()) {
1991 AddStmt(E->getArrayIndex(*D));
1992 continue;
1993 }
1994 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1995 AddStmt(E->getArrayRangeEnd(*D));
1996 AddStmt(E->getArrayRangeStart(*D));
1997 }
1998}
Ted Kremenek28a71942010-11-13 00:36:47 +00001999void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
2000 EnqueueChildren(E);
2001 AddTypeLoc(E->getTypeInfoAsWritten());
2002}
2003void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2004 AddStmt(FS->getBody());
2005 AddStmt(FS->getInc());
2006 AddStmt(FS->getCond());
2007 AddDecl(FS->getConditionVariable());
2008 AddStmt(FS->getInit());
2009}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002010void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2011 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2012}
Ted Kremenek28a71942010-11-13 00:36:47 +00002013void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2014 AddStmt(If->getElse());
2015 AddStmt(If->getThen());
2016 AddStmt(If->getCond());
2017 AddDecl(If->getConditionVariable());
2018}
2019void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2020 // We care about the syntactic form of the initializer list, only.
2021 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2022 IE = Syntactic;
2023 EnqueueChildren(IE);
2024}
2025void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00002026 WL.push_back(MemberExprParts(M, Parent));
2027
2028 // If the base of the member access expression is an implicit 'this', don't
2029 // visit it.
2030 // FIXME: If we ever want to show these implicit accesses, this will be
2031 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00002032 if (!M->isImplicitAccess())
2033 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00002034}
Ted Kremenek73d15c42010-11-13 01:09:29 +00002035void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2036 AddTypeLoc(E->getEncodedTypeSourceInfo());
2037}
Ted Kremenek28a71942010-11-13 00:36:47 +00002038void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2039 EnqueueChildren(M);
2040 AddTypeLoc(M->getClassReceiverTypeInfo());
2041}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002042void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2043 // Visit the components of the offsetof expression.
2044 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2045 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2046 const OffsetOfNode &Node = E->getComponent(I-1);
2047 switch (Node.getKind()) {
2048 case OffsetOfNode::Array:
2049 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2050 break;
2051 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002052 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002053 break;
2054 case OffsetOfNode::Identifier:
2055 case OffsetOfNode::Base:
2056 continue;
2057 }
2058 }
2059 // Visit the type into which we're computing the offset.
2060 AddTypeLoc(E->getTypeSourceInfo());
2061}
Ted Kremenek28a71942010-11-13 00:36:47 +00002062void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002063 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002064 WL.push_back(OverloadExprParts(E, Parent));
2065}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002066void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2067 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002068 EnqueueChildren(E);
2069 if (E->isArgumentType())
2070 AddTypeLoc(E->getArgumentTypeInfo());
2071}
Ted Kremenek28a71942010-11-13 00:36:47 +00002072void EnqueueVisitor::VisitStmt(Stmt *S) {
2073 EnqueueChildren(S);
2074}
2075void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2076 AddStmt(S->getBody());
2077 AddStmt(S->getCond());
2078 AddDecl(S->getConditionVariable());
2079}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002080
Ted Kremenek28a71942010-11-13 00:36:47 +00002081void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2082 AddStmt(W->getBody());
2083 AddStmt(W->getCond());
2084 AddDecl(W->getConditionVariable());
2085}
John Wiegley21ff2e52011-04-28 00:16:57 +00002086
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002087void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2088 AddTypeLoc(E->getQueriedTypeSourceInfo());
2089}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002090
2091void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002092 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002093 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002094}
2095
John Wiegley21ff2e52011-04-28 00:16:57 +00002096void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2097 AddTypeLoc(E->getQueriedTypeSourceInfo());
2098}
2099
John Wiegley55262202011-04-25 06:54:41 +00002100void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2101 EnqueueChildren(E);
2102}
2103
Ted Kremenek28a71942010-11-13 00:36:47 +00002104void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2105 VisitOverloadExpr(U);
2106 if (!U->isImplicitAccess())
2107 AddStmt(U->getBase());
2108}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002109void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2110 AddStmt(E->getSubExpr());
2111 AddTypeLoc(E->getWrittenTypeInfo());
2112}
Douglas Gregor94d96292011-01-19 20:34:17 +00002113void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2114 WL.push_back(SizeOfPackExprParts(E, Parent));
2115}
Ted Kremenek60458782010-11-12 21:34:16 +00002116
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002117void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002118 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002119}
2120
2121bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2122 if (RegionOfInterest.isValid()) {
2123 SourceRange Range = getRawCursorExtent(C);
2124 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2125 return false;
2126 }
2127 return true;
2128}
2129
2130bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2131 while (!WL.empty()) {
2132 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002133 VisitorJob LI = WL.back();
2134 WL.pop_back();
2135
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002136 // Set the Parent field, then back to its old value once we're done.
2137 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2138
2139 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002140 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002141 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002142 if (!D)
2143 continue;
2144
2145 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002146 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002147 return true;
2148
2149 continue;
2150 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002151 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2152 const ExplicitTemplateArgumentList *ArgList =
2153 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2154 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2155 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2156 Arg != ArgEnd; ++Arg) {
2157 if (VisitTemplateArgumentLoc(*Arg))
2158 return true;
2159 }
2160 continue;
2161 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002162 case VisitorJob::TypeLocVisitKind: {
2163 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002164 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002165 return true;
2166 continue;
2167 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002168 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002169 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002170 if (LabelStmt *stmt = LS->getStmt()) {
2171 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2172 TU))) {
2173 return true;
2174 }
2175 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002176 continue;
2177 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002178
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002179 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2180 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2181 if (VisitNestedNameSpecifierLoc(V->get()))
2182 return true;
2183 continue;
2184 }
2185
Ted Kremenekf64d8032010-11-18 00:02:32 +00002186 case VisitorJob::DeclarationNameInfoVisitKind: {
2187 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2188 ->get()))
2189 return true;
2190 continue;
2191 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002192 case VisitorJob::MemberRefVisitKind: {
2193 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2194 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2195 return true;
2196 continue;
2197 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002198 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002199 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002200 if (!S)
2201 continue;
2202
Ted Kremenekf1107452010-11-12 18:26:56 +00002203 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002204 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002205 if (!IsInRegionOfInterest(Cursor))
2206 continue;
2207 switch (Visitor(Cursor, Parent, ClientData)) {
2208 case CXChildVisit_Break: return true;
2209 case CXChildVisit_Continue: break;
2210 case CXChildVisit_Recurse:
2211 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002212 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002213 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002214 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002215 }
2216 case VisitorJob::MemberExprPartsKind: {
2217 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002218 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002219
2220 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002221 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2222 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002223 return true;
2224
2225 // Visit the declaration name.
2226 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2227 return true;
2228
2229 // Visit the explicitly-specified template arguments, if any.
2230 if (M->hasExplicitTemplateArgs()) {
2231 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2232 *ArgEnd = Arg + M->getNumTemplateArgs();
2233 Arg != ArgEnd; ++Arg) {
2234 if (VisitTemplateArgumentLoc(*Arg))
2235 return true;
2236 }
2237 }
2238 continue;
2239 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002240 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002241 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002242 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002243 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2244 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002245 return true;
2246 // Visit declaration name.
2247 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2248 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002249 continue;
2250 }
Ted Kremenek60458782010-11-12 21:34:16 +00002251 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002252 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002253 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002254 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2255 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002256 return true;
2257 // Visit the declaration name.
2258 if (VisitDeclarationNameInfo(O->getNameInfo()))
2259 return true;
2260 // Visit the overloaded declaration reference.
2261 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2262 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002263 continue;
2264 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002265 case VisitorJob::SizeOfPackExprPartsKind: {
2266 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2267 NamedDecl *Pack = E->getPack();
2268 if (isa<TemplateTypeParmDecl>(Pack)) {
2269 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2270 E->getPackLoc(), TU)))
2271 return true;
2272
2273 continue;
2274 }
2275
2276 if (isa<TemplateTemplateParmDecl>(Pack)) {
2277 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2278 E->getPackLoc(), TU)))
2279 return true;
2280
2281 continue;
2282 }
2283
2284 // Non-type template parameter packs and function parameter packs are
2285 // treated like DeclRefExpr cursors.
2286 continue;
2287 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002288 }
2289 }
2290 return false;
2291}
2292
Ted Kremenekcdba6592010-11-18 00:42:18 +00002293bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002294 VisitorWorkList *WL = 0;
2295 if (!WorkListFreeList.empty()) {
2296 WL = WorkListFreeList.back();
2297 WL->clear();
2298 WorkListFreeList.pop_back();
2299 }
2300 else {
2301 WL = new VisitorWorkList();
2302 WorkListCache.push_back(WL);
2303 }
2304 EnqueueWorkList(*WL, S);
2305 bool result = RunVisitorWorkList(*WL);
2306 WorkListFreeList.push_back(WL);
2307 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002308}
2309
Francois Pichet48a8d142011-07-25 22:00:44 +00002310namespace {
2311typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2312RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2313 const DeclarationNameInfo &NI,
2314 const SourceRange &QLoc,
2315 const ExplicitTemplateArgumentList *TemplateArgs = 0){
2316 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2317 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2318 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2319
2320 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2321
2322 RefNamePieces Pieces;
2323
2324 if (WantQualifier && QLoc.isValid())
2325 Pieces.push_back(QLoc);
2326
2327 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2328 Pieces.push_back(NI.getLoc());
2329
2330 if (WantTemplateArgs && TemplateArgs)
2331 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2332 TemplateArgs->RAngleLoc));
2333
2334 if (Kind == DeclarationName::CXXOperatorName) {
2335 Pieces.push_back(SourceLocation::getFromRawEncoding(
2336 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2337 Pieces.push_back(SourceLocation::getFromRawEncoding(
2338 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2339 }
2340
2341 if (WantSinglePiece) {
2342 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2343 Pieces.clear();
2344 Pieces.push_back(R);
2345 }
2346
2347 return Pieces;
2348}
2349}
2350
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002351//===----------------------------------------------------------------------===//
2352// Misc. API hooks.
2353//===----------------------------------------------------------------------===//
2354
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002355static llvm::sys::Mutex EnableMultithreadingMutex;
2356static bool EnabledMultithreading;
2357
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002358extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002359CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2360 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002361 // Disable pretty stack trace functionality, which will otherwise be a very
2362 // poor citizen of the world and set up all sorts of signal handlers.
2363 llvm::DisablePrettyStackTrace = true;
2364
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002365 // We use crash recovery to make some of our APIs more reliable, implicitly
2366 // enable it.
2367 llvm::CrashRecoveryContext::Enable();
2368
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002369 // Enable support for multithreading in LLVM.
2370 {
2371 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2372 if (!EnabledMultithreading) {
2373 llvm::llvm_start_multithreaded();
2374 EnabledMultithreading = true;
2375 }
2376 }
2377
Douglas Gregora030b7c2010-01-22 20:35:53 +00002378 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002379 if (excludeDeclarationsFromPCH)
2380 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002381 if (displayDiagnostics)
2382 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002383 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002384}
2385
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002386void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002387 if (CIdx)
2388 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002389}
2390
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002391void clang_toggleCrashRecovery(unsigned isEnabled) {
2392 if (isEnabled)
2393 llvm::CrashRecoveryContext::Enable();
2394 else
2395 llvm::CrashRecoveryContext::Disable();
2396}
2397
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002398CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002399 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002400 if (!CIdx)
2401 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002402
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002403 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002404 FileSystemOptions FileSystemOpts;
2405 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002406
Douglas Gregor28019772010-04-05 23:52:57 +00002407 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002408 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002409 CXXIdx->getOnlyLocalDecls(),
2410 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002411 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002412}
2413
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002414unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002415 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002416 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002417}
2418
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002419CXTranslationUnit
2420clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2421 const char *source_filename,
2422 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002423 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002424 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002425 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002426 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002427 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002428 return clang_parseTranslationUnit(CIdx, source_filename,
2429 command_line_args, num_command_line_args,
2430 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002431 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002432}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002433
2434struct ParseTranslationUnitInfo {
2435 CXIndex CIdx;
2436 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002437 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002438 int num_command_line_args;
2439 struct CXUnsavedFile *unsaved_files;
2440 unsigned num_unsaved_files;
2441 unsigned options;
2442 CXTranslationUnit result;
2443};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002444static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002445 ParseTranslationUnitInfo *PTUI =
2446 static_cast<ParseTranslationUnitInfo*>(UserData);
2447 CXIndex CIdx = PTUI->CIdx;
2448 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002449 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002450 int num_command_line_args = PTUI->num_command_line_args;
2451 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2452 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2453 unsigned options = PTUI->options;
2454 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002455
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002456 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002457 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002458
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002459 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2460
Douglas Gregor44c181a2010-07-23 00:33:23 +00002461 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002462 // FIXME: Add a flag for modules.
2463 TranslationUnitKind TUKind
2464 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002465 bool CacheCodeCompetionResults
2466 = options & CXTranslationUnit_CacheCompletionResults;
2467
Douglas Gregor5352ac02010-01-28 00:27:43 +00002468 // Configure the diagnostics.
2469 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002470 llvm::IntrusiveRefCntPtr<Diagnostic>
2471 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2472 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002473
Ted Kremenek25a11e12011-03-22 01:15:24 +00002474 // Recover resources if we crash before exiting this function.
2475 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2476 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2477 DiagCleanup(Diags.getPtr());
2478
2479 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2480 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2481
2482 // Recover resources if we crash before exiting this function.
2483 llvm::CrashRecoveryContextCleanupRegistrar<
2484 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2485
Douglas Gregor4db64a42010-01-23 00:14:00 +00002486 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002487 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002488 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002489 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002490 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2491 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002492 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002493
Ted Kremenek25a11e12011-03-22 01:15:24 +00002494 llvm::OwningPtr<std::vector<const char *> >
2495 Args(new std::vector<const char*>());
2496
2497 // Recover resources if we crash before exiting this method.
2498 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2499 ArgsCleanup(Args.get());
2500
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002501 // Since the Clang C library is primarily used by batch tools dealing with
2502 // (often very broken) source code, where spell-checking can have a
2503 // significant negative impact on performance (particularly when
2504 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002505 // Only do this if we haven't found a spell-checking-related argument.
2506 bool FoundSpellCheckingArgument = false;
2507 for (int I = 0; I != num_command_line_args; ++I) {
2508 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2509 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2510 FoundSpellCheckingArgument = true;
2511 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002512 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002513 }
2514 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002515 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002516
Ted Kremenek25a11e12011-03-22 01:15:24 +00002517 Args->insert(Args->end(), command_line_args,
2518 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002519
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002520 // The 'source_filename' argument is optional. If the caller does not
2521 // specify it then it is assumed that the source file is specified
2522 // in the actual argument list.
2523 // Put the source file after command_line_args otherwise if '-x' flag is
2524 // present it will be unused.
2525 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002526 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002527
Douglas Gregor44c181a2010-07-23 00:33:23 +00002528 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002529 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002530 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002531 Args->push_back("-Xclang");
2532 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002533 NestedMacroExpansions
2534 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002535 }
2536
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002537 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002538 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002539 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2540 /* vector::data() not portable */,
2541 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002542 Diags,
2543 CXXIdx->getClangResourcesPath(),
2544 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002545 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002546 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002547 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002548 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002549 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002550 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002551 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002552 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002553
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002554 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002555 // Make sure to check that 'Unit' is non-NULL.
2556 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2557 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2558 DEnd = Unit->stored_diag_end();
2559 D != DEnd; ++D) {
2560 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2561 CXString Msg = clang_formatDiagnostic(&Diag,
2562 clang_defaultDiagnosticDisplayOptions());
2563 fprintf(stderr, "%s\n", clang_getCString(Msg));
2564 clang_disposeString(Msg);
2565 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002566#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002567 // On Windows, force a flush, since there may be multiple copies of
2568 // stderr and stdout in the file system, all with different buffers
2569 // but writing to the same device.
2570 fflush(stderr);
2571#endif
2572 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002573 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002574
Ted Kremeneka60ed472010-11-16 08:15:36 +00002575 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002576}
2577CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2578 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002579 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002580 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002581 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002582 unsigned num_unsaved_files,
2583 unsigned options) {
2584 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002585 num_command_line_args, unsaved_files,
2586 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002587 llvm::CrashRecoveryContext CRC;
2588
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002589 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002590 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2591 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2592 fprintf(stderr, " 'command_line_args' : [");
2593 for (int i = 0; i != num_command_line_args; ++i) {
2594 if (i)
2595 fprintf(stderr, ", ");
2596 fprintf(stderr, "'%s'", command_line_args[i]);
2597 }
2598 fprintf(stderr, "],\n");
2599 fprintf(stderr, " 'unsaved_files' : [");
2600 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2601 if (i)
2602 fprintf(stderr, ", ");
2603 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2604 unsaved_files[i].Length);
2605 }
2606 fprintf(stderr, "],\n");
2607 fprintf(stderr, " 'options' : %d,\n", options);
2608 fprintf(stderr, "}\n");
2609
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002610 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002611 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2612 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002613 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002614
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002615 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002616}
2617
Douglas Gregor19998442010-08-13 15:35:05 +00002618unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2619 return CXSaveTranslationUnit_None;
2620}
2621
2622int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2623 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002624 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002625 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002626
Douglas Gregor39c411f2011-07-06 16:43:36 +00002627 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002628 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2629 PrintLibclangResourceUsage(TU);
2630 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002631}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002632
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002633void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002634 if (CTUnit) {
2635 // If the translation unit has been marked as unsafe to free, just discard
2636 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002637 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002638 return;
2639
Ted Kremeneka60ed472010-11-16 08:15:36 +00002640 delete static_cast<ASTUnit *>(CTUnit->TUData);
2641 disposeCXStringPool(CTUnit->StringPool);
2642 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002643 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002644}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002645
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002646unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2647 return CXReparse_None;
2648}
2649
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002650struct ReparseTranslationUnitInfo {
2651 CXTranslationUnit TU;
2652 unsigned num_unsaved_files;
2653 struct CXUnsavedFile *unsaved_files;
2654 unsigned options;
2655 int result;
2656};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002657
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002658static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002659 ReparseTranslationUnitInfo *RTUI =
2660 static_cast<ReparseTranslationUnitInfo*>(UserData);
2661 CXTranslationUnit TU = RTUI->TU;
2662 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2663 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2664 unsigned options = RTUI->options;
2665 (void) options;
2666 RTUI->result = 1;
2667
Douglas Gregorabc563f2010-07-19 21:46:24 +00002668 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002669 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002670
Ted Kremeneka60ed472010-11-16 08:15:36 +00002671 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002672 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002673
Ted Kremenek25a11e12011-03-22 01:15:24 +00002674 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2675 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2676
2677 // Recover resources if we crash before exiting this function.
2678 llvm::CrashRecoveryContextCleanupRegistrar<
2679 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2680
Douglas Gregorabc563f2010-07-19 21:46:24 +00002681 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002682 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002683 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002684 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002685 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2686 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002687 }
2688
Ted Kremenek4ee99262011-03-22 20:16:19 +00002689 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2690 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002691 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002692}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002693
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002694int clang_reparseTranslationUnit(CXTranslationUnit TU,
2695 unsigned num_unsaved_files,
2696 struct CXUnsavedFile *unsaved_files,
2697 unsigned options) {
2698 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2699 options, 0 };
2700 llvm::CrashRecoveryContext CRC;
2701
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002702 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002703 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002704 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002705 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002706 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2707 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002708
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002709 return RTUI.result;
2710}
2711
Douglas Gregordf95a132010-08-09 20:45:32 +00002712
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002713CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002714 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002715 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002716
Ted Kremeneka60ed472010-11-16 08:15:36 +00002717 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002718 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002719}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002720
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002721CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002722 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002723 return Result;
2724}
2725
Ted Kremenekfb480492010-01-13 21:46:36 +00002726} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002727
Ted Kremenekfb480492010-01-13 21:46:36 +00002728//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002729// CXSourceLocation and CXSourceRange Operations.
2730//===----------------------------------------------------------------------===//
2731
Douglas Gregorb9790342010-01-22 21:44:22 +00002732extern "C" {
2733CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002734 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002735 return Result;
2736}
2737
2738unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002739 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2740 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2741 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002742}
2743
2744CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2745 CXFile file,
2746 unsigned line,
2747 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002748 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002749 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002750
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002751 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002752 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002753 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002754 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002755 = CXXUnit->getSourceManager().getLocation(File, line, column);
2756 if (SLoc.isInvalid()) {
2757 if (Logging)
2758 llvm::errs() << "clang_getLocation(\"" << File->getName()
2759 << "\", " << line << ", " << column << ") = invalid\n";
2760 return clang_getNullLocation();
2761 }
2762
2763 if (Logging)
2764 llvm::errs() << "clang_getLocation(\"" << File->getName()
2765 << "\", " << line << ", " << column << ") = "
2766 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002767
2768 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2769}
2770
2771CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2772 CXFile file,
2773 unsigned offset) {
2774 if (!tu || !file)
2775 return clang_getNullLocation();
2776
Ted Kremeneka60ed472010-11-16 08:15:36 +00002777 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002778 SourceLocation Start
2779 = CXXUnit->getSourceManager().getLocation(
2780 static_cast<const FileEntry *>(file),
2781 1, 1);
2782 if (Start.isInvalid()) return clang_getNullLocation();
2783
2784 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2785
2786 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002787
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002788 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002789}
2790
Douglas Gregor5352ac02010-01-28 00:27:43 +00002791CXSourceRange clang_getNullRange() {
2792 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2793 return Result;
2794}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002795
Douglas Gregor5352ac02010-01-28 00:27:43 +00002796CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2797 if (begin.ptr_data[0] != end.ptr_data[0] ||
2798 begin.ptr_data[1] != end.ptr_data[1])
2799 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002800
2801 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002802 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002803 return Result;
2804}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002805
2806unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2807{
2808 return range1.ptr_data[0] == range2.ptr_data[0]
2809 && range1.ptr_data[1] == range2.ptr_data[1]
2810 && range1.begin_int_data == range2.begin_int_data
2811 && range1.end_int_data == range2.end_int_data;
2812}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002813} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002814
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002815static void createNullLocation(CXFile *file, unsigned *line,
2816 unsigned *column, unsigned *offset) {
2817 if (file)
2818 *file = 0;
2819 if (line)
2820 *line = 0;
2821 if (column)
2822 *column = 0;
2823 if (offset)
2824 *offset = 0;
2825 return;
2826}
2827
2828extern "C" {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002829void clang_getInstantiationLocation(CXSourceLocation location,
2830 CXFile *file,
2831 unsigned *line,
2832 unsigned *column,
2833 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002834 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2835
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002836 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002837 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002838 return;
2839 }
2840
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002841 const SourceManager &SM =
2842 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth40278532011-07-25 16:49:02 +00002843 SourceLocation InstLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002844
Chandler Carruthcea731a2011-07-14 16:07:57 +00002845 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002846 // This can manifest in invalid code.
2847 FileID fileID = SM.getFileID(InstLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002848 bool Invalid = false;
2849 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2850 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002851 createNullLocation(file, line, column, offset);
2852 return;
2853 }
2854
Douglas Gregor1db19de2010-01-19 21:36:55 +00002855 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002856 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002857 if (line)
Chandler Carruth64211622011-07-25 21:09:52 +00002858 *line = SM.getExpansionLineNumber(InstLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002859 if (column)
Chandler Carrutha77c0312011-07-25 20:57:57 +00002860 *column = SM.getExpansionColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002861 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002862 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002863}
2864
Douglas Gregora9b06d42010-11-09 06:24:54 +00002865void clang_getSpellingLocation(CXSourceLocation location,
2866 CXFile *file,
2867 unsigned *line,
2868 unsigned *column,
2869 unsigned *offset) {
2870 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2871
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002872 if (!location.ptr_data[0] || Loc.isInvalid())
2873 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002874
2875 const SourceManager &SM =
2876 *static_cast<const SourceManager*>(location.ptr_data[0]);
2877 SourceLocation SpellLoc = Loc;
2878 if (SpellLoc.isMacroID()) {
2879 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2880 if (SimpleSpellingLoc.isFileID() &&
2881 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2882 SpellLoc = SimpleSpellingLoc;
2883 else
Chandler Carruth40278532011-07-25 16:49:02 +00002884 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002885 }
2886
2887 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2888 FileID FID = LocInfo.first;
2889 unsigned FileOffset = LocInfo.second;
2890
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002891 if (FID.isInvalid())
2892 return createNullLocation(file, line, column, offset);
2893
Douglas Gregora9b06d42010-11-09 06:24:54 +00002894 if (file)
2895 *file = (void *)SM.getFileEntryForID(FID);
2896 if (line)
2897 *line = SM.getLineNumber(FID, FileOffset);
2898 if (column)
2899 *column = SM.getColumnNumber(FID, FileOffset);
2900 if (offset)
2901 *offset = FileOffset;
2902}
2903
Douglas Gregor1db19de2010-01-19 21:36:55 +00002904CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002905 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002906 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002907 return Result;
2908}
2909
2910CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002911 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002912 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002913 return Result;
2914}
2915
Douglas Gregorb9790342010-01-22 21:44:22 +00002916} // end: extern "C"
2917
Douglas Gregor1db19de2010-01-19 21:36:55 +00002918//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002919// CXFile Operations.
2920//===----------------------------------------------------------------------===//
2921
2922extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002923CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002924 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002925 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002926
Steve Naroff88145032009-10-27 14:35:18 +00002927 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002928 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002929}
2930
2931time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002932 if (!SFile)
2933 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002934
Steve Naroff88145032009-10-27 14:35:18 +00002935 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2936 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002937}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002938
Douglas Gregorb9790342010-01-22 21:44:22 +00002939CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2940 if (!tu)
2941 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002942
Ted Kremeneka60ed472010-11-16 08:15:36 +00002943 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002944
Douglas Gregorb9790342010-01-22 21:44:22 +00002945 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002946 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002947}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002948
Douglas Gregordd3e5542011-05-04 00:14:37 +00002949unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2950 if (!tu || !file)
2951 return 0;
2952
2953 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2954 FileEntry *FEnt = static_cast<FileEntry *>(file);
2955 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2956 .isFileMultipleIncludeGuarded(FEnt);
2957}
2958
Ted Kremenekfb480492010-01-13 21:46:36 +00002959} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002960
Ted Kremenekfb480492010-01-13 21:46:36 +00002961//===----------------------------------------------------------------------===//
2962// CXCursor Operations.
2963//===----------------------------------------------------------------------===//
2964
Ted Kremenekfb480492010-01-13 21:46:36 +00002965static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002966 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2967 return getDeclFromExpr(CE->getSubExpr());
2968
Ted Kremenekfb480492010-01-13 21:46:36 +00002969 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2970 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002971 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2972 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002973 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2974 return ME->getMemberDecl();
2975 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2976 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002977 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002978 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002979
Ted Kremenekfb480492010-01-13 21:46:36 +00002980 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2981 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002982 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002983 if (!CE->isElidable())
2984 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002985 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2986 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002987
Douglas Gregordb1314e2010-10-01 21:11:22 +00002988 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2989 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002990 if (SubstNonTypeTemplateParmPackExpr *NTTP
2991 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2992 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002993 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2994 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2995 isa<ParmVarDecl>(SizeOfPack->getPack()))
2996 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002997
Ted Kremenekfb480492010-01-13 21:46:36 +00002998 return 0;
2999}
3000
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003001static SourceLocation getLocationFromExpr(Expr *E) {
3002 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3003 return /*FIXME:*/Msg->getLeftLoc();
3004 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3005 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003006 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3007 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003008 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3009 return Member->getMemberLoc();
3010 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3011 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003012 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3013 return SizeOfPack->getPackLoc();
3014
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003015 return E->getLocStart();
3016}
3017
Ted Kremenekfb480492010-01-13 21:46:36 +00003018extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003019
3020unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003021 CXCursorVisitor visitor,
3022 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003023 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003024 getCursorASTUnit(parent)->getMaxPCHLevel(),
3025 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003026 return CursorVis.VisitChildren(parent);
3027}
3028
David Chisnall3387c652010-11-03 14:12:26 +00003029#ifndef __has_feature
3030#define __has_feature(x) 0
3031#endif
3032#if __has_feature(blocks)
3033typedef enum CXChildVisitResult
3034 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3035
3036static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3037 CXClientData client_data) {
3038 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3039 return block(cursor, parent);
3040}
3041#else
3042// If we are compiled with a compiler that doesn't have native blocks support,
3043// define and call the block manually, so the
3044typedef struct _CXChildVisitResult
3045{
3046 void *isa;
3047 int flags;
3048 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003049 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3050 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003051} *CXCursorVisitorBlock;
3052
3053static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3054 CXClientData client_data) {
3055 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3056 return block->invoke(block, cursor, parent);
3057}
3058#endif
3059
3060
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003061unsigned clang_visitChildrenWithBlock(CXCursor parent,
3062 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003063 return clang_visitChildren(parent, visitWithBlock, block);
3064}
3065
Douglas Gregor78205d42010-01-20 21:45:58 +00003066static CXString getDeclSpelling(Decl *D) {
3067 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003068 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003069 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003070 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3071 return createCXString(Property->getIdentifier()->getName());
3072
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003073 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003074 }
3075
Douglas Gregor78205d42010-01-20 21:45:58 +00003076 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003077 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003078
Douglas Gregor78205d42010-01-20 21:45:58 +00003079 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3080 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3081 // and returns different names. NamedDecl returns the class name and
3082 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003083 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003084
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003085 if (isa<UsingDirectiveDecl>(D))
3086 return createCXString("");
3087
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003088 llvm::SmallString<1024> S;
3089 llvm::raw_svector_ostream os(S);
3090 ND->printName(os);
3091
3092 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003093}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003094
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003095CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003096 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003097 return clang_getTranslationUnitSpelling(
3098 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003099
Steve Narofff334b4e2009-09-02 18:26:48 +00003100 if (clang_isReference(C.kind)) {
3101 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003102 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003103 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003104 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003105 }
3106 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003107 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003108 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003109 }
3110 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003111 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003112 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003113 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003114 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003115 case CXCursor_CXXBaseSpecifier: {
3116 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3117 return createCXString(B->getType().getAsString());
3118 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003119 case CXCursor_TypeRef: {
3120 TypeDecl *Type = getCursorTypeRef(C).first;
3121 assert(Type && "Missing type decl");
3122
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003123 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3124 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003125 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003126 case CXCursor_TemplateRef: {
3127 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003128 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003129
3130 return createCXString(Template->getNameAsString());
3131 }
Douglas Gregor69319002010-08-31 23:48:11 +00003132
3133 case CXCursor_NamespaceRef: {
3134 NamedDecl *NS = getCursorNamespaceRef(C).first;
3135 assert(NS && "Missing namespace decl");
3136
3137 return createCXString(NS->getNameAsString());
3138 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003139
Douglas Gregora67e03f2010-09-09 21:42:20 +00003140 case CXCursor_MemberRef: {
3141 FieldDecl *Field = getCursorMemberRef(C).first;
3142 assert(Field && "Missing member decl");
3143
3144 return createCXString(Field->getNameAsString());
3145 }
3146
Douglas Gregor36897b02010-09-10 00:22:18 +00003147 case CXCursor_LabelRef: {
3148 LabelStmt *Label = getCursorLabelRef(C).first;
3149 assert(Label && "Missing label");
3150
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003151 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003152 }
3153
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003154 case CXCursor_OverloadedDeclRef: {
3155 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3156 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3157 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3158 return createCXString(ND->getNameAsString());
3159 return createCXString("");
3160 }
3161 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3162 return createCXString(E->getName().getAsString());
3163 OverloadedTemplateStorage *Ovl
3164 = Storage.get<OverloadedTemplateStorage*>();
3165 if (Ovl->size() == 0)
3166 return createCXString("");
3167 return createCXString((*Ovl->begin())->getNameAsString());
3168 }
3169
Daniel Dunbaracca7252009-11-30 20:42:49 +00003170 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003171 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003172 }
3173 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003174
3175 if (clang_isExpression(C.kind)) {
3176 Decl *D = getDeclFromExpr(getCursorExpr(C));
3177 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003178 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003179 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003180 }
3181
Douglas Gregor36897b02010-09-10 00:22:18 +00003182 if (clang_isStatement(C.kind)) {
3183 Stmt *S = getCursorStmt(C);
3184 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003185 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003186
3187 return createCXString("");
3188 }
3189
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003190 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003191 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003192 ->getNameStart());
3193
Douglas Gregor572feb22010-03-18 18:04:21 +00003194 if (C.kind == CXCursor_MacroDefinition)
3195 return createCXString(getCursorMacroDefinition(C)->getName()
3196 ->getNameStart());
3197
Douglas Gregorecdcb882010-10-20 22:00:55 +00003198 if (C.kind == CXCursor_InclusionDirective)
3199 return createCXString(getCursorInclusionDirective(C)->getFileName());
3200
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003201 if (clang_isDeclaration(C.kind))
3202 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003203
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003204 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003205}
3206
Douglas Gregor358559d2010-10-02 22:49:11 +00003207CXString clang_getCursorDisplayName(CXCursor C) {
3208 if (!clang_isDeclaration(C.kind))
3209 return clang_getCursorSpelling(C);
3210
3211 Decl *D = getCursorDecl(C);
3212 if (!D)
3213 return createCXString("");
3214
3215 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3216 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3217 D = FunTmpl->getTemplatedDecl();
3218
3219 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3220 llvm::SmallString<64> Str;
3221 llvm::raw_svector_ostream OS(Str);
3222 OS << Function->getNameAsString();
3223 if (Function->getPrimaryTemplate())
3224 OS << "<>";
3225 OS << "(";
3226 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3227 if (I)
3228 OS << ", ";
3229 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3230 }
3231
3232 if (Function->isVariadic()) {
3233 if (Function->getNumParams())
3234 OS << ", ";
3235 OS << "...";
3236 }
3237 OS << ")";
3238 return createCXString(OS.str());
3239 }
3240
3241 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3242 llvm::SmallString<64> Str;
3243 llvm::raw_svector_ostream OS(Str);
3244 OS << ClassTemplate->getNameAsString();
3245 OS << "<";
3246 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3247 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3248 if (I)
3249 OS << ", ";
3250
3251 NamedDecl *Param = Params->getParam(I);
3252 if (Param->getIdentifier()) {
3253 OS << Param->getIdentifier()->getName();
3254 continue;
3255 }
3256
3257 // There is no parameter name, which makes this tricky. Try to come up
3258 // with something useful that isn't too long.
3259 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3260 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3261 else if (NonTypeTemplateParmDecl *NTTP
3262 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3263 OS << NTTP->getType().getAsString(Policy);
3264 else
3265 OS << "template<...> class";
3266 }
3267
3268 OS << ">";
3269 return createCXString(OS.str());
3270 }
3271
3272 if (ClassTemplateSpecializationDecl *ClassSpec
3273 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3274 // If the type was explicitly written, use that.
3275 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3276 return createCXString(TSInfo->getType().getAsString(Policy));
3277
3278 llvm::SmallString<64> Str;
3279 llvm::raw_svector_ostream OS(Str);
3280 OS << ClassSpec->getNameAsString();
3281 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003282 ClassSpec->getTemplateArgs().data(),
3283 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003284 Policy);
3285 return createCXString(OS.str());
3286 }
3287
3288 return clang_getCursorSpelling(C);
3289}
3290
Ted Kremeneke68fff62010-02-17 00:41:32 +00003291CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003292 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003293 case CXCursor_FunctionDecl:
3294 return createCXString("FunctionDecl");
3295 case CXCursor_TypedefDecl:
3296 return createCXString("TypedefDecl");
3297 case CXCursor_EnumDecl:
3298 return createCXString("EnumDecl");
3299 case CXCursor_EnumConstantDecl:
3300 return createCXString("EnumConstantDecl");
3301 case CXCursor_StructDecl:
3302 return createCXString("StructDecl");
3303 case CXCursor_UnionDecl:
3304 return createCXString("UnionDecl");
3305 case CXCursor_ClassDecl:
3306 return createCXString("ClassDecl");
3307 case CXCursor_FieldDecl:
3308 return createCXString("FieldDecl");
3309 case CXCursor_VarDecl:
3310 return createCXString("VarDecl");
3311 case CXCursor_ParmDecl:
3312 return createCXString("ParmDecl");
3313 case CXCursor_ObjCInterfaceDecl:
3314 return createCXString("ObjCInterfaceDecl");
3315 case CXCursor_ObjCCategoryDecl:
3316 return createCXString("ObjCCategoryDecl");
3317 case CXCursor_ObjCProtocolDecl:
3318 return createCXString("ObjCProtocolDecl");
3319 case CXCursor_ObjCPropertyDecl:
3320 return createCXString("ObjCPropertyDecl");
3321 case CXCursor_ObjCIvarDecl:
3322 return createCXString("ObjCIvarDecl");
3323 case CXCursor_ObjCInstanceMethodDecl:
3324 return createCXString("ObjCInstanceMethodDecl");
3325 case CXCursor_ObjCClassMethodDecl:
3326 return createCXString("ObjCClassMethodDecl");
3327 case CXCursor_ObjCImplementationDecl:
3328 return createCXString("ObjCImplementationDecl");
3329 case CXCursor_ObjCCategoryImplDecl:
3330 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003331 case CXCursor_CXXMethod:
3332 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003333 case CXCursor_UnexposedDecl:
3334 return createCXString("UnexposedDecl");
3335 case CXCursor_ObjCSuperClassRef:
3336 return createCXString("ObjCSuperClassRef");
3337 case CXCursor_ObjCProtocolRef:
3338 return createCXString("ObjCProtocolRef");
3339 case CXCursor_ObjCClassRef:
3340 return createCXString("ObjCClassRef");
3341 case CXCursor_TypeRef:
3342 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003343 case CXCursor_TemplateRef:
3344 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003345 case CXCursor_NamespaceRef:
3346 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003347 case CXCursor_MemberRef:
3348 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003349 case CXCursor_LabelRef:
3350 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003351 case CXCursor_OverloadedDeclRef:
3352 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003353 case CXCursor_UnexposedExpr:
3354 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003355 case CXCursor_BlockExpr:
3356 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003357 case CXCursor_DeclRefExpr:
3358 return createCXString("DeclRefExpr");
3359 case CXCursor_MemberRefExpr:
3360 return createCXString("MemberRefExpr");
3361 case CXCursor_CallExpr:
3362 return createCXString("CallExpr");
3363 case CXCursor_ObjCMessageExpr:
3364 return createCXString("ObjCMessageExpr");
3365 case CXCursor_UnexposedStmt:
3366 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003367 case CXCursor_LabelStmt:
3368 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003369 case CXCursor_InvalidFile:
3370 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003371 case CXCursor_InvalidCode:
3372 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003373 case CXCursor_NoDeclFound:
3374 return createCXString("NoDeclFound");
3375 case CXCursor_NotImplemented:
3376 return createCXString("NotImplemented");
3377 case CXCursor_TranslationUnit:
3378 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003379 case CXCursor_UnexposedAttr:
3380 return createCXString("UnexposedAttr");
3381 case CXCursor_IBActionAttr:
3382 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003383 case CXCursor_IBOutletAttr:
3384 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003385 case CXCursor_IBOutletCollectionAttr:
3386 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003387 case CXCursor_PreprocessingDirective:
3388 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003389 case CXCursor_MacroDefinition:
3390 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003391 case CXCursor_MacroExpansion:
3392 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003393 case CXCursor_InclusionDirective:
3394 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003395 case CXCursor_Namespace:
3396 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003397 case CXCursor_LinkageSpec:
3398 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003399 case CXCursor_CXXBaseSpecifier:
3400 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003401 case CXCursor_Constructor:
3402 return createCXString("CXXConstructor");
3403 case CXCursor_Destructor:
3404 return createCXString("CXXDestructor");
3405 case CXCursor_ConversionFunction:
3406 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003407 case CXCursor_TemplateTypeParameter:
3408 return createCXString("TemplateTypeParameter");
3409 case CXCursor_NonTypeTemplateParameter:
3410 return createCXString("NonTypeTemplateParameter");
3411 case CXCursor_TemplateTemplateParameter:
3412 return createCXString("TemplateTemplateParameter");
3413 case CXCursor_FunctionTemplate:
3414 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003415 case CXCursor_ClassTemplate:
3416 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003417 case CXCursor_ClassTemplatePartialSpecialization:
3418 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003419 case CXCursor_NamespaceAlias:
3420 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003421 case CXCursor_UsingDirective:
3422 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003423 case CXCursor_UsingDeclaration:
3424 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003425 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003426 return createCXString("TypeAliasDecl");
3427 case CXCursor_ObjCSynthesizeDecl:
3428 return createCXString("ObjCSynthesizeDecl");
3429 case CXCursor_ObjCDynamicDecl:
3430 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003431 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003432
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003433 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003434 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003435}
Steve Naroff89922f82009-08-31 00:59:03 +00003436
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003437struct GetCursorData {
3438 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003439 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003440 CXCursor &BestCursor;
3441
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003442 GetCursorData(SourceManager &SM,
3443 SourceLocation tokenBegin, CXCursor &outputCursor)
3444 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3445 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3446 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003447};
3448
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003449static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3450 CXCursor parent,
3451 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003452 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3453 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003454
3455 // If we point inside a macro argument we should provide info of what the
3456 // token is so use the actual cursor, don't replace it with a macro expansion
3457 // cursor.
3458 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3459 return CXChildVisit_Recurse;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003460
3461 if (clang_isExpression(cursor.kind) &&
3462 clang_isDeclaration(BestCursor->kind)) {
3463 Decl *D = getCursorDecl(*BestCursor);
3464
3465 // Avoid having the cursor of an expression replace the declaration cursor
3466 // when the expression source range overlaps the declaration range.
3467 // This can happen for C++ constructor expressions whose range generally
3468 // include the variable declaration, e.g.:
3469 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3470 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3471 D->getLocation() == Data->TokenBeginLoc)
3472 return CXChildVisit_Break;
3473 }
3474
Douglas Gregor93798e22010-11-05 21:11:19 +00003475 // If our current best cursor is the construction of a temporary object,
3476 // don't replace that cursor with a type reference, because we want
3477 // clang_getCursor() to point at the constructor.
3478 if (clang_isExpression(BestCursor->kind) &&
3479 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3480 cursor.kind == CXCursor_TypeRef)
3481 return CXChildVisit_Recurse;
3482
Douglas Gregor85fe1562010-12-10 07:23:11 +00003483 // Don't override a preprocessing cursor with another preprocessing
3484 // cursor; we want the outermost preprocessing cursor.
3485 if (clang_isPreprocessing(cursor.kind) &&
3486 clang_isPreprocessing(BestCursor->kind))
3487 return CXChildVisit_Recurse;
3488
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003489 *BestCursor = cursor;
3490 return CXChildVisit_Recurse;
3491}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003492
Douglas Gregorb9790342010-01-22 21:44:22 +00003493CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3494 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003495 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003496
Ted Kremeneka60ed472010-11-16 08:15:36 +00003497 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003498 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3499
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003500 // Translate the given source location to make it point at the beginning of
3501 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003502 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003503
3504 // Guard against an invalid SourceLocation, or we may assert in one
3505 // of the following calls.
3506 if (SLoc.isInvalid())
3507 return clang_getNullCursor();
3508
Douglas Gregor40749ee2010-11-03 00:35:38 +00003509 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003510 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3511 CXXUnit->getASTContext().getLangOptions());
3512
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003513 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3514 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003515 // FIXME: Would be great to have a "hint" cursor, then walk from that
3516 // hint cursor upward until we find a cursor whose source range encloses
3517 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003518 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003519 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003520 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003521 Decl::MaxPCHLevel, true, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003522 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003523 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003524
3525 if (Logging) {
3526 CXFile SearchFile;
3527 unsigned SearchLine, SearchColumn;
3528 CXFile ResultFile;
3529 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003530 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3531 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003532 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3533
3534 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3535 0);
3536 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3537 &ResultColumn, 0);
3538 SearchFileName = clang_getFileName(SearchFile);
3539 ResultFileName = clang_getFileName(ResultFile);
3540 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003541 USR = clang_getCursorUSR(Result);
3542 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003543 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3544 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003545 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3546 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003547 clang_disposeString(SearchFileName);
3548 clang_disposeString(ResultFileName);
3549 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003550 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003551
3552 CXCursor Definition = clang_getCursorDefinition(Result);
3553 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3554 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3555 CXString DefinitionKindSpelling
3556 = clang_getCursorKindSpelling(Definition.kind);
3557 CXFile DefinitionFile;
3558 unsigned DefinitionLine, DefinitionColumn;
3559 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3560 &DefinitionLine, &DefinitionColumn, 0);
3561 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3562 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3563 clang_getCString(DefinitionKindSpelling),
3564 clang_getCString(DefinitionFileName),
3565 DefinitionLine, DefinitionColumn);
3566 clang_disposeString(DefinitionFileName);
3567 clang_disposeString(DefinitionKindSpelling);
3568 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003569 }
3570
Ted Kremeneke68fff62010-02-17 00:41:32 +00003571 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003572}
3573
Ted Kremenek73885552009-11-17 19:28:59 +00003574CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003575 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003576}
3577
3578unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003579 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003580}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003581
Douglas Gregor9ce55842010-11-20 00:09:34 +00003582unsigned clang_hashCursor(CXCursor C) {
3583 unsigned Index = 0;
3584 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3585 Index = 1;
3586
3587 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3588 std::make_pair(C.kind, C.data[Index]));
3589}
3590
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003591unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003592 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3593}
3594
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003595unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003596 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3597}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003598
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003599unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003600 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3601}
3602
Douglas Gregor97b98722010-01-19 23:20:36 +00003603unsigned clang_isExpression(enum CXCursorKind K) {
3604 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3605}
3606
3607unsigned clang_isStatement(enum CXCursorKind K) {
3608 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3609}
3610
Douglas Gregor8be80e12011-07-06 03:00:34 +00003611unsigned clang_isAttribute(enum CXCursorKind K) {
3612 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3613}
3614
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003615unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3616 return K == CXCursor_TranslationUnit;
3617}
3618
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003619unsigned clang_isPreprocessing(enum CXCursorKind K) {
3620 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3621}
3622
Ted Kremenekad6eff62010-03-08 21:17:29 +00003623unsigned clang_isUnexposed(enum CXCursorKind K) {
3624 switch (K) {
3625 case CXCursor_UnexposedDecl:
3626 case CXCursor_UnexposedExpr:
3627 case CXCursor_UnexposedStmt:
3628 case CXCursor_UnexposedAttr:
3629 return true;
3630 default:
3631 return false;
3632 }
3633}
3634
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003635CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003636 return C.kind;
3637}
3638
Douglas Gregor98258af2010-01-18 22:46:11 +00003639CXSourceLocation clang_getCursorLocation(CXCursor C) {
3640 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003641 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003642 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003643 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3644 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003645 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003646 }
3647
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003648 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003649 std::pair<ObjCProtocolDecl *, SourceLocation> P
3650 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003651 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003652 }
3653
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003654 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003655 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3656 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003657 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003658 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003659
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003660 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003661 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003662 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003663 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003664
3665 case CXCursor_TemplateRef: {
3666 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3667 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3668 }
3669
Douglas Gregor69319002010-08-31 23:48:11 +00003670 case CXCursor_NamespaceRef: {
3671 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3672 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3673 }
3674
Douglas Gregora67e03f2010-09-09 21:42:20 +00003675 case CXCursor_MemberRef: {
3676 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3677 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3678 }
3679
Ted Kremenek3064ef92010-08-27 21:34:58 +00003680 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003681 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3682 if (!BaseSpec)
3683 return clang_getNullLocation();
3684
3685 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3686 return cxloc::translateSourceLocation(getCursorContext(C),
3687 TSInfo->getTypeLoc().getBeginLoc());
3688
3689 return cxloc::translateSourceLocation(getCursorContext(C),
3690 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003691 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003692
Douglas Gregor36897b02010-09-10 00:22:18 +00003693 case CXCursor_LabelRef: {
3694 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3695 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3696 }
3697
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003698 case CXCursor_OverloadedDeclRef:
3699 return cxloc::translateSourceLocation(getCursorContext(C),
3700 getCursorOverloadedDeclRef(C).second);
3701
Douglas Gregorf46034a2010-01-18 23:41:10 +00003702 default:
3703 // FIXME: Need a way to enumerate all non-reference cases.
3704 llvm_unreachable("Missed a reference kind");
3705 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003706 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003707
3708 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003709 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003710 getLocationFromExpr(getCursorExpr(C)));
3711
Douglas Gregor36897b02010-09-10 00:22:18 +00003712 if (clang_isStatement(C.kind))
3713 return cxloc::translateSourceLocation(getCursorContext(C),
3714 getCursorStmt(C)->getLocStart());
3715
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003716 if (C.kind == CXCursor_PreprocessingDirective) {
3717 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3718 return cxloc::translateSourceLocation(getCursorContext(C), L);
3719 }
Douglas Gregor48072312010-03-18 15:23:44 +00003720
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003721 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003722 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003723 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003724 return cxloc::translateSourceLocation(getCursorContext(C), L);
3725 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003726
3727 if (C.kind == CXCursor_MacroDefinition) {
3728 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3729 return cxloc::translateSourceLocation(getCursorContext(C), L);
3730 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003731
3732 if (C.kind == CXCursor_InclusionDirective) {
3733 SourceLocation L
3734 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3735 return cxloc::translateSourceLocation(getCursorContext(C), L);
3736 }
3737
Ted Kremenek9a700d22010-05-12 06:16:13 +00003738 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003739 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003740
Douglas Gregorf46034a2010-01-18 23:41:10 +00003741 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003742 SourceLocation Loc = D->getLocation();
3743 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3744 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003745 // FIXME: Multiple variables declared in a single declaration
3746 // currently lack the information needed to correctly determine their
3747 // ranges when accounting for the type-specifier. We use context
3748 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3749 // and if so, whether it is the first decl.
3750 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3751 if (!cxcursor::isFirstInDeclGroup(C))
3752 Loc = VD->getLocation();
3753 }
3754
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003755 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003756}
Douglas Gregora7bde202010-01-19 00:34:46 +00003757
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003758} // end extern "C"
3759
3760static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003761 if (clang_isReference(C.kind)) {
3762 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003763 case CXCursor_ObjCSuperClassRef:
3764 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003765
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003766 case CXCursor_ObjCProtocolRef:
3767 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003768
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003769 case CXCursor_ObjCClassRef:
3770 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003771
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003772 case CXCursor_TypeRef:
3773 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003774
3775 case CXCursor_TemplateRef:
3776 return getCursorTemplateRef(C).second;
3777
Douglas Gregor69319002010-08-31 23:48:11 +00003778 case CXCursor_NamespaceRef:
3779 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003780
3781 case CXCursor_MemberRef:
3782 return getCursorMemberRef(C).second;
3783
Ted Kremenek3064ef92010-08-27 21:34:58 +00003784 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003785 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003786
Douglas Gregor36897b02010-09-10 00:22:18 +00003787 case CXCursor_LabelRef:
3788 return getCursorLabelRef(C).second;
3789
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003790 case CXCursor_OverloadedDeclRef:
3791 return getCursorOverloadedDeclRef(C).second;
3792
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003793 default:
3794 // FIXME: Need a way to enumerate all non-reference cases.
3795 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003796 }
3797 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003798
3799 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003800 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003801
3802 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003803 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003804
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003805 if (C.kind == CXCursor_PreprocessingDirective)
3806 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003807
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003808 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003809 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003810
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003811 if (C.kind == CXCursor_MacroDefinition)
3812 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003813
3814 if (C.kind == CXCursor_InclusionDirective)
3815 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3816
Ted Kremenek007a7c92010-11-01 23:26:51 +00003817 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3818 Decl *D = cxcursor::getCursorDecl(C);
3819 SourceRange R = D->getSourceRange();
3820 // FIXME: Multiple variables declared in a single declaration
3821 // currently lack the information needed to correctly determine their
3822 // ranges when accounting for the type-specifier. We use context
3823 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3824 // and if so, whether it is the first decl.
3825 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3826 if (!cxcursor::isFirstInDeclGroup(C))
3827 R.setBegin(VD->getLocation());
3828 }
3829 return R;
3830 }
Douglas Gregor66537982010-11-17 17:14:07 +00003831 return SourceRange();
3832}
3833
3834/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3835/// the decl-specifier-seq for declarations.
3836static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3837 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3838 Decl *D = cxcursor::getCursorDecl(C);
3839 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003840
Douglas Gregor2494dd02011-03-01 01:34:45 +00003841 // Adjust the start of the location for declarations preceded by
3842 // declaration specifiers.
3843 SourceLocation StartLoc;
3844 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3845 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3846 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3847 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3848 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3849 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3850 }
3851
3852 if (StartLoc.isValid() && R.getBegin().isValid() &&
3853 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3854 R.setBegin(StartLoc);
3855
3856 // FIXME: Multiple variables declared in a single declaration
3857 // currently lack the information needed to correctly determine their
3858 // ranges when accounting for the type-specifier. We use context
3859 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3860 // and if so, whether it is the first decl.
3861 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3862 if (!cxcursor::isFirstInDeclGroup(C))
3863 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003864 }
3865
3866 return R;
3867 }
3868
3869 return getRawCursorExtent(C);
3870}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003871
3872extern "C" {
3873
3874CXSourceRange clang_getCursorExtent(CXCursor C) {
3875 SourceRange R = getRawCursorExtent(C);
3876 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003877 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003878
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003879 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003880}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003881
3882CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003883 if (clang_isInvalid(C.kind))
3884 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003885
Ted Kremeneka60ed472010-11-16 08:15:36 +00003886 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003887 if (clang_isDeclaration(C.kind)) {
3888 Decl *D = getCursorDecl(C);
3889 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003890 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003891 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003892 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003893 if (ObjCForwardProtocolDecl *Protocols
3894 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003896 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003897 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3898 return MakeCXCursor(Property, tu);
3899
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003900 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003901 }
3902
Douglas Gregor97b98722010-01-19 23:20:36 +00003903 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003904 Expr *E = getCursorExpr(C);
3905 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003906 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003907 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003908
3909 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003910 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003911
Douglas Gregor97b98722010-01-19 23:20:36 +00003912 return clang_getNullCursor();
3913 }
3914
Douglas Gregor36897b02010-09-10 00:22:18 +00003915 if (clang_isStatement(C.kind)) {
3916 Stmt *S = getCursorStmt(C);
3917 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003918 if (LabelDecl *label = Goto->getLabel())
3919 if (LabelStmt *labelS = label->getStmt())
3920 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003921
3922 return clang_getNullCursor();
3923 }
3924
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003925 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003926 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003927 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003928 }
3929
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003930 if (!clang_isReference(C.kind))
3931 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003932
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003933 switch (C.kind) {
3934 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003935 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003936
3937 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003938 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003939
3940 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003941 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003942
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003943 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003944 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003945
3946 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003947 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003948
Douglas Gregor69319002010-08-31 23:48:11 +00003949 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003950 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003951
Douglas Gregora67e03f2010-09-09 21:42:20 +00003952 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003953 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003954
Ted Kremenek3064ef92010-08-27 21:34:58 +00003955 case CXCursor_CXXBaseSpecifier: {
3956 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3957 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003958 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003959 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003960
Douglas Gregor36897b02010-09-10 00:22:18 +00003961 case CXCursor_LabelRef:
3962 // FIXME: We end up faking the "parent" declaration here because we
3963 // don't want to make CXCursor larger.
3964 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003965 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3966 .getTranslationUnitDecl(),
3967 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003968
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003969 case CXCursor_OverloadedDeclRef:
3970 return C;
3971
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003972 default:
3973 // We would prefer to enumerate all non-reference cursor kinds here.
3974 llvm_unreachable("Unhandled reference cursor kind");
3975 break;
3976 }
3977 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003978
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003979 return clang_getNullCursor();
3980}
3981
Douglas Gregorb6998662010-01-19 19:34:47 +00003982CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003983 if (clang_isInvalid(C.kind))
3984 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003985
Ted Kremeneka60ed472010-11-16 08:15:36 +00003986 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003987
Douglas Gregorb6998662010-01-19 19:34:47 +00003988 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003989 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003990 C = clang_getCursorReferenced(C);
3991 WasReference = true;
3992 }
3993
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003994 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003995 return clang_getCursorReferenced(C);
3996
Douglas Gregorb6998662010-01-19 19:34:47 +00003997 if (!clang_isDeclaration(C.kind))
3998 return clang_getNullCursor();
3999
4000 Decl *D = getCursorDecl(C);
4001 if (!D)
4002 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004003
Douglas Gregorb6998662010-01-19 19:34:47 +00004004 switch (D->getKind()) {
4005 // Declaration kinds that don't really separate the notions of
4006 // declaration and definition.
4007 case Decl::Namespace:
4008 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004009 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004010 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004011 case Decl::TemplateTypeParm:
4012 case Decl::EnumConstant:
4013 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004014 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004015 case Decl::ObjCIvar:
4016 case Decl::ObjCAtDefsField:
4017 case Decl::ImplicitParam:
4018 case Decl::ParmVar:
4019 case Decl::NonTypeTemplateParm:
4020 case Decl::TemplateTemplateParm:
4021 case Decl::ObjCCategoryImpl:
4022 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004023 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004024 case Decl::LinkageSpec:
4025 case Decl::ObjCPropertyImpl:
4026 case Decl::FileScopeAsm:
4027 case Decl::StaticAssert:
4028 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004029 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004030 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004031 return C;
4032
4033 // Declaration kinds that don't make any sense here, but are
4034 // nonetheless harmless.
4035 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004036 break;
4037
4038 // Declaration kinds for which the definition is not resolvable.
4039 case Decl::UnresolvedUsingTypename:
4040 case Decl::UnresolvedUsingValue:
4041 break;
4042
4043 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004044 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004045 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004046
4047 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004048 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004049
4050 case Decl::Enum:
4051 case Decl::Record:
4052 case Decl::CXXRecord:
4053 case Decl::ClassTemplateSpecialization:
4054 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004055 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004056 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004057 return clang_getNullCursor();
4058
4059 case Decl::Function:
4060 case Decl::CXXMethod:
4061 case Decl::CXXConstructor:
4062 case Decl::CXXDestructor:
4063 case Decl::CXXConversion: {
4064 const FunctionDecl *Def = 0;
4065 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004066 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004067 return clang_getNullCursor();
4068 }
4069
4070 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004071 // Ask the variable if it has a definition.
4072 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004073 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004074 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004075 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004076
Douglas Gregorb6998662010-01-19 19:34:47 +00004077 case Decl::FunctionTemplate: {
4078 const FunctionDecl *Def = 0;
4079 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004080 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004081 return clang_getNullCursor();
4082 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004083
Douglas Gregorb6998662010-01-19 19:34:47 +00004084 case Decl::ClassTemplate: {
4085 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004086 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004087 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004088 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004089 return clang_getNullCursor();
4090 }
4091
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004092 case Decl::Using:
4093 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004094 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004095
4096 case Decl::UsingShadow:
4097 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004098 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004099 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004100
4101 case Decl::ObjCMethod: {
4102 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4103 if (Method->isThisDeclarationADefinition())
4104 return C;
4105
4106 // Dig out the method definition in the associated
4107 // @implementation, if we have it.
4108 // FIXME: The ASTs should make finding the definition easier.
4109 if (ObjCInterfaceDecl *Class
4110 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4111 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4112 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4113 Method->isInstanceMethod()))
4114 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004115 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004116
4117 return clang_getNullCursor();
4118 }
4119
4120 case Decl::ObjCCategory:
4121 if (ObjCCategoryImplDecl *Impl
4122 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004123 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004124 return clang_getNullCursor();
4125
4126 case Decl::ObjCProtocol:
4127 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4128 return C;
4129 return clang_getNullCursor();
4130
4131 case Decl::ObjCInterface:
4132 // There are two notions of a "definition" for an Objective-C
4133 // class: the interface and its implementation. When we resolved a
4134 // reference to an Objective-C class, produce the @interface as
4135 // the definition; when we were provided with the interface,
4136 // produce the @implementation as the definition.
4137 if (WasReference) {
4138 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4139 return C;
4140 } else if (ObjCImplementationDecl *Impl
4141 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004142 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004143 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004144
Douglas Gregorb6998662010-01-19 19:34:47 +00004145 case Decl::ObjCProperty:
4146 // FIXME: We don't really know where to find the
4147 // ObjCPropertyImplDecls that implement this property.
4148 return clang_getNullCursor();
4149
4150 case Decl::ObjCCompatibleAlias:
4151 if (ObjCInterfaceDecl *Class
4152 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4153 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004154 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004155
Douglas Gregorb6998662010-01-19 19:34:47 +00004156 return clang_getNullCursor();
4157
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004158 case Decl::ObjCForwardProtocol:
4159 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004160 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004161
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004162 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004163 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004164 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004165
4166 case Decl::Friend:
4167 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004168 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004169 return clang_getNullCursor();
4170
4171 case Decl::FriendTemplate:
4172 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004173 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004174 return clang_getNullCursor();
4175 }
4176
4177 return clang_getNullCursor();
4178}
4179
4180unsigned clang_isCursorDefinition(CXCursor C) {
4181 if (!clang_isDeclaration(C.kind))
4182 return 0;
4183
4184 return clang_getCursorDefinition(C) == C;
4185}
4186
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004187CXCursor clang_getCanonicalCursor(CXCursor C) {
4188 if (!clang_isDeclaration(C.kind))
4189 return C;
4190
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004191 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004192 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4193 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4194 return MakeCXCursor(CatD, getCursorTU(C));
4195
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004196 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4197 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4198 return MakeCXCursor(IFD, getCursorTU(C));
4199
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004200 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004201 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004202
4203 return C;
4204}
4205
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004206unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004207 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004208 return 0;
4209
4210 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4211 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4212 return E->getNumDecls();
4213
4214 if (OverloadedTemplateStorage *S
4215 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4216 return S->size();
4217
4218 Decl *D = Storage.get<Decl*>();
4219 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004220 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004221 if (isa<ObjCClassDecl>(D))
4222 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004223 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4224 return Protocols->protocol_size();
4225
4226 return 0;
4227}
4228
4229CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004230 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004231 return clang_getNullCursor();
4232
4233 if (index >= clang_getNumOverloadedDecls(cursor))
4234 return clang_getNullCursor();
4235
Ted Kremeneka60ed472010-11-16 08:15:36 +00004236 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004237 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4238 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004239 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004240
4241 if (OverloadedTemplateStorage *S
4242 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004243 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004244
4245 Decl *D = Storage.get<Decl*>();
4246 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4247 // FIXME: This is, unfortunately, linear time.
4248 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4249 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004250 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004251 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004252 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004253 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004254 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004255 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004256
4257 return clang_getNullCursor();
4258}
4259
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004260void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004261 const char **startBuf,
4262 const char **endBuf,
4263 unsigned *startLine,
4264 unsigned *startColumn,
4265 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004266 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004267 assert(getCursorDecl(C) && "CXCursor has null decl");
4268 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004269 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4270 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004271
Steve Naroff4ade6d62009-09-23 17:52:52 +00004272 SourceManager &SM = FD->getASTContext().getSourceManager();
4273 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4274 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4275 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4276 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4277 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4278 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4279}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004280
Douglas Gregor430d7a12011-07-25 17:48:11 +00004281
4282CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4283 unsigned PieceIndex) {
4284 RefNamePieces Pieces;
4285
4286 switch (C.kind) {
4287 case CXCursor_MemberRefExpr:
4288 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4289 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4290 E->getQualifierLoc().getSourceRange());
4291 break;
4292
4293 case CXCursor_DeclRefExpr:
4294 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4295 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4296 E->getQualifierLoc().getSourceRange(),
4297 E->getExplicitTemplateArgsOpt());
4298 break;
4299
4300 case CXCursor_CallExpr:
4301 if (CXXOperatorCallExpr *OCE =
4302 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4303 Expr *Callee = OCE->getCallee();
4304 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4305 Callee = ICE->getSubExpr();
4306
4307 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4308 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4309 DRE->getQualifierLoc().getSourceRange());
4310 }
4311 break;
4312
4313 default:
4314 break;
4315 }
4316
4317 if (Pieces.empty()) {
4318 if (PieceIndex == 0)
4319 return clang_getCursorExtent(C);
4320 } else if (PieceIndex < Pieces.size()) {
4321 SourceRange R = Pieces[PieceIndex];
4322 if (R.isValid())
4323 return cxloc::translateSourceRange(getCursorContext(C), R);
4324 }
4325
4326 return clang_getNullRange();
4327}
4328
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004329void clang_enableStackTraces(void) {
4330 llvm::sys::PrintStackTraceOnErrorSignal();
4331}
4332
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004333void clang_executeOnThread(void (*fn)(void*), void *user_data,
4334 unsigned stack_size) {
4335 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4336}
4337
Ted Kremenekfb480492010-01-13 21:46:36 +00004338} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004339
Ted Kremenekfb480492010-01-13 21:46:36 +00004340//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004341// Token-based Operations.
4342//===----------------------------------------------------------------------===//
4343
4344/* CXToken layout:
4345 * int_data[0]: a CXTokenKind
4346 * int_data[1]: starting token location
4347 * int_data[2]: token length
4348 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004349 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004350 * otherwise unused.
4351 */
4352extern "C" {
4353
4354CXTokenKind clang_getTokenKind(CXToken CXTok) {
4355 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4356}
4357
4358CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4359 switch (clang_getTokenKind(CXTok)) {
4360 case CXToken_Identifier:
4361 case CXToken_Keyword:
4362 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004363 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4364 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004365
4366 case CXToken_Literal: {
4367 // We have stashed the starting pointer in the ptr_data field. Use it.
4368 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004369 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004370 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004371
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004372 case CXToken_Punctuation:
4373 case CXToken_Comment:
4374 break;
4375 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004376
4377 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004378 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004379 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004380 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004381 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004382
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004383 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4384 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004385 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004386 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004387 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004388 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4389 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004390 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004391
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004392 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004393}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004394
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004395CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004396 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004397 if (!CXXUnit)
4398 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004399
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004400 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4401 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4402}
4403
4404CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004405 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004406 if (!CXXUnit)
4407 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004408
4409 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004410 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4411}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004412
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004413void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4414 CXToken **Tokens, unsigned *NumTokens) {
4415 if (Tokens)
4416 *Tokens = 0;
4417 if (NumTokens)
4418 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004419
Ted Kremeneka60ed472010-11-16 08:15:36 +00004420 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004421 if (!CXXUnit || !Tokens || !NumTokens)
4422 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004423
Douglas Gregorbdf60622010-03-05 21:16:25 +00004424 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4425
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004426 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004427 if (R.isInvalid())
4428 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004429
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004430 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4431 std::pair<FileID, unsigned> BeginLocInfo
4432 = SourceMgr.getDecomposedLoc(R.getBegin());
4433 std::pair<FileID, unsigned> EndLocInfo
4434 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004435
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004436 // Cannot tokenize across files.
4437 if (BeginLocInfo.first != EndLocInfo.first)
4438 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004439
4440 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004441 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004442 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004443 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004444 if (Invalid)
4445 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004446
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004447 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4448 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004449 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004450 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004451
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004452 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004453 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004454 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004455 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004456 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004457 do {
4458 // Lex the next token
4459 Lex.LexFromRawLexer(Tok);
4460 if (Tok.is(tok::eof))
4461 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004462
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004463 // Initialize the CXToken.
4464 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004465
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004466 // - Common fields
4467 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4468 CXTok.int_data[2] = Tok.getLength();
4469 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004470
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004471 // - Kind-specific fields
4472 if (Tok.isLiteral()) {
4473 CXTok.int_data[0] = CXToken_Literal;
4474 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004475 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004476 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004477 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004478 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004479
David Chisnall096428b2010-10-13 21:44:48 +00004480 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004481 CXTok.int_data[0] = CXToken_Keyword;
4482 }
4483 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004484 CXTok.int_data[0] = Tok.is(tok::identifier)
4485 ? CXToken_Identifier
4486 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004487 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004488 CXTok.ptr_data = II;
4489 } else if (Tok.is(tok::comment)) {
4490 CXTok.int_data[0] = CXToken_Comment;
4491 CXTok.ptr_data = 0;
4492 } else {
4493 CXTok.int_data[0] = CXToken_Punctuation;
4494 CXTok.ptr_data = 0;
4495 }
4496 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004497 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004498 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004499
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004500 if (CXTokens.empty())
4501 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004502
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004503 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4504 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4505 *NumTokens = CXTokens.size();
4506}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004507
Ted Kremenek6db61092010-05-05 00:55:15 +00004508void clang_disposeTokens(CXTranslationUnit TU,
4509 CXToken *Tokens, unsigned NumTokens) {
4510 free(Tokens);
4511}
4512
4513} // end: extern "C"
4514
4515//===----------------------------------------------------------------------===//
4516// Token annotation APIs.
4517//===----------------------------------------------------------------------===//
4518
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004519typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004520static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4521 CXCursor parent,
4522 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004523namespace {
4524class AnnotateTokensWorker {
4525 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004526 CXToken *Tokens;
4527 CXCursor *Cursors;
4528 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004529 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004530 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004531 CursorVisitor AnnotateVis;
4532 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004533 bool HasContextSensitiveKeywords;
4534
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004535 bool MoreTokens() const { return TokIdx < NumTokens; }
4536 unsigned NextToken() const { return TokIdx; }
4537 void AdvanceToken() { ++TokIdx; }
4538 SourceLocation GetTokenLoc(unsigned tokI) {
4539 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4540 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004541 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004542 return Tokens[tokI].int_data[3] != 0;
4543 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004544 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004545 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4546 }
4547
4548 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004549 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4550 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004551
Ted Kremenek6db61092010-05-05 00:55:15 +00004552public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004553 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004554 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004555 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004556 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004557 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004558 AnnotateVis(tu,
4559 AnnotateTokensVisitor, this,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00004560 Decl::MaxPCHLevel, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004561 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4562 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004563
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004564 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004565 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004566 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004567 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004568 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004569 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004570
4571 /// \brief Determine whether the annotator saw any cursors that have
4572 /// context-sensitive keywords.
4573 bool hasContextSensitiveKeywords() const {
4574 return HasContextSensitiveKeywords;
4575 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004576};
4577}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004578
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004579void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4580 // Walk the AST within the region of interest, annotating tokens
4581 // along the way.
4582 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004583
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004584 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4585 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004586 if (Pos != Annotated.end() &&
4587 (clang_isInvalid(Cursors[I].kind) ||
4588 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004589 Cursors[I] = Pos->second;
4590 }
4591
4592 // Finish up annotating any tokens left.
4593 if (!MoreTokens())
4594 return;
4595
4596 const CXCursor &C = clang_getNullCursor();
4597 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4598 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4599 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004600 }
4601}
4602
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004603/// \brief It annotates and advances tokens with a cursor until the comparison
4604//// between the cursor location and the source range is the same as
4605/// \arg compResult.
4606///
4607/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4608/// Pass RangeOverlap to annotate tokens inside a range.
4609void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4610 RangeComparisonResult compResult,
4611 SourceRange range) {
4612 while (MoreTokens()) {
4613 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004614 if (isFunctionMacroToken(I))
4615 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004616
4617 SourceLocation TokLoc = GetTokenLoc(I);
4618 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4619 Cursors[I] = updateC;
4620 AdvanceToken();
4621 continue;
4622 }
4623 break;
4624 }
4625}
4626
4627/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004628void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4629 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004630 RangeComparisonResult compResult,
4631 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004632 assert(MoreTokens());
4633 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004634 "Should be called only for macro arg tokens");
4635
4636 // This works differently than annotateAndAdvanceTokens; because expanded
4637 // macro arguments can have arbitrary translation-unit source order, we do not
4638 // advance the token index one by one until a token fails the range test.
4639 // We only advance once past all of the macro arg tokens if all of them
4640 // pass the range test. If one of them fails we keep the token index pointing
4641 // at the start of the macro arg tokens so that the failing token will be
4642 // annotated by a subsequent annotation try.
4643
4644 bool atLeastOneCompFail = false;
4645
4646 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004647 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4648 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004649 if (TokLoc.isFileID())
4650 continue; // not macro arg token, it's parens or comma.
4651 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4652 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4653 Cursors[I] = updateC;
4654 } else
4655 atLeastOneCompFail = true;
4656 }
4657
4658 if (!atLeastOneCompFail)
4659 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4660}
4661
Ted Kremenek6db61092010-05-05 00:55:15 +00004662enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004663AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004664 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004665 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004666 if (cursorRange.isInvalid())
4667 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004668
4669 if (!HasContextSensitiveKeywords) {
4670 // Objective-C properties can have context-sensitive keywords.
4671 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4672 if (ObjCPropertyDecl *Property
4673 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4674 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4675 }
4676 // Objective-C methods can have context-sensitive keywords.
4677 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4678 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4679 if (ObjCMethodDecl *Method
4680 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4681 if (Method->getObjCDeclQualifier())
4682 HasContextSensitiveKeywords = true;
4683 else {
4684 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4685 PEnd = Method->param_end();
4686 P != PEnd; ++P) {
4687 if ((*P)->getObjCDeclQualifier()) {
4688 HasContextSensitiveKeywords = true;
4689 break;
4690 }
4691 }
4692 }
4693 }
4694 }
4695 // C++ methods can have context-sensitive keywords.
4696 else if (cursor.kind == CXCursor_CXXMethod) {
4697 if (CXXMethodDecl *Method
4698 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4699 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4700 HasContextSensitiveKeywords = true;
4701 }
4702 }
4703 // C++ classes can have context-sensitive keywords.
4704 else if (cursor.kind == CXCursor_StructDecl ||
4705 cursor.kind == CXCursor_ClassDecl ||
4706 cursor.kind == CXCursor_ClassTemplate ||
4707 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4708 if (Decl *D = getCursorDecl(cursor))
4709 if (D->hasAttr<FinalAttr>())
4710 HasContextSensitiveKeywords = true;
4711 }
4712 }
4713
Douglas Gregor4419b672010-10-21 06:10:04 +00004714 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004715 // For macro expansions, just note where the beginning of the macro
4716 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004717 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004718 Annotated[Loc.int_data] = cursor;
4719 return CXChildVisit_Recurse;
4720 }
4721
Douglas Gregor4419b672010-10-21 06:10:04 +00004722 // Items in the preprocessing record are kept separate from items in
4723 // declarations, so we keep a separate token index.
4724 unsigned SavedTokIdx = TokIdx;
4725 TokIdx = PreprocessingTokIdx;
4726
4727 // Skip tokens up until we catch up to the beginning of the preprocessing
4728 // entry.
4729 while (MoreTokens()) {
4730 const unsigned I = NextToken();
4731 SourceLocation TokLoc = GetTokenLoc(I);
4732 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4733 case RangeBefore:
4734 AdvanceToken();
4735 continue;
4736 case RangeAfter:
4737 case RangeOverlap:
4738 break;
4739 }
4740 break;
4741 }
4742
4743 // Look at all of the tokens within this range.
4744 while (MoreTokens()) {
4745 const unsigned I = NextToken();
4746 SourceLocation TokLoc = GetTokenLoc(I);
4747 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4748 case RangeBefore:
4749 assert(0 && "Infeasible");
4750 case RangeAfter:
4751 break;
4752 case RangeOverlap:
4753 Cursors[I] = cursor;
4754 AdvanceToken();
4755 continue;
4756 }
4757 break;
4758 }
4759
4760 // Save the preprocessing token index; restore the non-preprocessing
4761 // token index.
4762 PreprocessingTokIdx = TokIdx;
4763 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004764 return CXChildVisit_Recurse;
4765 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004766
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004767 if (cursorRange.isInvalid())
4768 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004769
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004770 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4771
Ted Kremeneka333c662010-05-12 05:29:33 +00004772 // Adjust the annotated range based specific declarations.
4773 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4774 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004775 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004776
4777 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004778 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004779 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4780 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4781 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4782 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4783 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004784 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004785
4786 if (StartLoc.isValid() && L.isValid() &&
4787 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4788 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004789 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004790
Ted Kremenek3f404602010-08-14 01:14:06 +00004791 // If the location of the cursor occurs within a macro instantiation, record
4792 // the spelling location of the cursor in our annotation map. We can then
4793 // paper over the token labelings during a post-processing step to try and
4794 // get cursor mappings for tokens that are the *arguments* of a macro
4795 // instantiation.
4796 if (L.isMacroID()) {
4797 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4798 // Only invalidate the old annotation if it isn't part of a preprocessing
4799 // directive. Here we assume that the default construction of CXCursor
4800 // results in CXCursor.kind being an initialized value (i.e., 0). If
4801 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004802
Ted Kremenek3f404602010-08-14 01:14:06 +00004803 CXCursor &oldC = Annotated[rawEncoding];
4804 if (!clang_isPreprocessing(oldC.kind))
4805 oldC = cursor;
4806 }
4807
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004808 const enum CXCursorKind K = clang_getCursorKind(parent);
4809 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004810 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4811 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004812
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004813 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004814
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004815 // Avoid having the cursor of an expression "overwrite" the annotation of the
4816 // variable declaration that it belongs to.
4817 // This can happen for C++ constructor expressions whose range generally
4818 // include the variable declaration, e.g.:
4819 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4820 if (clang_isExpression(cursorK)) {
4821 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004822 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004823 const unsigned I = NextToken();
4824 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4825 E->getLocStart() == D->getLocation() &&
4826 E->getLocStart() == GetTokenLoc(I)) {
4827 Cursors[I] = updateC;
4828 AdvanceToken();
4829 }
4830 }
4831 }
4832
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004833 // Visit children to get their cursor information.
4834 const unsigned BeforeChildren = NextToken();
4835 VisitChildren(cursor);
4836 const unsigned AfterChildren = NextToken();
4837
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004838 // Scan the tokens that are at the end of the cursor, but are not captured
4839 // but the child cursors.
4840 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004841
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004842 // Scan the tokens that are at the beginning of the cursor, but are not
4843 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004844 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4845 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4846 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004847
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004848 Cursors[I] = cursor;
4849 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004850
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004851 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004852}
4853
Ted Kremenek6db61092010-05-05 00:55:15 +00004854static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4855 CXCursor parent,
4856 CXClientData client_data) {
4857 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4858}
4859
Ted Kremenek6628a612011-03-18 22:51:30 +00004860namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004861
4862/// \brief Uses the macro expansions in the preprocessing record to find
4863/// and mark tokens that are macro arguments. This info is used by the
4864/// AnnotateTokensWorker.
4865class MarkMacroArgTokensVisitor {
4866 SourceManager &SM;
4867 CXToken *Tokens;
4868 unsigned NumTokens;
4869 unsigned CurIdx;
4870
4871public:
4872 MarkMacroArgTokensVisitor(SourceManager &SM,
4873 CXToken *tokens, unsigned numTokens)
4874 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4875
4876 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4877 if (cursor.kind != CXCursor_MacroExpansion)
4878 return CXChildVisit_Continue;
4879
4880 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4881 if (macroRange.getBegin() == macroRange.getEnd())
4882 return CXChildVisit_Continue; // it's not a function macro.
4883
4884 for (; CurIdx < NumTokens; ++CurIdx) {
4885 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4886 macroRange.getBegin()))
4887 break;
4888 }
4889
4890 if (CurIdx == NumTokens)
4891 return CXChildVisit_Break;
4892
4893 for (; CurIdx < NumTokens; ++CurIdx) {
4894 SourceLocation tokLoc = getTokenLoc(CurIdx);
4895 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4896 break;
4897
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004898 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004899 }
4900
4901 if (CurIdx == NumTokens)
4902 return CXChildVisit_Break;
4903
4904 return CXChildVisit_Continue;
4905 }
4906
4907private:
4908 SourceLocation getTokenLoc(unsigned tokI) {
4909 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4910 }
4911
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004912 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004913 // The third field is reserved and currently not used. Use it here
4914 // to mark macro arg expanded tokens with their expanded locations.
4915 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4916 }
4917};
4918
4919} // end anonymous namespace
4920
4921static CXChildVisitResult
4922MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4923 CXClientData client_data) {
4924 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4925 parent);
4926}
4927
4928namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004929 struct clang_annotateTokens_Data {
4930 CXTranslationUnit TU;
4931 ASTUnit *CXXUnit;
4932 CXToken *Tokens;
4933 unsigned NumTokens;
4934 CXCursor *Cursors;
4935 };
4936}
4937
Ted Kremenekab979612010-11-11 08:05:23 +00004938// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004939static void clang_annotateTokensImpl(void *UserData) {
4940 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4941 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4942 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4943 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4944 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4945
4946 // Determine the region of interest, which contains all of the tokens.
4947 SourceRange RegionOfInterest;
4948 RegionOfInterest.setBegin(
4949 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4950 RegionOfInterest.setEnd(
4951 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4952 Tokens[NumTokens-1])));
4953
4954 // A mapping from the source locations found when re-lexing or traversing the
4955 // region of interest to the corresponding cursors.
4956 AnnotateTokensData Annotated;
4957
4958 // Relex the tokens within the source range to look for preprocessing
4959 // directives.
4960 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4961 std::pair<FileID, unsigned> BeginLocInfo
4962 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4963 std::pair<FileID, unsigned> EndLocInfo
4964 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4965
Chris Lattner5f9e2722011-07-23 10:55:15 +00004966 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00004967 bool Invalid = false;
4968 if (BeginLocInfo.first == EndLocInfo.first &&
4969 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4970 !Invalid) {
4971 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4972 CXXUnit->getASTContext().getLangOptions(),
4973 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4974 Buffer.end());
4975 Lex.SetCommentRetentionState(true);
4976
4977 // Lex tokens in raw mode until we hit the end of the range, to avoid
4978 // entering #includes or expanding macros.
4979 while (true) {
4980 Token Tok;
4981 Lex.LexFromRawLexer(Tok);
4982
4983 reprocess:
4984 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4985 // We have found a preprocessing directive. Gobble it up so that we
4986 // don't see it while preprocessing these tokens later, but keep track
4987 // of all of the token locations inside this preprocessing directive so
4988 // that we can annotate them appropriately.
4989 //
4990 // FIXME: Some simple tests here could identify macro definitions and
4991 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004992 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00004993 do {
4994 Locations.push_back(Tok.getLocation());
4995 Lex.LexFromRawLexer(Tok);
4996 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4997
4998 using namespace cxcursor;
4999 CXCursor Cursor
5000 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5001 Locations.back()),
5002 TU);
5003 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5004 Annotated[Locations[I].getRawEncoding()] = Cursor;
5005 }
5006
5007 if (Tok.isAtStartOfLine())
5008 goto reprocess;
5009
5010 continue;
5011 }
5012
5013 if (Tok.is(tok::eof))
5014 break;
5015 }
5016 }
5017
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005018 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5019 // Search and mark tokens that are macro argument expansions.
5020 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5021 Tokens, NumTokens);
5022 CursorVisitor MacroArgMarker(TU,
5023 MarkMacroArgTokensVisitorDelegate, &Visitor,
5024 Decl::MaxPCHLevel, true, RegionOfInterest);
5025 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5026 }
5027
Ted Kremenek6628a612011-03-18 22:51:30 +00005028 // Annotate all of the source locations in the region of interest that map to
5029 // a specific cursor.
5030 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5031 TU, RegionOfInterest);
5032
5033 // FIXME: We use a ridiculous stack size here because the data-recursion
5034 // algorithm uses a large stack frame than the non-data recursive version,
5035 // and AnnotationTokensWorker currently transforms the data-recursion
5036 // algorithm back into a traditional recursion by explicitly calling
5037 // VisitChildren(). We will need to remove this explicit recursive call.
5038 W.AnnotateTokens();
5039
5040 // If we ran into any entities that involve context-sensitive keywords,
5041 // take another pass through the tokens to mark them as such.
5042 if (W.hasContextSensitiveKeywords()) {
5043 for (unsigned I = 0; I != NumTokens; ++I) {
5044 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5045 continue;
5046
5047 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5048 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5049 if (ObjCPropertyDecl *Property
5050 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5051 if (Property->getPropertyAttributesAsWritten() != 0 &&
5052 llvm::StringSwitch<bool>(II->getName())
5053 .Case("readonly", true)
5054 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005055 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005056 .Case("readwrite", true)
5057 .Case("retain", true)
5058 .Case("copy", true)
5059 .Case("nonatomic", true)
5060 .Case("atomic", true)
5061 .Case("getter", true)
5062 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005063 .Case("strong", true)
5064 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005065 .Default(false))
5066 Tokens[I].int_data[0] = CXToken_Keyword;
5067 }
5068 continue;
5069 }
5070
5071 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5072 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5073 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5074 if (llvm::StringSwitch<bool>(II->getName())
5075 .Case("in", true)
5076 .Case("out", true)
5077 .Case("inout", true)
5078 .Case("oneway", true)
5079 .Case("bycopy", true)
5080 .Case("byref", true)
5081 .Default(false))
5082 Tokens[I].int_data[0] = CXToken_Keyword;
5083 continue;
5084 }
5085
5086 if (Cursors[I].kind == CXCursor_CXXMethod) {
5087 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5088 if (CXXMethodDecl *Method
5089 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
5090 if ((Method->hasAttr<FinalAttr>() ||
5091 Method->hasAttr<OverrideAttr>()) &&
5092 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
5093 llvm::StringSwitch<bool>(II->getName())
5094 .Case("final", true)
5095 .Case("override", true)
5096 .Default(false))
5097 Tokens[I].int_data[0] = CXToken_Keyword;
5098 }
5099 continue;
5100 }
5101
5102 if (Cursors[I].kind == CXCursor_ClassDecl ||
5103 Cursors[I].kind == CXCursor_StructDecl ||
5104 Cursors[I].kind == CXCursor_ClassTemplate) {
5105 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5106 if (II->getName() == "final") {
5107 // We have to be careful with 'final', since it could be the name
5108 // of a member class rather than the context-sensitive keyword.
5109 // So, check whether the cursor associated with this
5110 Decl *D = getCursorDecl(Cursors[I]);
5111 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
5112 if ((Record->hasAttr<FinalAttr>()) &&
5113 Record->getIdentifier() != II)
5114 Tokens[I].int_data[0] = CXToken_Keyword;
5115 } else if (ClassTemplateDecl *ClassTemplate
5116 = dyn_cast_or_null<ClassTemplateDecl>(D)) {
5117 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
5118 if ((Record->hasAttr<FinalAttr>()) &&
5119 Record->getIdentifier() != II)
5120 Tokens[I].int_data[0] = CXToken_Keyword;
5121 }
5122 }
5123 continue;
5124 }
5125 }
5126 }
Ted Kremenekab979612010-11-11 08:05:23 +00005127}
5128
Ted Kremenek6db61092010-05-05 00:55:15 +00005129extern "C" {
5130
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005131void clang_annotateTokens(CXTranslationUnit TU,
5132 CXToken *Tokens, unsigned NumTokens,
5133 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005134
5135 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005136 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005137
Douglas Gregor4419b672010-10-21 06:10:04 +00005138 // Any token we don't specifically annotate will have a NULL cursor.
5139 CXCursor C = clang_getNullCursor();
5140 for (unsigned I = 0; I != NumTokens; ++I)
5141 Cursors[I] = C;
5142
Ted Kremeneka60ed472010-11-16 08:15:36 +00005143 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005144 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005145 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005146
Douglas Gregorbdf60622010-03-05 21:16:25 +00005147 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005148
5149 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005150 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005151 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005152 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005153 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5154 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005155}
Ted Kremenek6628a612011-03-18 22:51:30 +00005156
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005157} // end: extern "C"
5158
5159//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005160// Operations for querying linkage of a cursor.
5161//===----------------------------------------------------------------------===//
5162
5163extern "C" {
5164CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005165 if (!clang_isDeclaration(cursor.kind))
5166 return CXLinkage_Invalid;
5167
Ted Kremenek16b42592010-03-03 06:36:57 +00005168 Decl *D = cxcursor::getCursorDecl(cursor);
5169 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5170 switch (ND->getLinkage()) {
5171 case NoLinkage: return CXLinkage_NoLinkage;
5172 case InternalLinkage: return CXLinkage_Internal;
5173 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5174 case ExternalLinkage: return CXLinkage_External;
5175 };
5176
5177 return CXLinkage_Invalid;
5178}
5179} // end: extern "C"
5180
5181//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005182// Operations for querying language of a cursor.
5183//===----------------------------------------------------------------------===//
5184
5185static CXLanguageKind getDeclLanguage(const Decl *D) {
5186 switch (D->getKind()) {
5187 default:
5188 break;
5189 case Decl::ImplicitParam:
5190 case Decl::ObjCAtDefsField:
5191 case Decl::ObjCCategory:
5192 case Decl::ObjCCategoryImpl:
5193 case Decl::ObjCClass:
5194 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005195 case Decl::ObjCForwardProtocol:
5196 case Decl::ObjCImplementation:
5197 case Decl::ObjCInterface:
5198 case Decl::ObjCIvar:
5199 case Decl::ObjCMethod:
5200 case Decl::ObjCProperty:
5201 case Decl::ObjCPropertyImpl:
5202 case Decl::ObjCProtocol:
5203 return CXLanguage_ObjC;
5204 case Decl::CXXConstructor:
5205 case Decl::CXXConversion:
5206 case Decl::CXXDestructor:
5207 case Decl::CXXMethod:
5208 case Decl::CXXRecord:
5209 case Decl::ClassTemplate:
5210 case Decl::ClassTemplatePartialSpecialization:
5211 case Decl::ClassTemplateSpecialization:
5212 case Decl::Friend:
5213 case Decl::FriendTemplate:
5214 case Decl::FunctionTemplate:
5215 case Decl::LinkageSpec:
5216 case Decl::Namespace:
5217 case Decl::NamespaceAlias:
5218 case Decl::NonTypeTemplateParm:
5219 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005220 case Decl::TemplateTemplateParm:
5221 case Decl::TemplateTypeParm:
5222 case Decl::UnresolvedUsingTypename:
5223 case Decl::UnresolvedUsingValue:
5224 case Decl::Using:
5225 case Decl::UsingDirective:
5226 case Decl::UsingShadow:
5227 return CXLanguage_CPlusPlus;
5228 }
5229
5230 return CXLanguage_C;
5231}
5232
5233extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005234
5235enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5236 if (clang_isDeclaration(cursor.kind))
5237 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005238 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005239 return CXAvailability_Available;
5240
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005241 switch (D->getAvailability()) {
5242 case AR_Available:
5243 case AR_NotYetIntroduced:
5244 return CXAvailability_Available;
5245
5246 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005247 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005248
5249 case AR_Unavailable:
5250 return CXAvailability_NotAvailable;
5251 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005252 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005253
Douglas Gregor58ddb602010-08-23 23:00:57 +00005254 return CXAvailability_Available;
5255}
5256
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005257CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5258 if (clang_isDeclaration(cursor.kind))
5259 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5260
5261 return CXLanguage_Invalid;
5262}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005263
5264 /// \brief If the given cursor is the "templated" declaration
5265 /// descibing a class or function template, return the class or
5266 /// function template.
5267static Decl *maybeGetTemplateCursor(Decl *D) {
5268 if (!D)
5269 return 0;
5270
5271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5272 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5273 return FunTmpl;
5274
5275 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5276 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5277 return ClassTmpl;
5278
5279 return D;
5280}
5281
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005282CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5283 if (clang_isDeclaration(cursor.kind)) {
5284 if (Decl *D = getCursorDecl(cursor)) {
5285 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005286 if (!DC)
5287 return clang_getNullCursor();
5288
5289 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5290 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005291 }
5292 }
5293
5294 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5295 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005296 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005297 }
5298
5299 return clang_getNullCursor();
5300}
5301
5302CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5303 if (clang_isDeclaration(cursor.kind)) {
5304 if (Decl *D = getCursorDecl(cursor)) {
5305 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005306 if (!DC)
5307 return clang_getNullCursor();
5308
5309 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5310 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005311 }
5312 }
5313
5314 // FIXME: Note that we can't easily compute the lexical context of a
5315 // statement or expression, so we return nothing.
5316 return clang_getNullCursor();
5317}
5318
Douglas Gregor9f592342010-10-01 20:25:15 +00005319static void CollectOverriddenMethods(DeclContext *Ctx,
5320 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005321 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005322 if (!Ctx)
5323 return;
5324
5325 // If we have a class or category implementation, jump straight to the
5326 // interface.
5327 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5328 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5329
5330 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5331 if (!Container)
5332 return;
5333
5334 // Check whether we have a matching method at this level.
5335 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5336 Method->isInstanceMethod()))
5337 if (Method != Overridden) {
5338 // We found an override at this level; there is no need to look
5339 // into other protocols or categories.
5340 Methods.push_back(Overridden);
5341 return;
5342 }
5343
5344 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5345 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5346 PEnd = Protocol->protocol_end();
5347 P != PEnd; ++P)
5348 CollectOverriddenMethods(*P, Method, Methods);
5349 }
5350
5351 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5352 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5353 PEnd = Category->protocol_end();
5354 P != PEnd; ++P)
5355 CollectOverriddenMethods(*P, Method, Methods);
5356 }
5357
5358 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5359 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5360 PEnd = Interface->protocol_end();
5361 P != PEnd; ++P)
5362 CollectOverriddenMethods(*P, Method, Methods);
5363
5364 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5365 Category; Category = Category->getNextClassCategory())
5366 CollectOverriddenMethods(Category, Method, Methods);
5367
5368 // We only look into the superclass if we haven't found anything yet.
5369 if (Methods.empty())
5370 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5371 return CollectOverriddenMethods(Super, Method, Methods);
5372 }
5373}
5374
5375void clang_getOverriddenCursors(CXCursor cursor,
5376 CXCursor **overridden,
5377 unsigned *num_overridden) {
5378 if (overridden)
5379 *overridden = 0;
5380 if (num_overridden)
5381 *num_overridden = 0;
5382 if (!overridden || !num_overridden)
5383 return;
5384
5385 if (!clang_isDeclaration(cursor.kind))
5386 return;
5387
5388 Decl *D = getCursorDecl(cursor);
5389 if (!D)
5390 return;
5391
5392 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005393 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005394 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5395 *num_overridden = CXXMethod->size_overridden_methods();
5396 if (!*num_overridden)
5397 return;
5398
5399 *overridden = new CXCursor [*num_overridden];
5400 unsigned I = 0;
5401 for (CXXMethodDecl::method_iterator
5402 M = CXXMethod->begin_overridden_methods(),
5403 MEnd = CXXMethod->end_overridden_methods();
5404 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005405 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005406 return;
5407 }
5408
5409 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5410 if (!Method)
5411 return;
5412
5413 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005414 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005415 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5416
5417 if (Methods.empty())
5418 return;
5419
5420 *num_overridden = Methods.size();
5421 *overridden = new CXCursor [Methods.size()];
5422 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005423 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005424}
5425
5426void clang_disposeOverriddenCursors(CXCursor *overridden) {
5427 delete [] overridden;
5428}
5429
Douglas Gregorecdcb882010-10-20 22:00:55 +00005430CXFile clang_getIncludedFile(CXCursor cursor) {
5431 if (cursor.kind != CXCursor_InclusionDirective)
5432 return 0;
5433
5434 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5435 return (void *)ID->getFile();
5436}
5437
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005438} // end: extern "C"
5439
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005440
5441//===----------------------------------------------------------------------===//
5442// C++ AST instrospection.
5443//===----------------------------------------------------------------------===//
5444
5445extern "C" {
5446unsigned clang_CXXMethod_isStatic(CXCursor C) {
5447 if (!clang_isDeclaration(C.kind))
5448 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005449
5450 CXXMethodDecl *Method = 0;
5451 Decl *D = cxcursor::getCursorDecl(C);
5452 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5453 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5454 else
5455 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5456 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005457}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005458
Douglas Gregor211924b2011-05-12 15:17:24 +00005459unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5460 if (!clang_isDeclaration(C.kind))
5461 return 0;
5462
5463 CXXMethodDecl *Method = 0;
5464 Decl *D = cxcursor::getCursorDecl(C);
5465 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5466 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5467 else
5468 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5469 return (Method && Method->isVirtual()) ? 1 : 0;
5470}
5471
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005472} // end: extern "C"
5473
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005474//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005475// Attribute introspection.
5476//===----------------------------------------------------------------------===//
5477
5478extern "C" {
5479CXType clang_getIBOutletCollectionType(CXCursor C) {
5480 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005481 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005482
5483 IBOutletCollectionAttr *A =
5484 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5485
Douglas Gregor841b2382011-03-06 18:55:32 +00005486 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005487}
5488} // end: extern "C"
5489
5490//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005491// Inspecting memory usage.
5492//===----------------------------------------------------------------------===//
5493
Ted Kremenekf7870022011-04-20 16:41:07 +00005494typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005495
Ted Kremenekf7870022011-04-20 16:41:07 +00005496static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5497 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005498 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005499 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005500 entries.push_back(entry);
5501}
5502
5503extern "C" {
5504
Ted Kremenekf7870022011-04-20 16:41:07 +00005505const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005506 const char *str = "";
5507 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005508 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005509 str = "ASTContext: expressions, declarations, and types";
5510 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005511 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005512 str = "ASTContext: identifiers";
5513 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005514 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005515 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005516 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005517 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005518 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005519 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005520 case CXTUResourceUsage_SourceManagerContentCache:
5521 str = "SourceManager: content cache allocator";
5522 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005523 case CXTUResourceUsage_AST_SideTables:
5524 str = "ASTContext: side tables";
5525 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005526 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5527 str = "SourceManager: malloc'ed memory buffers";
5528 break;
5529 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5530 str = "SourceManager: mmap'ed memory buffers";
5531 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005532 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5533 str = "ExternalASTSource: malloc'ed memory buffers";
5534 break;
5535 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5536 str = "ExternalASTSource: mmap'ed memory buffers";
5537 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005538 case CXTUResourceUsage_Preprocessor:
5539 str = "Preprocessor: malloc'ed memory";
5540 break;
5541 case CXTUResourceUsage_PreprocessingRecord:
5542 str = "Preprocessor: PreprocessingRecord";
5543 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005544 case CXTUResourceUsage_SourceManager_DataStructures:
5545 str = "SourceManager: data structures and tables";
5546 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005547 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5548 str = "Preprocessor: header search tables";
5549 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005550 }
5551 return str;
5552}
5553
Ted Kremenekf7870022011-04-20 16:41:07 +00005554CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005555 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005556 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005557 return usage;
5558 }
5559
5560 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5561 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5562 ASTContext &astContext = astUnit->getASTContext();
5563
5564 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005565 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005566 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005567
5568 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005569 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005570 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5571
5572 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005573 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005574 (unsigned long) astContext.Selectors.getTotalMemory());
5575
Ted Kremenekba29bd22011-04-28 04:53:38 +00005576 // How much memory is used by ASTContext's side tables?
5577 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5578 (unsigned long) astContext.getSideTableAllocatedMemory());
5579
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005580 // How much memory is used for caching global code completion results?
5581 unsigned long completionBytes = 0;
5582 if (GlobalCodeCompletionAllocator *completionAllocator =
5583 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005584 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005585 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005586 createCXTUResourceUsageEntry(*entries,
5587 CXTUResourceUsage_GlobalCompletionResults,
5588 completionBytes);
5589
5590 // How much memory is being used by SourceManager's content cache?
5591 createCXTUResourceUsageEntry(*entries,
5592 CXTUResourceUsage_SourceManagerContentCache,
5593 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005594
5595 // How much memory is being used by the MemoryBuffer's in SourceManager?
5596 const SourceManager::MemoryBufferSizes &srcBufs =
5597 astUnit->getSourceManager().getMemoryBufferSizes();
5598
5599 createCXTUResourceUsageEntry(*entries,
5600 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5601 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005602 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005603 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5604 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005605 createCXTUResourceUsageEntry(*entries,
5606 CXTUResourceUsage_SourceManager_DataStructures,
5607 (unsigned long) astContext.getSourceManager()
5608 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005609
5610 // How much memory is being used by the ExternalASTSource?
5611 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5612 const ExternalASTSource::MemoryBufferSizes &sizes =
5613 esrc->getMemoryBufferSizes();
5614
5615 createCXTUResourceUsageEntry(*entries,
5616 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5617 (unsigned long) sizes.malloc_bytes);
5618 createCXTUResourceUsageEntry(*entries,
5619 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5620 (unsigned long) sizes.mmap_bytes);
5621 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005622
5623 // How much memory is being used by the Preprocessor?
5624 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005625 createCXTUResourceUsageEntry(*entries,
5626 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005627 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005628
5629 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5630 createCXTUResourceUsageEntry(*entries,
5631 CXTUResourceUsage_PreprocessingRecord,
5632 pRec->getTotalMemory());
5633 }
5634
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005635 createCXTUResourceUsageEntry(*entries,
5636 CXTUResourceUsage_Preprocessor_HeaderSearch,
5637 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005638
Ted Kremenekf7870022011-04-20 16:41:07 +00005639 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005640 (unsigned) entries->size(),
5641 entries->size() ? &(*entries)[0] : 0 };
5642 entries.take();
5643 return usage;
5644}
5645
Ted Kremenekf7870022011-04-20 16:41:07 +00005646void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005647 if (usage.data)
5648 delete (MemUsageEntries*) usage.data;
5649}
5650
5651} // end extern "C"
5652
Douglas Gregor6df78732011-05-05 20:27:22 +00005653void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5654 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5655 for (unsigned I = 0; I != Usage.numEntries; ++I)
5656 fprintf(stderr, " %s: %lu\n",
5657 clang_getTUResourceUsageName(Usage.entries[I].kind),
5658 Usage.entries[I].amount);
5659
5660 clang_disposeCXTUResourceUsage(Usage);
5661}
5662
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005663//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005664// Misc. utility functions.
5665//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005666
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005667/// Default to using an 8 MB stack size on "safety" threads.
5668static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005669
5670namespace clang {
5671
5672bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005673 void (*Fn)(void*), void *UserData,
5674 unsigned Size) {
5675 if (!Size)
5676 Size = GetSafetyThreadStackSize();
5677 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005678 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5679 return CRC.RunSafely(Fn, UserData);
5680}
5681
5682unsigned GetSafetyThreadStackSize() {
5683 return SafetyStackThreadSize;
5684}
5685
5686void SetSafetyThreadStackSize(unsigned Value) {
5687 SafetyStackThreadSize = Value;
5688}
5689
5690}
5691
Ted Kremenek04bb7162010-01-22 22:44:15 +00005692extern "C" {
5693
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005694CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005695 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005696}
5697
5698} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005699