blob: c8dbf3b58880779ecb42a27d31490b90639f93b8 [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"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
37#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000038#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000039#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000040#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000042#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000043#include "llvm/Support/Mutex.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000047#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000048
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Ted Kremeneka60ed472010-11-16 08:15:36 +000053static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
54 if (!TU)
55 return 0;
56 CXTranslationUnit D = new CXTranslationUnitImpl();
57 D->TUData = TU;
58 D->StringPool = createCXStringPool();
59 return D;
60}
61
Douglas Gregor33e9abd2010-01-22 19:49:59 +000062/// \brief The result of comparing two source ranges.
63enum RangeComparisonResult {
64 /// \brief Either the ranges overlap or one of the ranges is invalid.
65 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000066
Douglas Gregor33e9abd2010-01-22 19:49:59 +000067 /// \brief The first range ends before the second range starts.
68 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000069
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070 /// \brief The first range starts after the second range ends.
71 RangeAfter
72};
73
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076static RangeComparisonResult RangeCompare(SourceManager &SM,
77 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 SourceRange R2) {
79 assert(R1.isValid() && "First range is invalid?");
80 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000081 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000082 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000085 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 return RangeAfter;
87 return RangeOverlap;
88}
89
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000090/// \brief Determine if a source location falls within, before, or after a
91/// a given source range.
92static RangeComparisonResult LocationCompare(SourceManager &SM,
93 SourceLocation L, SourceRange R) {
94 assert(R.isValid() && "First range is invalid?");
95 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000096 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
99 return RangeBefore;
100 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
101 return RangeAfter;
102 return RangeOverlap;
103}
104
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105/// \brief Translate a Clang source range into a CIndex source range.
106///
107/// Clang internally represents ranges where the end location points to the
108/// start of the token at the end. However, for external clients it is more
109/// useful to have a CXSourceRange be a proper half-open interval. This routine
110/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000111CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000113 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000115 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000117 if (EndLoc.isValid() && EndLoc.isMacroID())
118 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000119 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000120 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000121 EndLoc = EndLoc.getFileLocWithOffset(Length);
122 }
123
124 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
125 R.getBegin().getRawEncoding(),
126 EndLoc.getRawEncoding() };
127 return Result;
128}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000129
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
133
Steve Naroff89922f82009-08-31 00:59:03 +0000134namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135
136class VisitorJob {
137public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000138 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000139 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000140 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000141 ExplicitTemplateArgsVisitKind,
142 NestedNameSpecifierVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000143 DeclarationNameInfoVisitKind,
144 MemberRefVisitKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000145protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000146 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147 CXCursor parent;
148 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
150 : parent(C), K(k) {
151 data[0] = d1;
152 data[1] = d2;
153 data[2] = d3;
154 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000155public:
156 Kind getKind() const { return K; }
157 const CXCursor &getParent() const { return parent; }
158 static bool classof(VisitorJob *VJ) { return true; }
159};
160
161typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
162
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000164class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000165 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000168 CXTranslationUnit TU;
169 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The declaration that serves at the parent of any statement or
175 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000176 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000178 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000179 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000184 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
185 // to the visitor. Declarations with a PCH level greater than this value will
186 // be suppressed.
187 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188
189 /// \brief When valid, a source range to which the cursor should restrict
190 /// its search.
191 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000193 // FIXME: Eventually remove. This part of a hack to support proper
194 // iteration over all Decls contained lexically within an ObjC container.
195 DeclContext::decl_iterator *DI_current;
196 DeclContext::decl_iterator DE_current;
197
Ted Kremenekd1ded662010-11-15 23:31:32 +0000198 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
199 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
200 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000204
205 /// \brief Determine whether this particular source range comes before, comes
206 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000208 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
210
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000211 class SetParentRAII {
212 CXCursor &Parent;
213 Decl *&StmtParent;
214 CXCursor OldParent;
215
216 public:
217 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
218 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
219 {
220 Parent = NewParent;
221 if (clang_isDeclaration(Parent.kind))
222 StmtParent = getCursorDecl(Parent);
223 }
224
225 ~SetParentRAII() {
226 Parent = OldParent;
227 if (clang_isDeclaration(Parent.kind))
228 StmtParent = getCursorDecl(Parent);
229 }
230 };
231
Steve Naroff89922f82009-08-31 00:59:03 +0000232public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000233 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
234 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000237 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
238 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000239 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
240 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 {
242 Parent.kind = CXCursor_NoDeclFound;
243 Parent.data[0] = 0;
244 Parent.data[1] = 0;
245 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000246 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000247 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000248
Ted Kremenekd1ded662010-11-15 23:31:32 +0000249 ~CursorVisitor() {
250 // Free the pre-allocated worklists for data-recursion.
251 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
252 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
253 delete *I;
254 }
255 }
256
Ted Kremeneka60ed472010-11-16 08:15:36 +0000257 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
258 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000259
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000260 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000261
262 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
263 getPreprocessedEntities();
264
Douglas Gregorb1373d02010-01-20 20:59:29 +0000265 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000266
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000268 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000269 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000270 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000271 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000273 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
274 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000276 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000277 bool VisitClassTemplatePartialSpecializationDecl(
278 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000279 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000280 bool VisitEnumConstantDecl(EnumConstantDecl *D);
281 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
282 bool VisitFunctionDecl(FunctionDecl *ND);
283 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000284 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000285 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000287 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000288 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
290 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
291 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
292 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000293 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
295 bool VisitObjCImplDecl(ObjCImplDecl *D);
296 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
297 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
299 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
300 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000301 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000302 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000303 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000304 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000305 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000306 bool VisitUsingDecl(UsingDecl *D);
307 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
308 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000309
Douglas Gregor01829d32010-08-31 14:41:23 +0000310 // Name visitor
311 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000312 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000313
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000314 // Template visitors
315 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000316 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000317 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
318
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000319 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000320 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000322 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
324 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000325 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000326 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000327 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000329 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitPointerTypeLoc(PointerTypeLoc TL);
331 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
332 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
333 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
334 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000335 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000337 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000338 // FIXME: Implement visitors here when the unimplemented TypeLocs get
339 // implemented
340 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
341 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000342
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000343 // Data-recursive visitor functions.
344 bool IsInRegionOfInterest(CXCursor C);
345 bool RunVisitorWorkList(VisitorWorkList &WL);
346 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000347 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000348};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000349
Ted Kremenekab188932010-01-05 19:32:54 +0000350} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000351
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000352static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000353static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
354
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000355
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000356RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000357 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000358}
359
Douglas Gregorb1373d02010-01-20 20:59:29 +0000360/// \brief Visit the given cursor and, if requested by the visitor,
361/// its children.
362///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000363/// \param Cursor the cursor to visit.
364///
365/// \param CheckRegionOfInterest if true, then the caller already checked that
366/// this cursor is within the region of interest.
367///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000368/// \returns true if the visitation should be aborted, false if it
369/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000370bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 if (clang_isInvalid(Cursor.kind))
372 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000373
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 if (clang_isDeclaration(Cursor.kind)) {
375 Decl *D = getCursorDecl(Cursor);
376 assert(D && "Invalid declaration cursor");
377 if (D->getPCHLevel() > MaxPCHLevel)
378 return false;
379
380 if (D->isImplicit())
381 return false;
382 }
383
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000384 // If we have a range of interest, and this cursor doesn't intersect with it,
385 // we're done.
386 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000387 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000388 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000389 return false;
390 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000391
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392 switch (Visitor(Cursor, Parent, ClientData)) {
393 case CXChildVisit_Break:
394 return true;
395
396 case CXChildVisit_Continue:
397 return false;
398
399 case CXChildVisit_Recurse:
400 return VisitChildren(Cursor);
401 }
402
Douglas Gregorfd643772010-01-25 16:45:46 +0000403 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404}
405
Douglas Gregor788f5a12010-03-20 00:41:21 +0000406std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
407CursorVisitor::getPreprocessedEntities() {
408 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000409 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000410
411 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000412 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000413
Douglas Gregor89d99802010-11-30 06:16:57 +0000414 PreprocessingRecord::iterator StartEntity, EndEntity;
415 if (OnlyLocalDecls) {
416 StartEntity = AU->pp_entity_begin();
417 EndEntity = AU->pp_entity_end();
418 } else {
419 StartEntity = PPRec.begin();
420 EndEntity = PPRec.end();
421 }
422
Douglas Gregor788f5a12010-03-20 00:41:21 +0000423 // There is no region of interest; we have to walk everything.
424 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000425 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000426
427 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000428 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429 std::pair<FileID, unsigned> Begin
430 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
431 std::pair<FileID, unsigned> End
432 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
433
434 // The region of interest spans files; we have to walk everything.
435 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000436 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000437
438 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000439 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000440 if (ByFileMap.empty()) {
441 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000442 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000443 std::pair<FileID, unsigned> P
444 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000445
Douglas Gregor788f5a12010-03-20 00:41:21 +0000446 ByFileMap[P.first].push_back(*E);
447 }
448 }
449
450 return std::make_pair(ByFileMap[Begin.first].begin(),
451 ByFileMap[Begin.first].end());
452}
453
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000455///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456/// \returns true if the visitation should be aborted, false if it
457/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000458bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000459 if (clang_isReference(Cursor.kind)) {
460 // By definition, references have no children.
461 return false;
462 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463
464 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000465 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000466 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000467
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 if (clang_isDeclaration(Cursor.kind)) {
469 Decl *D = getCursorDecl(Cursor);
470 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000471 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000473
Douglas Gregora59e3902010-01-21 23:27:09 +0000474 if (clang_isStatement(Cursor.kind))
475 return Visit(getCursorStmt(Cursor));
476 if (clang_isExpression(Cursor.kind))
477 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478
Douglas Gregorb1373d02010-01-20 20:59:29 +0000479 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000480 CXTranslationUnit tu = getCursorTU(Cursor);
481 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000482 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
483 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000484 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
485 TLEnd = CXXUnit->top_level_end();
486 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000487 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000488 return true;
489 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000490 } else if (VisitDeclContext(
491 CXXUnit->getASTContext().getTranslationUnitDecl()))
492 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000493
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000495 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 // FIXME: Once we have the ability to deserialize a preprocessing record,
497 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000498 PreprocessingRecord::iterator E, EEnd;
499 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000501 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000503
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 continue;
505 }
506
507 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000508 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000509 return true;
510
511 continue;
512 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000513
514 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000515 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000516 return true;
517
518 continue;
519 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000520 }
521 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000522 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000524
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 return false;
527}
528
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000529bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000530 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
531 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000532
Ted Kremenek664cffd2010-07-22 11:30:19 +0000533 if (Stmt *Body = B->getBody())
534 return Visit(MakeCXCursor(Body, StmtParent, TU));
535
536 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000537}
538
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000539llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
540 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000541 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000542 if (Range.isInvalid())
543 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000544
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000545 switch (CompareRegionOfInterest(Range)) {
546 case RangeBefore:
547 // This declaration comes before the region of interest; skip it.
548 return llvm::Optional<bool>();
549
550 case RangeAfter:
551 // This declaration comes after the region of interest; we're done.
552 return false;
553
554 case RangeOverlap:
555 // This declaration overlaps the region of interest; visit it.
556 break;
557 }
558 }
559 return true;
560}
561
562bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
563 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
564
565 // FIXME: Eventually remove. This part of a hack to support proper
566 // iteration over all Decls contained lexically within an ObjC container.
567 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
568 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
569
570 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000571 Decl *D = *I;
572 if (D->getLexicalDeclContext() != DC)
573 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000574 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000575 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
576 if (!V.hasValue())
577 continue;
578 if (!V.getValue())
579 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000580 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581 return true;
582 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000584}
585
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000586bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
587 llvm_unreachable("Translation units are visited directly by Visit()");
588 return false;
589}
590
591bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
592 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
593 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595 return false;
596}
597
598bool CursorVisitor::VisitTagDecl(TagDecl *D) {
599 return VisitDeclContext(D);
600}
601
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000602bool CursorVisitor::VisitClassTemplateSpecializationDecl(
603 ClassTemplateSpecializationDecl *D) {
604 bool ShouldVisitBody = false;
605 switch (D->getSpecializationKind()) {
606 case TSK_Undeclared:
607 case TSK_ImplicitInstantiation:
608 // Nothing to visit
609 return false;
610
611 case TSK_ExplicitInstantiationDeclaration:
612 case TSK_ExplicitInstantiationDefinition:
613 break;
614
615 case TSK_ExplicitSpecialization:
616 ShouldVisitBody = true;
617 break;
618 }
619
620 // Visit the template arguments used in the specialization.
621 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
622 TypeLoc TL = SpecType->getTypeLoc();
623 if (TemplateSpecializationTypeLoc *TSTLoc
624 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
625 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
626 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
627 return true;
628 }
629 }
630
631 if (ShouldVisitBody && VisitCXXRecordDecl(D))
632 return true;
633
634 return false;
635}
636
Douglas Gregor74dbe642010-08-31 19:31:58 +0000637bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
638 ClassTemplatePartialSpecializationDecl *D) {
639 // FIXME: Visit the "outer" template parameter lists on the TagDecl
640 // before visiting these template parameters.
641 if (VisitTemplateParameters(D->getTemplateParameters()))
642 return true;
643
644 // Visit the partial specialization arguments.
645 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
646 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
647 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
648 return true;
649
650 return VisitCXXRecordDecl(D);
651}
652
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000653bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000654 // Visit the default argument.
655 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
656 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
657 if (Visit(DefArg->getTypeLoc()))
658 return true;
659
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000660 return false;
661}
662
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000663bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
664 if (Expr *Init = D->getInitExpr())
665 return Visit(MakeCXCursor(Init, StmtParent, TU));
666 return false;
667}
668
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000669bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
670 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
671 if (Visit(TSInfo->getTypeLoc()))
672 return true;
673
674 return false;
675}
676
Douglas Gregora67e03f2010-09-09 21:42:20 +0000677/// \brief Compare two base or member initializers based on their source order.
678static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
679 CXXBaseOrMemberInitializer const * const *X
680 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
681 CXXBaseOrMemberInitializer const * const *Y
682 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
683
684 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
685 return -1;
686 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
687 return 1;
688 else
689 return 0;
690}
691
Douglas Gregorb1373d02010-01-20 20:59:29 +0000692bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000693 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
694 // Visit the function declaration's syntactic components in the order
695 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000696 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000697 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
698
699 // If we have a function declared directly (without the use of a typedef),
700 // visit just the return type. Otherwise, just visit the function's type
701 // now.
702 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
703 (!FTL && Visit(TL)))
704 return true;
705
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000706 // Visit the nested-name-specifier, if present.
707 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
708 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
709 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000710
711 // Visit the declaration name.
712 if (VisitDeclarationNameInfo(ND->getNameInfo()))
713 return true;
714
715 // FIXME: Visit explicitly-specified template arguments!
716
717 // Visit the function parameters, if we have a function type.
718 if (FTL && VisitFunctionTypeLoc(*FTL, true))
719 return true;
720
721 // FIXME: Attributes?
722 }
723
Douglas Gregora67e03f2010-09-09 21:42:20 +0000724 if (ND->isThisDeclarationADefinition()) {
725 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
726 // Find the initializers that were written in the source.
727 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
728 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
729 IEnd = Constructor->init_end();
730 I != IEnd; ++I) {
731 if (!(*I)->isWritten())
732 continue;
733
734 WrittenInits.push_back(*I);
735 }
736
737 // Sort the initializers in source order
738 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
739 &CompareCXXBaseOrMemberInitializers);
740
741 // Visit the initializers in source order
742 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
743 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000744 if (Init->isAnyMemberInitializer()) {
745 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000746 Init->getMemberLocation(), TU)))
747 return true;
748 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
749 if (Visit(BaseInfo->getTypeLoc()))
750 return true;
751 }
752
753 // Visit the initializer value.
754 if (Expr *Initializer = Init->getInit())
755 if (Visit(MakeCXCursor(Initializer, ND, TU)))
756 return true;
757 }
758 }
759
760 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
761 return true;
762 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000763
Douglas Gregorb1373d02010-01-20 20:59:29 +0000764 return false;
765}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000766
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000767bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
768 if (VisitDeclaratorDecl(D))
769 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000770
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000771 if (Expr *BitWidth = D->getBitWidth())
772 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000773
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000774 return false;
775}
776
777bool CursorVisitor::VisitVarDecl(VarDecl *D) {
778 if (VisitDeclaratorDecl(D))
779 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781 if (Expr *Init = D->getInit())
782 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 return false;
785}
786
Douglas Gregor84b51d72010-09-01 20:16:53 +0000787bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
788 if (VisitDeclaratorDecl(D))
789 return true;
790
791 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
792 if (Expr *DefArg = D->getDefaultArgument())
793 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
794
795 return false;
796}
797
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000798bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
799 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
800 // before visiting these template parameters.
801 if (VisitTemplateParameters(D->getTemplateParameters()))
802 return true;
803
804 return VisitFunctionDecl(D->getTemplatedDecl());
805}
806
Douglas Gregor39d6f072010-08-31 19:02:00 +0000807bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
808 // FIXME: Visit the "outer" template parameter lists on the TagDecl
809 // before visiting these template parameters.
810 if (VisitTemplateParameters(D->getTemplateParameters()))
811 return true;
812
813 return VisitCXXRecordDecl(D->getTemplatedDecl());
814}
815
Douglas Gregor84b51d72010-09-01 20:16:53 +0000816bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
817 if (VisitTemplateParameters(D->getTemplateParameters()))
818 return true;
819
820 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
821 VisitTemplateArgumentLoc(D->getDefaultArgument()))
822 return true;
823
824 return false;
825}
826
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000827bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000828 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
829 if (Visit(TSInfo->getTypeLoc()))
830 return true;
831
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000833 PEnd = ND->param_end();
834 P != PEnd; ++P) {
835 if (Visit(MakeCXCursor(*P, TU)))
836 return true;
837 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839 if (ND->isThisDeclarationADefinition() &&
840 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
841 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 return false;
844}
845
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000846namespace {
847 struct ContainerDeclsSort {
848 SourceManager &SM;
849 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
850 bool operator()(Decl *A, Decl *B) {
851 SourceLocation L_A = A->getLocStart();
852 SourceLocation L_B = B->getLocStart();
853 assert(L_A.isValid() && L_B.isValid());
854 return SM.isBeforeInTranslationUnit(L_A, L_B);
855 }
856 };
857}
858
Douglas Gregora59e3902010-01-21 23:27:09 +0000859bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000860 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
861 // an @implementation can lexically contain Decls that are not properly
862 // nested in the AST. When we identify such cases, we need to retrofit
863 // this nesting here.
864 if (!DI_current)
865 return VisitDeclContext(D);
866
867 // Scan the Decls that immediately come after the container
868 // in the current DeclContext. If any fall within the
869 // container's lexical region, stash them into a vector
870 // for later processing.
871 llvm::SmallVector<Decl *, 24> DeclsInContainer;
872 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000873 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000874 if (EndLoc.isValid()) {
875 DeclContext::decl_iterator next = *DI_current;
876 while (++next != DE_current) {
877 Decl *D_next = *next;
878 if (!D_next)
879 break;
880 SourceLocation L = D_next->getLocStart();
881 if (!L.isValid())
882 break;
883 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
884 *DI_current = next;
885 DeclsInContainer.push_back(D_next);
886 continue;
887 }
888 break;
889 }
890 }
891
892 // The common case.
893 if (DeclsInContainer.empty())
894 return VisitDeclContext(D);
895
896 // Get all the Decls in the DeclContext, and sort them with the
897 // additional ones we've collected. Then visit them.
898 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
899 I!=E; ++I) {
900 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000901 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
902 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000903 continue;
904 DeclsInContainer.push_back(subDecl);
905 }
906
907 // Now sort the Decls so that they appear in lexical order.
908 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
909 ContainerDeclsSort(SM));
910
911 // Now visit the decls.
912 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
913 E = DeclsInContainer.end(); I != E; ++I) {
914 CXCursor Cursor = MakeCXCursor(*I, TU);
915 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
916 if (!V.hasValue())
917 continue;
918 if (!V.getValue())
919 return false;
920 if (Visit(Cursor, true))
921 return true;
922 }
923 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000924}
925
Douglas Gregorb1373d02010-01-20 20:59:29 +0000926bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000927 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
928 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000929 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000930
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000931 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
932 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
933 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000934 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000935 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000936
Douglas Gregora59e3902010-01-21 23:27:09 +0000937 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000938}
939
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000940bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
941 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
942 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
943 E = PID->protocol_end(); I != E; ++I, ++PL)
944 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
945 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000946
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000947 return VisitObjCContainerDecl(PID);
948}
949
Ted Kremenek23173d72010-05-18 21:09:07 +0000950bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000951 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000952 return true;
953
Ted Kremenek23173d72010-05-18 21:09:07 +0000954 // FIXME: This implements a workaround with @property declarations also being
955 // installed in the DeclContext for the @interface. Eventually this code
956 // should be removed.
957 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
958 if (!CDecl || !CDecl->IsClassExtension())
959 return false;
960
961 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
962 if (!ID)
963 return false;
964
965 IdentifierInfo *PropertyId = PD->getIdentifier();
966 ObjCPropertyDecl *prevDecl =
967 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
968
969 if (!prevDecl)
970 return false;
971
972 // Visit synthesized methods since they will be skipped when visiting
973 // the @interface.
974 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000975 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000976 if (Visit(MakeCXCursor(MD, TU)))
977 return true;
978
979 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000980 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000981 if (Visit(MakeCXCursor(MD, TU)))
982 return true;
983
984 return false;
985}
986
Douglas Gregorb1373d02010-01-20 20:59:29 +0000987bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000988 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000989 if (D->getSuperClass() &&
990 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000991 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000992 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000993 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000995 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
996 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
997 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000998 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000999 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001000
Douglas Gregora59e3902010-01-21 23:27:09 +00001001 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001002}
1003
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001004bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1005 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001006}
1007
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001008bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001009 // 'ID' could be null when dealing with invalid code.
1010 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1011 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1012 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001014 return VisitObjCImplDecl(D);
1015}
1016
1017bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1018#if 0
1019 // Issue callbacks for super class.
1020 // FIXME: No source location information!
1021 if (D->getSuperClass() &&
1022 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001023 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001024 TU)))
1025 return true;
1026#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028 return VisitObjCImplDecl(D);
1029}
1030
1031bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1032 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1033 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1034 E = D->protocol_end();
1035 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001036 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001037 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001038
1039 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001040}
1041
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1043 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1044 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1045 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001046
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001047 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001048}
1049
Douglas Gregora4ffd852010-11-17 01:03:52 +00001050bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1051 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1052 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1053
1054 return false;
1055}
1056
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001057bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1058 return VisitDeclContext(D);
1059}
1060
Douglas Gregor69319002010-08-31 23:48:11 +00001061bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001062 // Visit nested-name-specifier.
1063 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1064 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1065 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001066
1067 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1068 D->getTargetNameLoc(), TU));
1069}
1070
Douglas Gregor7e242562010-09-01 19:52:22 +00001071bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001072 // Visit nested-name-specifier.
1073 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1074 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1075 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001076
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001077 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1078 return true;
1079
Douglas Gregor7e242562010-09-01 19:52:22 +00001080 return VisitDeclarationNameInfo(D->getNameInfo());
1081}
1082
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001083bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001084 // Visit nested-name-specifier.
1085 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1086 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1087 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001088
1089 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1090 D->getIdentLocation(), TU));
1091}
1092
Douglas Gregor7e242562010-09-01 19:52:22 +00001093bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001094 // Visit nested-name-specifier.
1095 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1096 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1097 return true;
1098
Douglas Gregor7e242562010-09-01 19:52:22 +00001099 return VisitDeclarationNameInfo(D->getNameInfo());
1100}
1101
1102bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1103 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001104 // Visit nested-name-specifier.
1105 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1106 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1107 return true;
1108
Douglas Gregor7e242562010-09-01 19:52:22 +00001109 return false;
1110}
1111
Douglas Gregor01829d32010-08-31 14:41:23 +00001112bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1113 switch (Name.getName().getNameKind()) {
1114 case clang::DeclarationName::Identifier:
1115 case clang::DeclarationName::CXXLiteralOperatorName:
1116 case clang::DeclarationName::CXXOperatorName:
1117 case clang::DeclarationName::CXXUsingDirective:
1118 return false;
1119
1120 case clang::DeclarationName::CXXConstructorName:
1121 case clang::DeclarationName::CXXDestructorName:
1122 case clang::DeclarationName::CXXConversionFunctionName:
1123 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1124 return Visit(TSInfo->getTypeLoc());
1125 return false;
1126
1127 case clang::DeclarationName::ObjCZeroArgSelector:
1128 case clang::DeclarationName::ObjCOneArgSelector:
1129 case clang::DeclarationName::ObjCMultiArgSelector:
1130 // FIXME: Per-identifier location info?
1131 return false;
1132 }
1133
1134 return false;
1135}
1136
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001137bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1138 SourceRange Range) {
1139 // FIXME: This whole routine is a hack to work around the lack of proper
1140 // source information in nested-name-specifiers (PR5791). Since we do have
1141 // a beginning source location, we can visit the first component of the
1142 // nested-name-specifier, if it's a single-token component.
1143 if (!NNS)
1144 return false;
1145
1146 // Get the first component in the nested-name-specifier.
1147 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1148 NNS = Prefix;
1149
1150 switch (NNS->getKind()) {
1151 case NestedNameSpecifier::Namespace:
1152 // FIXME: The token at this source location might actually have been a
1153 // namespace alias, but we don't model that. Lame!
1154 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1155 TU));
1156
1157 case NestedNameSpecifier::TypeSpec: {
1158 // If the type has a form where we know that the beginning of the source
1159 // range matches up with a reference cursor. Visit the appropriate reference
1160 // cursor.
1161 Type *T = NNS->getAsType();
1162 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1163 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1164 if (const TagType *Tag = dyn_cast<TagType>(T))
1165 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1166 if (const TemplateSpecializationType *TST
1167 = dyn_cast<TemplateSpecializationType>(T))
1168 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1169 break;
1170 }
1171
1172 case NestedNameSpecifier::TypeSpecWithTemplate:
1173 case NestedNameSpecifier::Global:
1174 case NestedNameSpecifier::Identifier:
1175 break;
1176 }
1177
1178 return false;
1179}
1180
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001181bool CursorVisitor::VisitTemplateParameters(
1182 const TemplateParameterList *Params) {
1183 if (!Params)
1184 return false;
1185
1186 for (TemplateParameterList::const_iterator P = Params->begin(),
1187 PEnd = Params->end();
1188 P != PEnd; ++P) {
1189 if (Visit(MakeCXCursor(*P, TU)))
1190 return true;
1191 }
1192
1193 return false;
1194}
1195
Douglas Gregor0b36e612010-08-31 20:37:03 +00001196bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1197 switch (Name.getKind()) {
1198 case TemplateName::Template:
1199 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1200
1201 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001202 // Visit the overloaded template set.
1203 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1204 return true;
1205
Douglas Gregor0b36e612010-08-31 20:37:03 +00001206 return false;
1207
1208 case TemplateName::DependentTemplate:
1209 // FIXME: Visit nested-name-specifier.
1210 return false;
1211
1212 case TemplateName::QualifiedTemplate:
1213 // FIXME: Visit nested-name-specifier.
1214 return Visit(MakeCursorTemplateRef(
1215 Name.getAsQualifiedTemplateName()->getDecl(),
1216 Loc, TU));
1217 }
1218
1219 return false;
1220}
1221
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001222bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1223 switch (TAL.getArgument().getKind()) {
1224 case TemplateArgument::Null:
1225 case TemplateArgument::Integral:
1226 return false;
1227
1228 case TemplateArgument::Pack:
1229 // FIXME: Implement when variadic templates come along.
1230 return false;
1231
1232 case TemplateArgument::Type:
1233 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1234 return Visit(TSInfo->getTypeLoc());
1235 return false;
1236
1237 case TemplateArgument::Declaration:
1238 if (Expr *E = TAL.getSourceDeclExpression())
1239 return Visit(MakeCXCursor(E, StmtParent, TU));
1240 return false;
1241
1242 case TemplateArgument::Expression:
1243 if (Expr *E = TAL.getSourceExpression())
1244 return Visit(MakeCXCursor(E, StmtParent, TU));
1245 return false;
1246
1247 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001248 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1249 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001250 }
1251
1252 return false;
1253}
1254
Ted Kremeneka0536d82010-05-07 01:04:29 +00001255bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1256 return VisitDeclContext(D);
1257}
1258
Douglas Gregor01829d32010-08-31 14:41:23 +00001259bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1260 return Visit(TL.getUnqualifiedLoc());
1261}
1262
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001263bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001264 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001265
1266 // Some builtin types (such as Objective-C's "id", "sel", and
1267 // "Class") have associated declarations. Create cursors for those.
1268 QualType VisitType;
1269 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001270 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001271 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001272 case BuiltinType::Char_U:
1273 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001274 case BuiltinType::Char16:
1275 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001276 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001277 case BuiltinType::UInt:
1278 case BuiltinType::ULong:
1279 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001280 case BuiltinType::UInt128:
1281 case BuiltinType::Char_S:
1282 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001283 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001284 case BuiltinType::Short:
1285 case BuiltinType::Int:
1286 case BuiltinType::Long:
1287 case BuiltinType::LongLong:
1288 case BuiltinType::Int128:
1289 case BuiltinType::Float:
1290 case BuiltinType::Double:
1291 case BuiltinType::LongDouble:
1292 case BuiltinType::NullPtr:
1293 case BuiltinType::Overload:
1294 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001295 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001296
1297 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001298 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001299
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001300 case BuiltinType::ObjCId:
1301 VisitType = Context.getObjCIdType();
1302 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001303
1304 case BuiltinType::ObjCClass:
1305 VisitType = Context.getObjCClassType();
1306 break;
1307
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001308 case BuiltinType::ObjCSel:
1309 VisitType = Context.getObjCSelType();
1310 break;
1311 }
1312
1313 if (!VisitType.isNull()) {
1314 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001315 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001316 TU));
1317 }
1318
1319 return false;
1320}
1321
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001322bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1323 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1324}
1325
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001326bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1327 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1328}
1329
1330bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1331 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1332}
1333
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001334bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001335 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001336 // no context information with which we can match up the depth/index in the
1337 // type to the appropriate
1338 return false;
1339}
1340
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1342 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1343 return true;
1344
John McCallc12c5bb2010-05-15 11:32:37 +00001345 return false;
1346}
1347
1348bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1349 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1350 return true;
1351
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001352 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1353 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1354 TU)))
1355 return true;
1356 }
1357
1358 return false;
1359}
1360
1361bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001362 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001363}
1364
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001365bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1366 return Visit(TL.getInnerLoc());
1367}
1368
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001369bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1370 return Visit(TL.getPointeeLoc());
1371}
1372
1373bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1374 return Visit(TL.getPointeeLoc());
1375}
1376
1377bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1378 return Visit(TL.getPointeeLoc());
1379}
1380
1381bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001382 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001383}
1384
1385bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001386 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387}
1388
Douglas Gregor01829d32010-08-31 14:41:23 +00001389bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1390 bool SkipResultType) {
1391 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392 return true;
1393
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001395 if (Decl *D = TL.getArg(I))
1396 if (Visit(MakeCXCursor(D, TU)))
1397 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001398
1399 return false;
1400}
1401
1402bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1403 if (Visit(TL.getElementLoc()))
1404 return true;
1405
1406 if (Expr *Size = TL.getSizeExpr())
1407 return Visit(MakeCXCursor(Size, StmtParent, TU));
1408
1409 return false;
1410}
1411
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001412bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1413 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001414 // Visit the template name.
1415 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1416 TL.getTemplateNameLoc()))
1417 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001418
1419 // Visit the template arguments.
1420 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1421 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1422 return true;
1423
1424 return false;
1425}
1426
Douglas Gregor2332c112010-01-21 20:48:56 +00001427bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1428 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1429}
1430
1431bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1432 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1433 return Visit(TSInfo->getTypeLoc());
1434
1435 return false;
1436}
1437
Ted Kremenek3064ef92010-08-27 21:34:58 +00001438bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1439 if (D->isDefinition()) {
1440 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1441 E = D->bases_end(); I != E; ++I) {
1442 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1443 return true;
1444 }
1445 }
1446
1447 return VisitTagDecl(D);
1448}
1449
Ted Kremenek09dfa372010-02-18 05:46:33 +00001450bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001451 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1452 i != e; ++i)
1453 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001454 return true;
1455
1456 return false;
1457}
1458
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001459//===----------------------------------------------------------------------===//
1460// Data-recursive visitor methods.
1461//===----------------------------------------------------------------------===//
1462
Ted Kremenek28a71942010-11-13 00:36:47 +00001463namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001464#define DEF_JOB(NAME, DATA, KIND)\
1465class NAME : public VisitorJob {\
1466public:\
1467 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1468 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001469 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001470};
1471
1472DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1473DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001474DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001475DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001476DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1477 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001478#undef DEF_JOB
1479
1480class DeclVisit : public VisitorJob {
1481public:
1482 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1483 VisitorJob(parent, VisitorJob::DeclVisitKind,
1484 d, isFirst ? (void*) 1 : (void*) 0) {}
1485 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001486 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001487 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001488 Decl *get() const { return static_cast<Decl*>(data[0]); }
1489 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001490};
Ted Kremenek035dc412010-11-13 00:36:50 +00001491class TypeLocVisit : public VisitorJob {
1492public:
1493 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1494 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1495 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1496
1497 static bool classof(const VisitorJob *VJ) {
1498 return VJ->getKind() == TypeLocVisitKind;
1499 }
1500
Ted Kremenek82f3c502010-11-15 22:23:26 +00001501 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001502 QualType T = QualType::getFromOpaquePtr(data[0]);
1503 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001504 }
1505};
1506
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001507class LabelRefVisit : public VisitorJob {
1508public:
1509 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1510 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1511 (void*) labelLoc.getRawEncoding()) {}
1512
1513 static bool classof(const VisitorJob *VJ) {
1514 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1515 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001516 LabelStmt *get() const { return static_cast<LabelStmt*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001517 SourceLocation getLoc() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001518 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); }
1519};
1520class NestedNameSpecifierVisit : public VisitorJob {
1521public:
1522 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1523 CXCursor parent)
1524 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
1525 NS, (void*) R.getBegin().getRawEncoding(),
1526 (void*) R.getEnd().getRawEncoding()) {}
1527 static bool classof(const VisitorJob *VJ) {
1528 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1529 }
1530 NestedNameSpecifier *get() const {
1531 return static_cast<NestedNameSpecifier*>(data[0]);
1532 }
1533 SourceRange getSourceRange() const {
1534 SourceLocation A =
1535 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1536 SourceLocation B =
1537 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1538 return SourceRange(A, B);
1539 }
1540};
1541class DeclarationNameInfoVisit : public VisitorJob {
1542public:
1543 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1544 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1545 static bool classof(const VisitorJob *VJ) {
1546 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1547 }
1548 DeclarationNameInfo get() const {
1549 Stmt *S = static_cast<Stmt*>(data[0]);
1550 switch (S->getStmtClass()) {
1551 default:
1552 llvm_unreachable("Unhandled Stmt");
1553 case Stmt::CXXDependentScopeMemberExprClass:
1554 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1555 case Stmt::DependentScopeDeclRefExprClass:
1556 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1557 }
1558 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001559};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001560class MemberRefVisit : public VisitorJob {
1561public:
1562 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1563 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1564 (void*) L.getRawEncoding()) {}
1565 static bool classof(const VisitorJob *VJ) {
1566 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1567 }
1568 FieldDecl *get() const {
1569 return static_cast<FieldDecl*>(data[0]);
1570 }
1571 SourceLocation getLoc() const {
1572 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1573 }
1574};
Ted Kremenek28a71942010-11-13 00:36:47 +00001575class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1576 VisitorWorkList &WL;
1577 CXCursor Parent;
1578public:
1579 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1580 : WL(wl), Parent(parent) {}
1581
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001582 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001583 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001584 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001585 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001586 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001587 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001588 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001589 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001590 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001591 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001592 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001593 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001594 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001595 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001596 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001597 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001598 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001599 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001600 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1601 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001602 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001603 void VisitIfStmt(IfStmt *If);
1604 void VisitInitListExpr(InitListExpr *IE);
1605 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001606 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001607 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001608 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1609 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001610 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001611 void VisitStmt(Stmt *S);
1612 void VisitSwitchStmt(SwitchStmt *S);
1613 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001614 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001615 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001616 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001617 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001618
1619private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001620 void AddDeclarationNameInfo(Stmt *S);
1621 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001622 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001623 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001624 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001625 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001626 void AddTypeLoc(TypeSourceInfo *TI);
1627 void EnqueueChildren(Stmt *S);
1628};
1629} // end anonyous namespace
1630
Ted Kremenekf64d8032010-11-18 00:02:32 +00001631void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1632 // 'S' should always be non-null, since it comes from the
1633 // statement we are visiting.
1634 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1635}
1636void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1637 SourceRange R) {
1638 if (N)
1639 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1640}
Ted Kremenek28a71942010-11-13 00:36:47 +00001641void EnqueueVisitor::AddStmt(Stmt *S) {
1642 if (S)
1643 WL.push_back(StmtVisit(S, Parent));
1644}
Ted Kremenek035dc412010-11-13 00:36:50 +00001645void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001646 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001647 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001648}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001649void EnqueueVisitor::
1650 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1651 if (A)
1652 WL.push_back(ExplicitTemplateArgsVisit(
1653 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1654}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001655void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1656 if (D)
1657 WL.push_back(MemberRefVisit(D, L, Parent));
1658}
Ted Kremenek28a71942010-11-13 00:36:47 +00001659void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1660 if (TI)
1661 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1662 }
1663void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001664 unsigned size = WL.size();
1665 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1666 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001667 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001668 }
1669 if (size == WL.size())
1670 return;
1671 // Now reverse the entries we just added. This will match the DFS
1672 // ordering performed by the worklist.
1673 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1674 std::reverse(I, E);
1675}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001676void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1677 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1678}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001679void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1680 AddDecl(B->getBlockDecl());
1681}
Ted Kremenek28a71942010-11-13 00:36:47 +00001682void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1683 EnqueueChildren(E);
1684 AddTypeLoc(E->getTypeSourceInfo());
1685}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001686void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1687 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1688 E = S->body_rend(); I != E; ++I) {
1689 AddStmt(*I);
1690 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001691}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001692void EnqueueVisitor::
1693VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1694 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1695 AddDeclarationNameInfo(E);
1696 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1697 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1698 if (!E->isImplicitAccess())
1699 AddStmt(E->getBase());
1700}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001701void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1702 // Enqueue the initializer or constructor arguments.
1703 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1704 AddStmt(E->getConstructorArg(I-1));
1705 // Enqueue the array size, if any.
1706 AddStmt(E->getArraySize());
1707 // Enqueue the allocated type.
1708 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1709 // Enqueue the placement arguments.
1710 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1711 AddStmt(E->getPlacementArg(I-1));
1712}
Ted Kremenek28a71942010-11-13 00:36:47 +00001713void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001714 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1715 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001716 AddStmt(CE->getCallee());
1717 AddStmt(CE->getArg(0));
1718}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001719void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1720 // Visit the name of the type being destroyed.
1721 AddTypeLoc(E->getDestroyedTypeInfo());
1722 // Visit the scope type that looks disturbingly like the nested-name-specifier
1723 // but isn't.
1724 AddTypeLoc(E->getScopeTypeInfo());
1725 // Visit the nested-name-specifier.
1726 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1727 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1728 // Visit base expression.
1729 AddStmt(E->getBase());
1730}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001731void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1732 AddTypeLoc(E->getTypeSourceInfo());
1733}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001734void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1735 EnqueueChildren(E);
1736 AddTypeLoc(E->getTypeSourceInfo());
1737}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001738void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1739 EnqueueChildren(E);
1740 if (E->isTypeOperand())
1741 AddTypeLoc(E->getTypeOperandSourceInfo());
1742}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001743
1744void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1745 *E) {
1746 EnqueueChildren(E);
1747 AddTypeLoc(E->getTypeSourceInfo());
1748}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001749void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1750 EnqueueChildren(E);
1751 if (E->isTypeOperand())
1752 AddTypeLoc(E->getTypeOperandSourceInfo());
1753}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001754void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001755 if (DR->hasExplicitTemplateArgs()) {
1756 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1757 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001758 WL.push_back(DeclRefExprParts(DR, Parent));
1759}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001760void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1761 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1762 AddDeclarationNameInfo(E);
1763 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1764 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1765}
Ted Kremenek035dc412010-11-13 00:36:50 +00001766void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1767 unsigned size = WL.size();
1768 bool isFirst = true;
1769 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1770 D != DEnd; ++D) {
1771 AddDecl(*D, isFirst);
1772 isFirst = false;
1773 }
1774 if (size == WL.size())
1775 return;
1776 // Now reverse the entries we just added. This will match the DFS
1777 // ordering performed by the worklist.
1778 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1779 std::reverse(I, E);
1780}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001781void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1782 AddStmt(E->getInit());
1783 typedef DesignatedInitExpr::Designator Designator;
1784 for (DesignatedInitExpr::reverse_designators_iterator
1785 D = E->designators_rbegin(), DEnd = E->designators_rend();
1786 D != DEnd; ++D) {
1787 if (D->isFieldDesignator()) {
1788 if (FieldDecl *Field = D->getField())
1789 AddMemberRef(Field, D->getFieldLoc());
1790 continue;
1791 }
1792 if (D->isArrayDesignator()) {
1793 AddStmt(E->getArrayIndex(*D));
1794 continue;
1795 }
1796 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1797 AddStmt(E->getArrayRangeEnd(*D));
1798 AddStmt(E->getArrayRangeStart(*D));
1799 }
1800}
Ted Kremenek28a71942010-11-13 00:36:47 +00001801void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1802 EnqueueChildren(E);
1803 AddTypeLoc(E->getTypeInfoAsWritten());
1804}
1805void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1806 AddStmt(FS->getBody());
1807 AddStmt(FS->getInc());
1808 AddStmt(FS->getCond());
1809 AddDecl(FS->getConditionVariable());
1810 AddStmt(FS->getInit());
1811}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001812void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1813 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1814}
Ted Kremenek28a71942010-11-13 00:36:47 +00001815void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1816 AddStmt(If->getElse());
1817 AddStmt(If->getThen());
1818 AddStmt(If->getCond());
1819 AddDecl(If->getConditionVariable());
1820}
1821void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1822 // We care about the syntactic form of the initializer list, only.
1823 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1824 IE = Syntactic;
1825 EnqueueChildren(IE);
1826}
1827void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001828 WL.push_back(MemberExprParts(M, Parent));
1829
1830 // If the base of the member access expression is an implicit 'this', don't
1831 // visit it.
1832 // FIXME: If we ever want to show these implicit accesses, this will be
1833 // unfortunate. However, clang_getCursor() relies on this behavior.
1834 if (CXXThisExpr *This
1835 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1836 if (This->isImplicit())
1837 return;
1838
Ted Kremenek28a71942010-11-13 00:36:47 +00001839 AddStmt(M->getBase());
1840}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001841void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1842 AddTypeLoc(E->getEncodedTypeSourceInfo());
1843}
Ted Kremenek28a71942010-11-13 00:36:47 +00001844void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1845 EnqueueChildren(M);
1846 AddTypeLoc(M->getClassReceiverTypeInfo());
1847}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001848void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1849 // Visit the components of the offsetof expression.
1850 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1851 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1852 const OffsetOfNode &Node = E->getComponent(I-1);
1853 switch (Node.getKind()) {
1854 case OffsetOfNode::Array:
1855 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1856 break;
1857 case OffsetOfNode::Field:
1858 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1859 break;
1860 case OffsetOfNode::Identifier:
1861 case OffsetOfNode::Base:
1862 continue;
1863 }
1864 }
1865 // Visit the type into which we're computing the offset.
1866 AddTypeLoc(E->getTypeSourceInfo());
1867}
Ted Kremenek28a71942010-11-13 00:36:47 +00001868void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001869 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001870 WL.push_back(OverloadExprParts(E, Parent));
1871}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001872void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1873 EnqueueChildren(E);
1874 if (E->isArgumentType())
1875 AddTypeLoc(E->getArgumentTypeInfo());
1876}
Ted Kremenek28a71942010-11-13 00:36:47 +00001877void EnqueueVisitor::VisitStmt(Stmt *S) {
1878 EnqueueChildren(S);
1879}
1880void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1881 AddStmt(S->getBody());
1882 AddStmt(S->getCond());
1883 AddDecl(S->getConditionVariable());
1884}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001885
Ted Kremenek28a71942010-11-13 00:36:47 +00001886void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1887 AddStmt(W->getBody());
1888 AddStmt(W->getCond());
1889 AddDecl(W->getConditionVariable());
1890}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001891void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1892 AddTypeLoc(E->getQueriedTypeSourceInfo());
1893}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001894
1895void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00001896 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00001897 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00001898}
1899
Ted Kremenek28a71942010-11-13 00:36:47 +00001900void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1901 VisitOverloadExpr(U);
1902 if (!U->isImplicitAccess())
1903 AddStmt(U->getBase());
1904}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001905void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1906 AddStmt(E->getSubExpr());
1907 AddTypeLoc(E->getWrittenTypeInfo());
1908}
Ted Kremenek60458782010-11-12 21:34:16 +00001909
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001910void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001911 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001912}
1913
1914bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1915 if (RegionOfInterest.isValid()) {
1916 SourceRange Range = getRawCursorExtent(C);
1917 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1918 return false;
1919 }
1920 return true;
1921}
1922
1923bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1924 while (!WL.empty()) {
1925 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001926 VisitorJob LI = WL.back();
1927 WL.pop_back();
1928
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001929 // Set the Parent field, then back to its old value once we're done.
1930 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1931
1932 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001933 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001934 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001935 if (!D)
1936 continue;
1937
1938 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001939 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001940 return true;
1941
1942 continue;
1943 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001944 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1945 const ExplicitTemplateArgumentList *ArgList =
1946 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1947 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1948 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1949 Arg != ArgEnd; ++Arg) {
1950 if (VisitTemplateArgumentLoc(*Arg))
1951 return true;
1952 }
1953 continue;
1954 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001955 case VisitorJob::TypeLocVisitKind: {
1956 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001957 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001958 return true;
1959 continue;
1960 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001961 case VisitorJob::LabelRefVisitKind: {
1962 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1963 if (Visit(MakeCursorLabelRef(LS,
1964 cast<LabelRefVisit>(&LI)->getLoc(),
1965 TU)))
1966 return true;
1967 continue;
1968 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001969 case VisitorJob::NestedNameSpecifierVisitKind: {
1970 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
1971 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
1972 return true;
1973 continue;
1974 }
1975 case VisitorJob::DeclarationNameInfoVisitKind: {
1976 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
1977 ->get()))
1978 return true;
1979 continue;
1980 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00001981 case VisitorJob::MemberRefVisitKind: {
1982 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
1983 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
1984 return true;
1985 continue;
1986 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001987 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001988 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001989 if (!S)
1990 continue;
1991
Ted Kremenekf1107452010-11-12 18:26:56 +00001992 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001993 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001994 if (!IsInRegionOfInterest(Cursor))
1995 continue;
1996 switch (Visitor(Cursor, Parent, ClientData)) {
1997 case CXChildVisit_Break: return true;
1998 case CXChildVisit_Continue: break;
1999 case CXChildVisit_Recurse:
2000 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002001 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002002 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002003 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002004 }
2005 case VisitorJob::MemberExprPartsKind: {
2006 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002007 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002008
2009 // Visit the nested-name-specifier
2010 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2011 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2012 return true;
2013
2014 // Visit the declaration name.
2015 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2016 return true;
2017
2018 // Visit the explicitly-specified template arguments, if any.
2019 if (M->hasExplicitTemplateArgs()) {
2020 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2021 *ArgEnd = Arg + M->getNumTemplateArgs();
2022 Arg != ArgEnd; ++Arg) {
2023 if (VisitTemplateArgumentLoc(*Arg))
2024 return true;
2025 }
2026 }
2027 continue;
2028 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002029 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002030 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002031 // Visit nested-name-specifier, if present.
2032 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2033 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2034 return true;
2035 // Visit declaration name.
2036 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2037 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002038 continue;
2039 }
Ted Kremenek60458782010-11-12 21:34:16 +00002040 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002041 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002042 // Visit the nested-name-specifier.
2043 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2044 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2045 return true;
2046 // Visit the declaration name.
2047 if (VisitDeclarationNameInfo(O->getNameInfo()))
2048 return true;
2049 // Visit the overloaded declaration reference.
2050 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2051 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002052 continue;
2053 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002054 }
2055 }
2056 return false;
2057}
2058
Ted Kremenekcdba6592010-11-18 00:42:18 +00002059bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002060 VisitorWorkList *WL = 0;
2061 if (!WorkListFreeList.empty()) {
2062 WL = WorkListFreeList.back();
2063 WL->clear();
2064 WorkListFreeList.pop_back();
2065 }
2066 else {
2067 WL = new VisitorWorkList();
2068 WorkListCache.push_back(WL);
2069 }
2070 EnqueueWorkList(*WL, S);
2071 bool result = RunVisitorWorkList(*WL);
2072 WorkListFreeList.push_back(WL);
2073 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002074}
2075
2076//===----------------------------------------------------------------------===//
2077// Misc. API hooks.
2078//===----------------------------------------------------------------------===//
2079
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002080static llvm::sys::Mutex EnableMultithreadingMutex;
2081static bool EnabledMultithreading;
2082
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002083extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002084CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2085 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002086 // Disable pretty stack trace functionality, which will otherwise be a very
2087 // poor citizen of the world and set up all sorts of signal handlers.
2088 llvm::DisablePrettyStackTrace = true;
2089
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002090 // We use crash recovery to make some of our APIs more reliable, implicitly
2091 // enable it.
2092 llvm::CrashRecoveryContext::Enable();
2093
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002094 // Enable support for multithreading in LLVM.
2095 {
2096 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2097 if (!EnabledMultithreading) {
2098 llvm::llvm_start_multithreaded();
2099 EnabledMultithreading = true;
2100 }
2101 }
2102
Douglas Gregora030b7c2010-01-22 20:35:53 +00002103 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002104 if (excludeDeclarationsFromPCH)
2105 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002106 if (displayDiagnostics)
2107 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002108 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002109}
2110
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002111void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002112 if (CIdx)
2113 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002114}
2115
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002116CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002117 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002118 if (!CIdx)
2119 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002120
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002121 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002122 FileSystemOptions FileSystemOpts;
2123 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002124
Douglas Gregor28019772010-04-05 23:52:57 +00002125 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002126 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002127 CXXIdx->getOnlyLocalDecls(),
2128 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002129 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002130}
2131
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002132unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002133 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002134 CXTranslationUnit_CacheCompletionResults |
2135 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002136}
2137
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002138CXTranslationUnit
2139clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2140 const char *source_filename,
2141 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002142 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002143 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002144 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002145 return clang_parseTranslationUnit(CIdx, source_filename,
2146 command_line_args, num_command_line_args,
2147 unsaved_files, num_unsaved_files,
2148 CXTranslationUnit_DetailedPreprocessingRecord);
2149}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002150
2151struct ParseTranslationUnitInfo {
2152 CXIndex CIdx;
2153 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002154 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002155 int num_command_line_args;
2156 struct CXUnsavedFile *unsaved_files;
2157 unsigned num_unsaved_files;
2158 unsigned options;
2159 CXTranslationUnit result;
2160};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002161static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002162 ParseTranslationUnitInfo *PTUI =
2163 static_cast<ParseTranslationUnitInfo*>(UserData);
2164 CXIndex CIdx = PTUI->CIdx;
2165 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002166 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002167 int num_command_line_args = PTUI->num_command_line_args;
2168 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2169 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2170 unsigned options = PTUI->options;
2171 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002172
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002173 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002174 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002175
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002176 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2177
Douglas Gregor44c181a2010-07-23 00:33:23 +00002178 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002179 bool CompleteTranslationUnit
2180 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002181 bool CacheCodeCompetionResults
2182 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002183 bool CXXPrecompilePreamble
2184 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2185 bool CXXChainedPCH
2186 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002187
Douglas Gregor5352ac02010-01-28 00:27:43 +00002188 // Configure the diagnostics.
2189 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002190 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2191 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002192
Douglas Gregor4db64a42010-01-23 00:14:00 +00002193 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2194 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002195 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002196 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002197 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002198 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2199 Buffer));
2200 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002201
Douglas Gregorb10daed2010-10-11 16:52:23 +00002202 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002203
Ted Kremenek139ba862009-10-22 00:03:57 +00002204 // The 'source_filename' argument is optional. If the caller does not
2205 // specify it then it is assumed that the source file is specified
2206 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002207 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002208 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002209
2210 // Since the Clang C library is primarily used by batch tools dealing with
2211 // (often very broken) source code, where spell-checking can have a
2212 // significant negative impact on performance (particularly when
2213 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002214 // Only do this if we haven't found a spell-checking-related argument.
2215 bool FoundSpellCheckingArgument = false;
2216 for (int I = 0; I != num_command_line_args; ++I) {
2217 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2218 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2219 FoundSpellCheckingArgument = true;
2220 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002221 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002222 }
2223 if (!FoundSpellCheckingArgument)
2224 Args.push_back("-fno-spell-checking");
2225
2226 Args.insert(Args.end(), command_line_args,
2227 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002228
Douglas Gregor44c181a2010-07-23 00:33:23 +00002229 // Do we need the detailed preprocessing record?
2230 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002231 Args.push_back("-Xclang");
2232 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002233 }
2234
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002235 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002236 llvm::OwningPtr<ASTUnit> Unit(
2237 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2238 Diags,
2239 CXXIdx->getClangResourcesPath(),
2240 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002241 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002242 RemappedFiles.data(),
2243 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002244 PrecompilePreamble,
2245 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002246 CacheCodeCompetionResults,
2247 CXXPrecompilePreamble,
2248 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002249
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002250 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002251 // Make sure to check that 'Unit' is non-NULL.
2252 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2253 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2254 DEnd = Unit->stored_diag_end();
2255 D != DEnd; ++D) {
2256 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2257 CXString Msg = clang_formatDiagnostic(&Diag,
2258 clang_defaultDiagnosticDisplayOptions());
2259 fprintf(stderr, "%s\n", clang_getCString(Msg));
2260 clang_disposeString(Msg);
2261 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002262#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002263 // On Windows, force a flush, since there may be multiple copies of
2264 // stderr and stdout in the file system, all with different buffers
2265 // but writing to the same device.
2266 fflush(stderr);
2267#endif
2268 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002269 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002270
Ted Kremeneka60ed472010-11-16 08:15:36 +00002271 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002272}
2273CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2274 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002275 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002276 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002277 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002278 unsigned num_unsaved_files,
2279 unsigned options) {
2280 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002281 num_command_line_args, unsaved_files,
2282 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002283 llvm::CrashRecoveryContext CRC;
2284
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002285 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002286 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2287 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2288 fprintf(stderr, " 'command_line_args' : [");
2289 for (int i = 0; i != num_command_line_args; ++i) {
2290 if (i)
2291 fprintf(stderr, ", ");
2292 fprintf(stderr, "'%s'", command_line_args[i]);
2293 }
2294 fprintf(stderr, "],\n");
2295 fprintf(stderr, " 'unsaved_files' : [");
2296 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2297 if (i)
2298 fprintf(stderr, ", ");
2299 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2300 unsaved_files[i].Length);
2301 }
2302 fprintf(stderr, "],\n");
2303 fprintf(stderr, " 'options' : %d,\n", options);
2304 fprintf(stderr, "}\n");
2305
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002306 return 0;
2307 }
2308
2309 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002310}
2311
Douglas Gregor19998442010-08-13 15:35:05 +00002312unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2313 return CXSaveTranslationUnit_None;
2314}
2315
2316int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2317 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002318 if (!TU)
2319 return 1;
2320
Ted Kremeneka60ed472010-11-16 08:15:36 +00002321 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002322}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002323
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002324void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002325 if (CTUnit) {
2326 // If the translation unit has been marked as unsafe to free, just discard
2327 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002328 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002329 return;
2330
Ted Kremeneka60ed472010-11-16 08:15:36 +00002331 delete static_cast<ASTUnit *>(CTUnit->TUData);
2332 disposeCXStringPool(CTUnit->StringPool);
2333 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002334 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002335}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002336
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002337unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2338 return CXReparse_None;
2339}
2340
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002341struct ReparseTranslationUnitInfo {
2342 CXTranslationUnit TU;
2343 unsigned num_unsaved_files;
2344 struct CXUnsavedFile *unsaved_files;
2345 unsigned options;
2346 int result;
2347};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002348
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002349static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002350 ReparseTranslationUnitInfo *RTUI =
2351 static_cast<ReparseTranslationUnitInfo*>(UserData);
2352 CXTranslationUnit TU = RTUI->TU;
2353 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2354 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2355 unsigned options = RTUI->options;
2356 (void) options;
2357 RTUI->result = 1;
2358
Douglas Gregorabc563f2010-07-19 21:46:24 +00002359 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002360 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002361
Ted Kremeneka60ed472010-11-16 08:15:36 +00002362 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002363 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002364
2365 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2366 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2367 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2368 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002369 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002370 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2371 Buffer));
2372 }
2373
Douglas Gregor593b0c12010-09-23 18:47:53 +00002374 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2375 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002376}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002377
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002378int clang_reparseTranslationUnit(CXTranslationUnit TU,
2379 unsigned num_unsaved_files,
2380 struct CXUnsavedFile *unsaved_files,
2381 unsigned options) {
2382 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2383 options, 0 };
2384 llvm::CrashRecoveryContext CRC;
2385
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002386 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002387 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002388 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002389 return 1;
2390 }
2391
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002392
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002393 return RTUI.result;
2394}
2395
Douglas Gregordf95a132010-08-09 20:45:32 +00002396
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002397CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002398 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002399 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002400
Ted Kremeneka60ed472010-11-16 08:15:36 +00002401 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002402 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002403}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002404
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002405CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002406 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002407 return Result;
2408}
2409
Ted Kremenekfb480492010-01-13 21:46:36 +00002410} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002411
Ted Kremenekfb480492010-01-13 21:46:36 +00002412//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002413// CXSourceLocation and CXSourceRange Operations.
2414//===----------------------------------------------------------------------===//
2415
Douglas Gregorb9790342010-01-22 21:44:22 +00002416extern "C" {
2417CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002418 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002419 return Result;
2420}
2421
2422unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002423 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2424 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2425 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002426}
2427
2428CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2429 CXFile file,
2430 unsigned line,
2431 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002432 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002433 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002434
Ted Kremeneka60ed472010-11-16 08:15:36 +00002435 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002436 SourceLocation SLoc
2437 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002438 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002439 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002440 if (SLoc.isInvalid()) return clang_getNullLocation();
2441
2442 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2443}
2444
2445CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2446 CXFile file,
2447 unsigned offset) {
2448 if (!tu || !file)
2449 return clang_getNullLocation();
2450
Ted Kremeneka60ed472010-11-16 08:15:36 +00002451 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002452 SourceLocation Start
2453 = CXXUnit->getSourceManager().getLocation(
2454 static_cast<const FileEntry *>(file),
2455 1, 1);
2456 if (Start.isInvalid()) return clang_getNullLocation();
2457
2458 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2459
2460 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002461
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002462 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002463}
2464
Douglas Gregor5352ac02010-01-28 00:27:43 +00002465CXSourceRange clang_getNullRange() {
2466 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2467 return Result;
2468}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002469
Douglas Gregor5352ac02010-01-28 00:27:43 +00002470CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2471 if (begin.ptr_data[0] != end.ptr_data[0] ||
2472 begin.ptr_data[1] != end.ptr_data[1])
2473 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002474
2475 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002476 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002477 return Result;
2478}
2479
Douglas Gregor46766dc2010-01-26 19:19:08 +00002480void clang_getInstantiationLocation(CXSourceLocation location,
2481 CXFile *file,
2482 unsigned *line,
2483 unsigned *column,
2484 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002485 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2486
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002487 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002488 if (file)
2489 *file = 0;
2490 if (line)
2491 *line = 0;
2492 if (column)
2493 *column = 0;
2494 if (offset)
2495 *offset = 0;
2496 return;
2497 }
2498
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002499 const SourceManager &SM =
2500 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002501 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002502
2503 if (file)
2504 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2505 if (line)
2506 *line = SM.getInstantiationLineNumber(InstLoc);
2507 if (column)
2508 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002509 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002510 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002511}
2512
Douglas Gregora9b06d42010-11-09 06:24:54 +00002513void clang_getSpellingLocation(CXSourceLocation location,
2514 CXFile *file,
2515 unsigned *line,
2516 unsigned *column,
2517 unsigned *offset) {
2518 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2519
2520 if (!location.ptr_data[0] || Loc.isInvalid()) {
2521 if (file)
2522 *file = 0;
2523 if (line)
2524 *line = 0;
2525 if (column)
2526 *column = 0;
2527 if (offset)
2528 *offset = 0;
2529 return;
2530 }
2531
2532 const SourceManager &SM =
2533 *static_cast<const SourceManager*>(location.ptr_data[0]);
2534 SourceLocation SpellLoc = Loc;
2535 if (SpellLoc.isMacroID()) {
2536 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2537 if (SimpleSpellingLoc.isFileID() &&
2538 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2539 SpellLoc = SimpleSpellingLoc;
2540 else
2541 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2542 }
2543
2544 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2545 FileID FID = LocInfo.first;
2546 unsigned FileOffset = LocInfo.second;
2547
2548 if (file)
2549 *file = (void *)SM.getFileEntryForID(FID);
2550 if (line)
2551 *line = SM.getLineNumber(FID, FileOffset);
2552 if (column)
2553 *column = SM.getColumnNumber(FID, FileOffset);
2554 if (offset)
2555 *offset = FileOffset;
2556}
2557
Douglas Gregor1db19de2010-01-19 21:36:55 +00002558CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002559 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002560 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002561 return Result;
2562}
2563
2564CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002565 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002566 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002567 return Result;
2568}
2569
Douglas Gregorb9790342010-01-22 21:44:22 +00002570} // end: extern "C"
2571
Douglas Gregor1db19de2010-01-19 21:36:55 +00002572//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002573// CXFile Operations.
2574//===----------------------------------------------------------------------===//
2575
2576extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002577CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002578 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002579 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002580
Steve Naroff88145032009-10-27 14:35:18 +00002581 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002582 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002583}
2584
2585time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002586 if (!SFile)
2587 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002588
Steve Naroff88145032009-10-27 14:35:18 +00002589 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2590 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002591}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
Douglas Gregorb9790342010-01-22 21:44:22 +00002593CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2594 if (!tu)
2595 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002596
Ted Kremeneka60ed472010-11-16 08:15:36 +00002597 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Douglas Gregorb9790342010-01-22 21:44:22 +00002599 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002600 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002601}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002602
Ted Kremenekfb480492010-01-13 21:46:36 +00002603} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002604
Ted Kremenekfb480492010-01-13 21:46:36 +00002605//===----------------------------------------------------------------------===//
2606// CXCursor Operations.
2607//===----------------------------------------------------------------------===//
2608
Ted Kremenekfb480492010-01-13 21:46:36 +00002609static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002610 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2611 return getDeclFromExpr(CE->getSubExpr());
2612
Ted Kremenekfb480492010-01-13 21:46:36 +00002613 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2614 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002615 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2616 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002617 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2618 return ME->getMemberDecl();
2619 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2620 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002621 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002622 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002623
Ted Kremenekfb480492010-01-13 21:46:36 +00002624 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2625 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002626 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2627 if (!CE->isElidable())
2628 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002629 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2630 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002631
Douglas Gregordb1314e2010-10-01 21:11:22 +00002632 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2633 return PE->getProtocol();
2634
Ted Kremenekfb480492010-01-13 21:46:36 +00002635 return 0;
2636}
2637
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002638static SourceLocation getLocationFromExpr(Expr *E) {
2639 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2640 return /*FIXME:*/Msg->getLeftLoc();
2641 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2642 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002643 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2644 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002645 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2646 return Member->getMemberLoc();
2647 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2648 return Ivar->getLocation();
2649 return E->getLocStart();
2650}
2651
Ted Kremenekfb480492010-01-13 21:46:36 +00002652extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002653
2654unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002655 CXCursorVisitor visitor,
2656 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002657 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2658 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002659 return CursorVis.VisitChildren(parent);
2660}
2661
David Chisnall3387c652010-11-03 14:12:26 +00002662#ifndef __has_feature
2663#define __has_feature(x) 0
2664#endif
2665#if __has_feature(blocks)
2666typedef enum CXChildVisitResult
2667 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2668
2669static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2670 CXClientData client_data) {
2671 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2672 return block(cursor, parent);
2673}
2674#else
2675// If we are compiled with a compiler that doesn't have native blocks support,
2676// define and call the block manually, so the
2677typedef struct _CXChildVisitResult
2678{
2679 void *isa;
2680 int flags;
2681 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002682 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2683 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002684} *CXCursorVisitorBlock;
2685
2686static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2687 CXClientData client_data) {
2688 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2689 return block->invoke(block, cursor, parent);
2690}
2691#endif
2692
2693
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002694unsigned clang_visitChildrenWithBlock(CXCursor parent,
2695 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002696 return clang_visitChildren(parent, visitWithBlock, block);
2697}
2698
Douglas Gregor78205d42010-01-20 21:45:58 +00002699static CXString getDeclSpelling(Decl *D) {
2700 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002701 if (!ND) {
2702 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2703 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2704 return createCXString(Property->getIdentifier()->getName());
2705
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002706 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002707 }
2708
Douglas Gregor78205d42010-01-20 21:45:58 +00002709 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002710 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002711
Douglas Gregor78205d42010-01-20 21:45:58 +00002712 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2713 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2714 // and returns different names. NamedDecl returns the class name and
2715 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002716 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002717
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002718 if (isa<UsingDirectiveDecl>(D))
2719 return createCXString("");
2720
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002721 llvm::SmallString<1024> S;
2722 llvm::raw_svector_ostream os(S);
2723 ND->printName(os);
2724
2725 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002726}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002727
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002728CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002729 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002730 return clang_getTranslationUnitSpelling(
2731 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002732
Steve Narofff334b4e2009-09-02 18:26:48 +00002733 if (clang_isReference(C.kind)) {
2734 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002735 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002736 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002737 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002738 }
2739 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002740 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002741 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002742 }
2743 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002744 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002745 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002746 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002747 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002748 case CXCursor_CXXBaseSpecifier: {
2749 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2750 return createCXString(B->getType().getAsString());
2751 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002752 case CXCursor_TypeRef: {
2753 TypeDecl *Type = getCursorTypeRef(C).first;
2754 assert(Type && "Missing type decl");
2755
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002756 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2757 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002758 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002759 case CXCursor_TemplateRef: {
2760 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002761 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002762
2763 return createCXString(Template->getNameAsString());
2764 }
Douglas Gregor69319002010-08-31 23:48:11 +00002765
2766 case CXCursor_NamespaceRef: {
2767 NamedDecl *NS = getCursorNamespaceRef(C).first;
2768 assert(NS && "Missing namespace decl");
2769
2770 return createCXString(NS->getNameAsString());
2771 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002772
Douglas Gregora67e03f2010-09-09 21:42:20 +00002773 case CXCursor_MemberRef: {
2774 FieldDecl *Field = getCursorMemberRef(C).first;
2775 assert(Field && "Missing member decl");
2776
2777 return createCXString(Field->getNameAsString());
2778 }
2779
Douglas Gregor36897b02010-09-10 00:22:18 +00002780 case CXCursor_LabelRef: {
2781 LabelStmt *Label = getCursorLabelRef(C).first;
2782 assert(Label && "Missing label");
2783
2784 return createCXString(Label->getID()->getName());
2785 }
2786
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002787 case CXCursor_OverloadedDeclRef: {
2788 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2789 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2790 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2791 return createCXString(ND->getNameAsString());
2792 return createCXString("");
2793 }
2794 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2795 return createCXString(E->getName().getAsString());
2796 OverloadedTemplateStorage *Ovl
2797 = Storage.get<OverloadedTemplateStorage*>();
2798 if (Ovl->size() == 0)
2799 return createCXString("");
2800 return createCXString((*Ovl->begin())->getNameAsString());
2801 }
2802
Daniel Dunbaracca7252009-11-30 20:42:49 +00002803 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002804 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002805 }
2806 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002807
2808 if (clang_isExpression(C.kind)) {
2809 Decl *D = getDeclFromExpr(getCursorExpr(C));
2810 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002811 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002812 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002813 }
2814
Douglas Gregor36897b02010-09-10 00:22:18 +00002815 if (clang_isStatement(C.kind)) {
2816 Stmt *S = getCursorStmt(C);
2817 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2818 return createCXString(Label->getID()->getName());
2819
2820 return createCXString("");
2821 }
2822
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002823 if (C.kind == CXCursor_MacroInstantiation)
2824 return createCXString(getCursorMacroInstantiation(C)->getName()
2825 ->getNameStart());
2826
Douglas Gregor572feb22010-03-18 18:04:21 +00002827 if (C.kind == CXCursor_MacroDefinition)
2828 return createCXString(getCursorMacroDefinition(C)->getName()
2829 ->getNameStart());
2830
Douglas Gregorecdcb882010-10-20 22:00:55 +00002831 if (C.kind == CXCursor_InclusionDirective)
2832 return createCXString(getCursorInclusionDirective(C)->getFileName());
2833
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002834 if (clang_isDeclaration(C.kind))
2835 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002836
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002837 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002838}
2839
Douglas Gregor358559d2010-10-02 22:49:11 +00002840CXString clang_getCursorDisplayName(CXCursor C) {
2841 if (!clang_isDeclaration(C.kind))
2842 return clang_getCursorSpelling(C);
2843
2844 Decl *D = getCursorDecl(C);
2845 if (!D)
2846 return createCXString("");
2847
2848 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2849 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2850 D = FunTmpl->getTemplatedDecl();
2851
2852 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2853 llvm::SmallString<64> Str;
2854 llvm::raw_svector_ostream OS(Str);
2855 OS << Function->getNameAsString();
2856 if (Function->getPrimaryTemplate())
2857 OS << "<>";
2858 OS << "(";
2859 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2860 if (I)
2861 OS << ", ";
2862 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2863 }
2864
2865 if (Function->isVariadic()) {
2866 if (Function->getNumParams())
2867 OS << ", ";
2868 OS << "...";
2869 }
2870 OS << ")";
2871 return createCXString(OS.str());
2872 }
2873
2874 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2875 llvm::SmallString<64> Str;
2876 llvm::raw_svector_ostream OS(Str);
2877 OS << ClassTemplate->getNameAsString();
2878 OS << "<";
2879 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2880 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2881 if (I)
2882 OS << ", ";
2883
2884 NamedDecl *Param = Params->getParam(I);
2885 if (Param->getIdentifier()) {
2886 OS << Param->getIdentifier()->getName();
2887 continue;
2888 }
2889
2890 // There is no parameter name, which makes this tricky. Try to come up
2891 // with something useful that isn't too long.
2892 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2893 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2894 else if (NonTypeTemplateParmDecl *NTTP
2895 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2896 OS << NTTP->getType().getAsString(Policy);
2897 else
2898 OS << "template<...> class";
2899 }
2900
2901 OS << ">";
2902 return createCXString(OS.str());
2903 }
2904
2905 if (ClassTemplateSpecializationDecl *ClassSpec
2906 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2907 // If the type was explicitly written, use that.
2908 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2909 return createCXString(TSInfo->getType().getAsString(Policy));
2910
2911 llvm::SmallString<64> Str;
2912 llvm::raw_svector_ostream OS(Str);
2913 OS << ClassSpec->getNameAsString();
2914 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002915 ClassSpec->getTemplateArgs().data(),
2916 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002917 Policy);
2918 return createCXString(OS.str());
2919 }
2920
2921 return clang_getCursorSpelling(C);
2922}
2923
Ted Kremeneke68fff62010-02-17 00:41:32 +00002924CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002925 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002926 case CXCursor_FunctionDecl:
2927 return createCXString("FunctionDecl");
2928 case CXCursor_TypedefDecl:
2929 return createCXString("TypedefDecl");
2930 case CXCursor_EnumDecl:
2931 return createCXString("EnumDecl");
2932 case CXCursor_EnumConstantDecl:
2933 return createCXString("EnumConstantDecl");
2934 case CXCursor_StructDecl:
2935 return createCXString("StructDecl");
2936 case CXCursor_UnionDecl:
2937 return createCXString("UnionDecl");
2938 case CXCursor_ClassDecl:
2939 return createCXString("ClassDecl");
2940 case CXCursor_FieldDecl:
2941 return createCXString("FieldDecl");
2942 case CXCursor_VarDecl:
2943 return createCXString("VarDecl");
2944 case CXCursor_ParmDecl:
2945 return createCXString("ParmDecl");
2946 case CXCursor_ObjCInterfaceDecl:
2947 return createCXString("ObjCInterfaceDecl");
2948 case CXCursor_ObjCCategoryDecl:
2949 return createCXString("ObjCCategoryDecl");
2950 case CXCursor_ObjCProtocolDecl:
2951 return createCXString("ObjCProtocolDecl");
2952 case CXCursor_ObjCPropertyDecl:
2953 return createCXString("ObjCPropertyDecl");
2954 case CXCursor_ObjCIvarDecl:
2955 return createCXString("ObjCIvarDecl");
2956 case CXCursor_ObjCInstanceMethodDecl:
2957 return createCXString("ObjCInstanceMethodDecl");
2958 case CXCursor_ObjCClassMethodDecl:
2959 return createCXString("ObjCClassMethodDecl");
2960 case CXCursor_ObjCImplementationDecl:
2961 return createCXString("ObjCImplementationDecl");
2962 case CXCursor_ObjCCategoryImplDecl:
2963 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002964 case CXCursor_CXXMethod:
2965 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002966 case CXCursor_UnexposedDecl:
2967 return createCXString("UnexposedDecl");
2968 case CXCursor_ObjCSuperClassRef:
2969 return createCXString("ObjCSuperClassRef");
2970 case CXCursor_ObjCProtocolRef:
2971 return createCXString("ObjCProtocolRef");
2972 case CXCursor_ObjCClassRef:
2973 return createCXString("ObjCClassRef");
2974 case CXCursor_TypeRef:
2975 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002976 case CXCursor_TemplateRef:
2977 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002978 case CXCursor_NamespaceRef:
2979 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002980 case CXCursor_MemberRef:
2981 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002982 case CXCursor_LabelRef:
2983 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002984 case CXCursor_OverloadedDeclRef:
2985 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002986 case CXCursor_UnexposedExpr:
2987 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002988 case CXCursor_BlockExpr:
2989 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002990 case CXCursor_DeclRefExpr:
2991 return createCXString("DeclRefExpr");
2992 case CXCursor_MemberRefExpr:
2993 return createCXString("MemberRefExpr");
2994 case CXCursor_CallExpr:
2995 return createCXString("CallExpr");
2996 case CXCursor_ObjCMessageExpr:
2997 return createCXString("ObjCMessageExpr");
2998 case CXCursor_UnexposedStmt:
2999 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003000 case CXCursor_LabelStmt:
3001 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003002 case CXCursor_InvalidFile:
3003 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003004 case CXCursor_InvalidCode:
3005 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003006 case CXCursor_NoDeclFound:
3007 return createCXString("NoDeclFound");
3008 case CXCursor_NotImplemented:
3009 return createCXString("NotImplemented");
3010 case CXCursor_TranslationUnit:
3011 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003012 case CXCursor_UnexposedAttr:
3013 return createCXString("UnexposedAttr");
3014 case CXCursor_IBActionAttr:
3015 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003016 case CXCursor_IBOutletAttr:
3017 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003018 case CXCursor_IBOutletCollectionAttr:
3019 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003020 case CXCursor_PreprocessingDirective:
3021 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003022 case CXCursor_MacroDefinition:
3023 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003024 case CXCursor_MacroInstantiation:
3025 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003026 case CXCursor_InclusionDirective:
3027 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003028 case CXCursor_Namespace:
3029 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003030 case CXCursor_LinkageSpec:
3031 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003032 case CXCursor_CXXBaseSpecifier:
3033 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003034 case CXCursor_Constructor:
3035 return createCXString("CXXConstructor");
3036 case CXCursor_Destructor:
3037 return createCXString("CXXDestructor");
3038 case CXCursor_ConversionFunction:
3039 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003040 case CXCursor_TemplateTypeParameter:
3041 return createCXString("TemplateTypeParameter");
3042 case CXCursor_NonTypeTemplateParameter:
3043 return createCXString("NonTypeTemplateParameter");
3044 case CXCursor_TemplateTemplateParameter:
3045 return createCXString("TemplateTemplateParameter");
3046 case CXCursor_FunctionTemplate:
3047 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003048 case CXCursor_ClassTemplate:
3049 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003050 case CXCursor_ClassTemplatePartialSpecialization:
3051 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003052 case CXCursor_NamespaceAlias:
3053 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003054 case CXCursor_UsingDirective:
3055 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003056 case CXCursor_UsingDeclaration:
3057 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003058 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003059
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003060 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003061 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003062}
Steve Naroff89922f82009-08-31 00:59:03 +00003063
Ted Kremeneke68fff62010-02-17 00:41:32 +00003064enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3065 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003066 CXClientData client_data) {
3067 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003068
3069 // If our current best cursor is the construction of a temporary object,
3070 // don't replace that cursor with a type reference, because we want
3071 // clang_getCursor() to point at the constructor.
3072 if (clang_isExpression(BestCursor->kind) &&
3073 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3074 cursor.kind == CXCursor_TypeRef)
3075 return CXChildVisit_Recurse;
3076
Douglas Gregor85fe1562010-12-10 07:23:11 +00003077 // Don't override a preprocessing cursor with another preprocessing
3078 // cursor; we want the outermost preprocessing cursor.
3079 if (clang_isPreprocessing(cursor.kind) &&
3080 clang_isPreprocessing(BestCursor->kind))
3081 return CXChildVisit_Recurse;
3082
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003083 *BestCursor = cursor;
3084 return CXChildVisit_Recurse;
3085}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003086
Douglas Gregorb9790342010-01-22 21:44:22 +00003087CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3088 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003089 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003090
Ted Kremeneka60ed472010-11-16 08:15:36 +00003091 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003092 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3093
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003094 // Translate the given source location to make it point at the beginning of
3095 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003096 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003097
3098 // Guard against an invalid SourceLocation, or we may assert in one
3099 // of the following calls.
3100 if (SLoc.isInvalid())
3101 return clang_getNullCursor();
3102
Douglas Gregor40749ee2010-11-03 00:35:38 +00003103 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003104 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3105 CXXUnit->getASTContext().getLangOptions());
3106
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003107 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3108 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003109 // FIXME: Would be great to have a "hint" cursor, then walk from that
3110 // hint cursor upward until we find a cursor whose source range encloses
3111 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003112 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3113 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003114 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003115 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003116 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003117
3118 if (Logging) {
3119 CXFile SearchFile;
3120 unsigned SearchLine, SearchColumn;
3121 CXFile ResultFile;
3122 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003123 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3124 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003125 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3126
3127 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3128 0);
3129 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3130 &ResultColumn, 0);
3131 SearchFileName = clang_getFileName(SearchFile);
3132 ResultFileName = clang_getFileName(ResultFile);
3133 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003134 USR = clang_getCursorUSR(Result);
3135 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003136 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3137 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003138 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3139 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003140 clang_disposeString(SearchFileName);
3141 clang_disposeString(ResultFileName);
3142 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003143 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003144
3145 CXCursor Definition = clang_getCursorDefinition(Result);
3146 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3147 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3148 CXString DefinitionKindSpelling
3149 = clang_getCursorKindSpelling(Definition.kind);
3150 CXFile DefinitionFile;
3151 unsigned DefinitionLine, DefinitionColumn;
3152 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3153 &DefinitionLine, &DefinitionColumn, 0);
3154 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3155 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3156 clang_getCString(DefinitionKindSpelling),
3157 clang_getCString(DefinitionFileName),
3158 DefinitionLine, DefinitionColumn);
3159 clang_disposeString(DefinitionFileName);
3160 clang_disposeString(DefinitionKindSpelling);
3161 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003162 }
3163
Ted Kremeneke68fff62010-02-17 00:41:32 +00003164 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003165}
3166
Ted Kremenek73885552009-11-17 19:28:59 +00003167CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003168 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003169}
3170
3171unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003172 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003173}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003174
Douglas Gregor9ce55842010-11-20 00:09:34 +00003175unsigned clang_hashCursor(CXCursor C) {
3176 unsigned Index = 0;
3177 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3178 Index = 1;
3179
3180 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3181 std::make_pair(C.kind, C.data[Index]));
3182}
3183
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003184unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003185 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3186}
3187
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003188unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003189 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3190}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003191
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003192unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003193 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3194}
3195
Douglas Gregor97b98722010-01-19 23:20:36 +00003196unsigned clang_isExpression(enum CXCursorKind K) {
3197 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3198}
3199
3200unsigned clang_isStatement(enum CXCursorKind K) {
3201 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3202}
3203
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003204unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3205 return K == CXCursor_TranslationUnit;
3206}
3207
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003208unsigned clang_isPreprocessing(enum CXCursorKind K) {
3209 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3210}
3211
Ted Kremenekad6eff62010-03-08 21:17:29 +00003212unsigned clang_isUnexposed(enum CXCursorKind K) {
3213 switch (K) {
3214 case CXCursor_UnexposedDecl:
3215 case CXCursor_UnexposedExpr:
3216 case CXCursor_UnexposedStmt:
3217 case CXCursor_UnexposedAttr:
3218 return true;
3219 default:
3220 return false;
3221 }
3222}
3223
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003224CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003225 return C.kind;
3226}
3227
Douglas Gregor98258af2010-01-18 22:46:11 +00003228CXSourceLocation clang_getCursorLocation(CXCursor C) {
3229 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003230 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003231 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003232 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3233 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003234 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003235 }
3236
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003237 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003238 std::pair<ObjCProtocolDecl *, SourceLocation> P
3239 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003240 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003241 }
3242
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003243 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003244 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3245 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003246 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003247 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003248
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003249 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003250 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003251 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003252 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003253
3254 case CXCursor_TemplateRef: {
3255 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3256 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3257 }
3258
Douglas Gregor69319002010-08-31 23:48:11 +00003259 case CXCursor_NamespaceRef: {
3260 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3261 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3262 }
3263
Douglas Gregora67e03f2010-09-09 21:42:20 +00003264 case CXCursor_MemberRef: {
3265 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3266 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3267 }
3268
Ted Kremenek3064ef92010-08-27 21:34:58 +00003269 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003270 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3271 if (!BaseSpec)
3272 return clang_getNullLocation();
3273
3274 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3275 return cxloc::translateSourceLocation(getCursorContext(C),
3276 TSInfo->getTypeLoc().getBeginLoc());
3277
3278 return cxloc::translateSourceLocation(getCursorContext(C),
3279 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003280 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003281
Douglas Gregor36897b02010-09-10 00:22:18 +00003282 case CXCursor_LabelRef: {
3283 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3284 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3285 }
3286
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003287 case CXCursor_OverloadedDeclRef:
3288 return cxloc::translateSourceLocation(getCursorContext(C),
3289 getCursorOverloadedDeclRef(C).second);
3290
Douglas Gregorf46034a2010-01-18 23:41:10 +00003291 default:
3292 // FIXME: Need a way to enumerate all non-reference cases.
3293 llvm_unreachable("Missed a reference kind");
3294 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003295 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003296
3297 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003298 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003299 getLocationFromExpr(getCursorExpr(C)));
3300
Douglas Gregor36897b02010-09-10 00:22:18 +00003301 if (clang_isStatement(C.kind))
3302 return cxloc::translateSourceLocation(getCursorContext(C),
3303 getCursorStmt(C)->getLocStart());
3304
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003305 if (C.kind == CXCursor_PreprocessingDirective) {
3306 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3307 return cxloc::translateSourceLocation(getCursorContext(C), L);
3308 }
Douglas Gregor48072312010-03-18 15:23:44 +00003309
3310 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003311 SourceLocation L
3312 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003313 return cxloc::translateSourceLocation(getCursorContext(C), L);
3314 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003315
3316 if (C.kind == CXCursor_MacroDefinition) {
3317 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3318 return cxloc::translateSourceLocation(getCursorContext(C), L);
3319 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003320
3321 if (C.kind == CXCursor_InclusionDirective) {
3322 SourceLocation L
3323 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3324 return cxloc::translateSourceLocation(getCursorContext(C), L);
3325 }
3326
Ted Kremenek9a700d22010-05-12 06:16:13 +00003327 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003328 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003329
Douglas Gregorf46034a2010-01-18 23:41:10 +00003330 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003331 SourceLocation Loc = D->getLocation();
3332 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3333 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003334 // FIXME: Multiple variables declared in a single declaration
3335 // currently lack the information needed to correctly determine their
3336 // ranges when accounting for the type-specifier. We use context
3337 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3338 // and if so, whether it is the first decl.
3339 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3340 if (!cxcursor::isFirstInDeclGroup(C))
3341 Loc = VD->getLocation();
3342 }
3343
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003344 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003345}
Douglas Gregora7bde202010-01-19 00:34:46 +00003346
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003347} // end extern "C"
3348
3349static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003350 if (clang_isReference(C.kind)) {
3351 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003352 case CXCursor_ObjCSuperClassRef:
3353 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003354
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003355 case CXCursor_ObjCProtocolRef:
3356 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003357
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003358 case CXCursor_ObjCClassRef:
3359 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003360
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003361 case CXCursor_TypeRef:
3362 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003363
3364 case CXCursor_TemplateRef:
3365 return getCursorTemplateRef(C).second;
3366
Douglas Gregor69319002010-08-31 23:48:11 +00003367 case CXCursor_NamespaceRef:
3368 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003369
3370 case CXCursor_MemberRef:
3371 return getCursorMemberRef(C).second;
3372
Ted Kremenek3064ef92010-08-27 21:34:58 +00003373 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003374 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003375
Douglas Gregor36897b02010-09-10 00:22:18 +00003376 case CXCursor_LabelRef:
3377 return getCursorLabelRef(C).second;
3378
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003379 case CXCursor_OverloadedDeclRef:
3380 return getCursorOverloadedDeclRef(C).second;
3381
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003382 default:
3383 // FIXME: Need a way to enumerate all non-reference cases.
3384 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003385 }
3386 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003387
3388 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003389 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003390
3391 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003392 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003393
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003394 if (C.kind == CXCursor_PreprocessingDirective)
3395 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003396
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003397 if (C.kind == CXCursor_MacroInstantiation)
3398 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003399
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003400 if (C.kind == CXCursor_MacroDefinition)
3401 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003402
3403 if (C.kind == CXCursor_InclusionDirective)
3404 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3405
Ted Kremenek007a7c92010-11-01 23:26:51 +00003406 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3407 Decl *D = cxcursor::getCursorDecl(C);
3408 SourceRange R = D->getSourceRange();
3409 // FIXME: Multiple variables declared in a single declaration
3410 // currently lack the information needed to correctly determine their
3411 // ranges when accounting for the type-specifier. We use context
3412 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3413 // and if so, whether it is the first decl.
3414 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3415 if (!cxcursor::isFirstInDeclGroup(C))
3416 R.setBegin(VD->getLocation());
3417 }
3418 return R;
3419 }
Douglas Gregor66537982010-11-17 17:14:07 +00003420 return SourceRange();
3421}
3422
3423/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3424/// the decl-specifier-seq for declarations.
3425static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3426 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3427 Decl *D = cxcursor::getCursorDecl(C);
3428 SourceRange R = D->getSourceRange();
3429
3430 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3431 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3432 TypeLoc TL = TI->getTypeLoc();
3433 SourceLocation TLoc = TL.getSourceRange().getBegin();
3434 if (TLoc.isValid() && R.getBegin().isValid() &&
3435 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3436 R.setBegin(TLoc);
3437 }
3438
3439 // FIXME: Multiple variables declared in a single declaration
3440 // currently lack the information needed to correctly determine their
3441 // ranges when accounting for the type-specifier. We use context
3442 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3443 // and if so, whether it is the first decl.
3444 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3445 if (!cxcursor::isFirstInDeclGroup(C))
3446 R.setBegin(VD->getLocation());
3447 }
3448 }
3449
3450 return R;
3451 }
3452
3453 return getRawCursorExtent(C);
3454}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003455
3456extern "C" {
3457
3458CXSourceRange clang_getCursorExtent(CXCursor C) {
3459 SourceRange R = getRawCursorExtent(C);
3460 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003461 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003462
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003463 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003464}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003465
3466CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003467 if (clang_isInvalid(C.kind))
3468 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003469
Ted Kremeneka60ed472010-11-16 08:15:36 +00003470 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003471 if (clang_isDeclaration(C.kind)) {
3472 Decl *D = getCursorDecl(C);
3473 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003474 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003475 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003476 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003477 if (ObjCForwardProtocolDecl *Protocols
3478 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003479 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003480 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3481 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3482 return MakeCXCursor(Property, tu);
3483
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003484 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003485 }
3486
Douglas Gregor97b98722010-01-19 23:20:36 +00003487 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003488 Expr *E = getCursorExpr(C);
3489 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003490 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003491 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003492
3493 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003494 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003495
Douglas Gregor97b98722010-01-19 23:20:36 +00003496 return clang_getNullCursor();
3497 }
3498
Douglas Gregor36897b02010-09-10 00:22:18 +00003499 if (clang_isStatement(C.kind)) {
3500 Stmt *S = getCursorStmt(C);
3501 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003502 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003503
3504 return clang_getNullCursor();
3505 }
3506
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003507 if (C.kind == CXCursor_MacroInstantiation) {
3508 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003509 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003510 }
3511
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003512 if (!clang_isReference(C.kind))
3513 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003514
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003515 switch (C.kind) {
3516 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003517 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003518
3519 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003520 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003521
3522 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003523 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003524
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003525 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003526 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003527
3528 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003529 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003530
Douglas Gregor69319002010-08-31 23:48:11 +00003531 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003532 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003533
Douglas Gregora67e03f2010-09-09 21:42:20 +00003534 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003535 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003536
Ted Kremenek3064ef92010-08-27 21:34:58 +00003537 case CXCursor_CXXBaseSpecifier: {
3538 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3539 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003540 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003541 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003542
Douglas Gregor36897b02010-09-10 00:22:18 +00003543 case CXCursor_LabelRef:
3544 // FIXME: We end up faking the "parent" declaration here because we
3545 // don't want to make CXCursor larger.
3546 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003547 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3548 .getTranslationUnitDecl(),
3549 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003550
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003551 case CXCursor_OverloadedDeclRef:
3552 return C;
3553
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003554 default:
3555 // We would prefer to enumerate all non-reference cursor kinds here.
3556 llvm_unreachable("Unhandled reference cursor kind");
3557 break;
3558 }
3559 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003560
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003561 return clang_getNullCursor();
3562}
3563
Douglas Gregorb6998662010-01-19 19:34:47 +00003564CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003565 if (clang_isInvalid(C.kind))
3566 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003567
Ted Kremeneka60ed472010-11-16 08:15:36 +00003568 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003569
Douglas Gregorb6998662010-01-19 19:34:47 +00003570 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003571 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003572 C = clang_getCursorReferenced(C);
3573 WasReference = true;
3574 }
3575
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003576 if (C.kind == CXCursor_MacroInstantiation)
3577 return clang_getCursorReferenced(C);
3578
Douglas Gregorb6998662010-01-19 19:34:47 +00003579 if (!clang_isDeclaration(C.kind))
3580 return clang_getNullCursor();
3581
3582 Decl *D = getCursorDecl(C);
3583 if (!D)
3584 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585
Douglas Gregorb6998662010-01-19 19:34:47 +00003586 switch (D->getKind()) {
3587 // Declaration kinds that don't really separate the notions of
3588 // declaration and definition.
3589 case Decl::Namespace:
3590 case Decl::Typedef:
3591 case Decl::TemplateTypeParm:
3592 case Decl::EnumConstant:
3593 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003594 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003595 case Decl::ObjCIvar:
3596 case Decl::ObjCAtDefsField:
3597 case Decl::ImplicitParam:
3598 case Decl::ParmVar:
3599 case Decl::NonTypeTemplateParm:
3600 case Decl::TemplateTemplateParm:
3601 case Decl::ObjCCategoryImpl:
3602 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003603 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003604 case Decl::LinkageSpec:
3605 case Decl::ObjCPropertyImpl:
3606 case Decl::FileScopeAsm:
3607 case Decl::StaticAssert:
3608 case Decl::Block:
3609 return C;
3610
3611 // Declaration kinds that don't make any sense here, but are
3612 // nonetheless harmless.
3613 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003614 break;
3615
3616 // Declaration kinds for which the definition is not resolvable.
3617 case Decl::UnresolvedUsingTypename:
3618 case Decl::UnresolvedUsingValue:
3619 break;
3620
3621 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003622 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003623 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003624
3625 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003626 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003627
3628 case Decl::Enum:
3629 case Decl::Record:
3630 case Decl::CXXRecord:
3631 case Decl::ClassTemplateSpecialization:
3632 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003633 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003634 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003635 return clang_getNullCursor();
3636
3637 case Decl::Function:
3638 case Decl::CXXMethod:
3639 case Decl::CXXConstructor:
3640 case Decl::CXXDestructor:
3641 case Decl::CXXConversion: {
3642 const FunctionDecl *Def = 0;
3643 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003644 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003645 return clang_getNullCursor();
3646 }
3647
3648 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003649 // Ask the variable if it has a definition.
3650 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003651 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003652 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003653 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003654
Douglas Gregorb6998662010-01-19 19:34:47 +00003655 case Decl::FunctionTemplate: {
3656 const FunctionDecl *Def = 0;
3657 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003658 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003659 return clang_getNullCursor();
3660 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003661
Douglas Gregorb6998662010-01-19 19:34:47 +00003662 case Decl::ClassTemplate: {
3663 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003664 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003665 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003666 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003667 return clang_getNullCursor();
3668 }
3669
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003670 case Decl::Using:
3671 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003672 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003673
3674 case Decl::UsingShadow:
3675 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003676 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003677 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003678
3679 case Decl::ObjCMethod: {
3680 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3681 if (Method->isThisDeclarationADefinition())
3682 return C;
3683
3684 // Dig out the method definition in the associated
3685 // @implementation, if we have it.
3686 // FIXME: The ASTs should make finding the definition easier.
3687 if (ObjCInterfaceDecl *Class
3688 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3689 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3690 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3691 Method->isInstanceMethod()))
3692 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003693 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003694
3695 return clang_getNullCursor();
3696 }
3697
3698 case Decl::ObjCCategory:
3699 if (ObjCCategoryImplDecl *Impl
3700 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003701 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003702 return clang_getNullCursor();
3703
3704 case Decl::ObjCProtocol:
3705 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3706 return C;
3707 return clang_getNullCursor();
3708
3709 case Decl::ObjCInterface:
3710 // There are two notions of a "definition" for an Objective-C
3711 // class: the interface and its implementation. When we resolved a
3712 // reference to an Objective-C class, produce the @interface as
3713 // the definition; when we were provided with the interface,
3714 // produce the @implementation as the definition.
3715 if (WasReference) {
3716 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3717 return C;
3718 } else if (ObjCImplementationDecl *Impl
3719 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003720 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003721 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003722
Douglas Gregorb6998662010-01-19 19:34:47 +00003723 case Decl::ObjCProperty:
3724 // FIXME: We don't really know where to find the
3725 // ObjCPropertyImplDecls that implement this property.
3726 return clang_getNullCursor();
3727
3728 case Decl::ObjCCompatibleAlias:
3729 if (ObjCInterfaceDecl *Class
3730 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3731 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003732 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003733
Douglas Gregorb6998662010-01-19 19:34:47 +00003734 return clang_getNullCursor();
3735
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003736 case Decl::ObjCForwardProtocol:
3737 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003738 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003739
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003740 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003741 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003742 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003743
3744 case Decl::Friend:
3745 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003746 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003747 return clang_getNullCursor();
3748
3749 case Decl::FriendTemplate:
3750 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003751 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003752 return clang_getNullCursor();
3753 }
3754
3755 return clang_getNullCursor();
3756}
3757
3758unsigned clang_isCursorDefinition(CXCursor C) {
3759 if (!clang_isDeclaration(C.kind))
3760 return 0;
3761
3762 return clang_getCursorDefinition(C) == C;
3763}
3764
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003765CXCursor clang_getCanonicalCursor(CXCursor C) {
3766 if (!clang_isDeclaration(C.kind))
3767 return C;
3768
3769 if (Decl *D = getCursorDecl(C))
3770 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3771
3772 return C;
3773}
3774
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003775unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003776 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003777 return 0;
3778
3779 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3780 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3781 return E->getNumDecls();
3782
3783 if (OverloadedTemplateStorage *S
3784 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3785 return S->size();
3786
3787 Decl *D = Storage.get<Decl*>();
3788 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003789 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003790 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3791 return Classes->size();
3792 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3793 return Protocols->protocol_size();
3794
3795 return 0;
3796}
3797
3798CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003799 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003800 return clang_getNullCursor();
3801
3802 if (index >= clang_getNumOverloadedDecls(cursor))
3803 return clang_getNullCursor();
3804
Ted Kremeneka60ed472010-11-16 08:15:36 +00003805 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003806 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3807 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003808 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003809
3810 if (OverloadedTemplateStorage *S
3811 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003812 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003813
3814 Decl *D = Storage.get<Decl*>();
3815 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3816 // FIXME: This is, unfortunately, linear time.
3817 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3818 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003819 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003820 }
3821
3822 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003823 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003824
3825 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003826 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003827
3828 return clang_getNullCursor();
3829}
3830
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003831void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003832 const char **startBuf,
3833 const char **endBuf,
3834 unsigned *startLine,
3835 unsigned *startColumn,
3836 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003837 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003838 assert(getCursorDecl(C) && "CXCursor has null decl");
3839 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003840 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3841 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003842
Steve Naroff4ade6d62009-09-23 17:52:52 +00003843 SourceManager &SM = FD->getASTContext().getSourceManager();
3844 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3845 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3846 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3847 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3848 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3849 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3850}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003852void clang_enableStackTraces(void) {
3853 llvm::sys::PrintStackTraceOnErrorSignal();
3854}
3855
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003856void clang_executeOnThread(void (*fn)(void*), void *user_data,
3857 unsigned stack_size) {
3858 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3859}
3860
Ted Kremenekfb480492010-01-13 21:46:36 +00003861} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003862
Ted Kremenekfb480492010-01-13 21:46:36 +00003863//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864// Token-based Operations.
3865//===----------------------------------------------------------------------===//
3866
3867/* CXToken layout:
3868 * int_data[0]: a CXTokenKind
3869 * int_data[1]: starting token location
3870 * int_data[2]: token length
3871 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003872 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003873 * otherwise unused.
3874 */
3875extern "C" {
3876
3877CXTokenKind clang_getTokenKind(CXToken CXTok) {
3878 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3879}
3880
3881CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3882 switch (clang_getTokenKind(CXTok)) {
3883 case CXToken_Identifier:
3884 case CXToken_Keyword:
3885 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003886 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3887 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003888
3889 case CXToken_Literal: {
3890 // We have stashed the starting pointer in the ptr_data field. Use it.
3891 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003892 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895 case CXToken_Punctuation:
3896 case CXToken_Comment:
3897 break;
3898 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003899
3900 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003901 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003902 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003903 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003904 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003905
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003906 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3907 std::pair<FileID, unsigned> LocInfo
3908 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003909 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003910 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003911 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3912 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003913 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003914
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003915 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003916}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003917
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003918CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003919 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003920 if (!CXXUnit)
3921 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003922
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003923 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3924 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3925}
3926
3927CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003928 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003929 if (!CXXUnit)
3930 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003931
3932 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003933 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3934}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003935
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003936void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3937 CXToken **Tokens, unsigned *NumTokens) {
3938 if (Tokens)
3939 *Tokens = 0;
3940 if (NumTokens)
3941 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003942
Ted Kremeneka60ed472010-11-16 08:15:36 +00003943 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003944 if (!CXXUnit || !Tokens || !NumTokens)
3945 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003946
Douglas Gregorbdf60622010-03-05 21:16:25 +00003947 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3948
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003949 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003950 if (R.isInvalid())
3951 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003952
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003953 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3954 std::pair<FileID, unsigned> BeginLocInfo
3955 = SourceMgr.getDecomposedLoc(R.getBegin());
3956 std::pair<FileID, unsigned> EndLocInfo
3957 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003958
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003959 // Cannot tokenize across files.
3960 if (BeginLocInfo.first != EndLocInfo.first)
3961 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003962
3963 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003964 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003965 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003966 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003967 if (Invalid)
3968 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003969
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003970 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3971 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003972 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003973 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003974
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003975 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003976 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003977 llvm::SmallVector<CXToken, 32> CXTokens;
3978 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003979 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003980 do {
3981 // Lex the next token
3982 Lex.LexFromRawLexer(Tok);
3983 if (Tok.is(tok::eof))
3984 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003985
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003986 // Initialize the CXToken.
3987 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003988
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003989 // - Common fields
3990 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3991 CXTok.int_data[2] = Tok.getLength();
3992 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003993
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003994 // - Kind-specific fields
3995 if (Tok.isLiteral()) {
3996 CXTok.int_data[0] = CXToken_Literal;
3997 CXTok.ptr_data = (void *)Tok.getLiteralData();
3998 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003999 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004000 std::pair<FileID, unsigned> LocInfo
4001 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00004002 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004003 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00004004 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4005 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004006 return;
4007
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004008 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004009 IdentifierInfo *II
4010 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004011
David Chisnall096428b2010-10-13 21:44:48 +00004012 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004013 CXTok.int_data[0] = CXToken_Keyword;
4014 }
4015 else {
4016 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
4017 CXToken_Identifier
4018 : CXToken_Keyword;
4019 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004020 CXTok.ptr_data = II;
4021 } else if (Tok.is(tok::comment)) {
4022 CXTok.int_data[0] = CXToken_Comment;
4023 CXTok.ptr_data = 0;
4024 } else {
4025 CXTok.int_data[0] = CXToken_Punctuation;
4026 CXTok.ptr_data = 0;
4027 }
4028 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004029 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004030 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004031
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004032 if (CXTokens.empty())
4033 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004034
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004035 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4036 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4037 *NumTokens = CXTokens.size();
4038}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004039
Ted Kremenek6db61092010-05-05 00:55:15 +00004040void clang_disposeTokens(CXTranslationUnit TU,
4041 CXToken *Tokens, unsigned NumTokens) {
4042 free(Tokens);
4043}
4044
4045} // end: extern "C"
4046
4047//===----------------------------------------------------------------------===//
4048// Token annotation APIs.
4049//===----------------------------------------------------------------------===//
4050
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004051typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004052static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4053 CXCursor parent,
4054 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004055namespace {
4056class AnnotateTokensWorker {
4057 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004058 CXToken *Tokens;
4059 CXCursor *Cursors;
4060 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004061 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004062 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004063 CursorVisitor AnnotateVis;
4064 SourceManager &SrcMgr;
4065
4066 bool MoreTokens() const { return TokIdx < NumTokens; }
4067 unsigned NextToken() const { return TokIdx; }
4068 void AdvanceToken() { ++TokIdx; }
4069 SourceLocation GetTokenLoc(unsigned tokI) {
4070 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4071 }
4072
Ted Kremenek6db61092010-05-05 00:55:15 +00004073public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004074 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004075 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004076 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004077 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004078 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004079 AnnotateVis(tu,
4080 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004081 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004082 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004083
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004084 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004085 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004086 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004087 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004088 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004089 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004090};
4091}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004092
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004093void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4094 // Walk the AST within the region of interest, annotating tokens
4095 // along the way.
4096 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004097
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004098 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4099 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004100 if (Pos != Annotated.end() &&
4101 (clang_isInvalid(Cursors[I].kind) ||
4102 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004103 Cursors[I] = Pos->second;
4104 }
4105
4106 // Finish up annotating any tokens left.
4107 if (!MoreTokens())
4108 return;
4109
4110 const CXCursor &C = clang_getNullCursor();
4111 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4112 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4113 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004114 }
4115}
4116
Ted Kremenek6db61092010-05-05 00:55:15 +00004117enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004118AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004119 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004120 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004121 if (cursorRange.isInvalid())
4122 return CXChildVisit_Recurse;
4123
Douglas Gregor4419b672010-10-21 06:10:04 +00004124 if (clang_isPreprocessing(cursor.kind)) {
4125 // For macro instantiations, just note where the beginning of the macro
4126 // instantiation occurs.
4127 if (cursor.kind == CXCursor_MacroInstantiation) {
4128 Annotated[Loc.int_data] = cursor;
4129 return CXChildVisit_Recurse;
4130 }
4131
Douglas Gregor4419b672010-10-21 06:10:04 +00004132 // Items in the preprocessing record are kept separate from items in
4133 // declarations, so we keep a separate token index.
4134 unsigned SavedTokIdx = TokIdx;
4135 TokIdx = PreprocessingTokIdx;
4136
4137 // Skip tokens up until we catch up to the beginning of the preprocessing
4138 // entry.
4139 while (MoreTokens()) {
4140 const unsigned I = NextToken();
4141 SourceLocation TokLoc = GetTokenLoc(I);
4142 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4143 case RangeBefore:
4144 AdvanceToken();
4145 continue;
4146 case RangeAfter:
4147 case RangeOverlap:
4148 break;
4149 }
4150 break;
4151 }
4152
4153 // Look at all of the tokens within this range.
4154 while (MoreTokens()) {
4155 const unsigned I = NextToken();
4156 SourceLocation TokLoc = GetTokenLoc(I);
4157 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4158 case RangeBefore:
4159 assert(0 && "Infeasible");
4160 case RangeAfter:
4161 break;
4162 case RangeOverlap:
4163 Cursors[I] = cursor;
4164 AdvanceToken();
4165 continue;
4166 }
4167 break;
4168 }
4169
4170 // Save the preprocessing token index; restore the non-preprocessing
4171 // token index.
4172 PreprocessingTokIdx = TokIdx;
4173 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004174 return CXChildVisit_Recurse;
4175 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004176
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004177 if (cursorRange.isInvalid())
4178 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004179
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004180 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4181
Ted Kremeneka333c662010-05-12 05:29:33 +00004182 // Adjust the annotated range based specific declarations.
4183 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4184 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004185 Decl *D = cxcursor::getCursorDecl(cursor);
4186 // Don't visit synthesized ObjC methods, since they have no syntatic
4187 // representation in the source.
4188 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4189 if (MD->isSynthesized())
4190 return CXChildVisit_Continue;
4191 }
4192 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004193 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4194 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004195 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004196 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004197 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004198 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004199 }
4200 }
4201 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004202
Ted Kremenek3f404602010-08-14 01:14:06 +00004203 // If the location of the cursor occurs within a macro instantiation, record
4204 // the spelling location of the cursor in our annotation map. We can then
4205 // paper over the token labelings during a post-processing step to try and
4206 // get cursor mappings for tokens that are the *arguments* of a macro
4207 // instantiation.
4208 if (L.isMacroID()) {
4209 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4210 // Only invalidate the old annotation if it isn't part of a preprocessing
4211 // directive. Here we assume that the default construction of CXCursor
4212 // results in CXCursor.kind being an initialized value (i.e., 0). If
4213 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004214
Ted Kremenek3f404602010-08-14 01:14:06 +00004215 CXCursor &oldC = Annotated[rawEncoding];
4216 if (!clang_isPreprocessing(oldC.kind))
4217 oldC = cursor;
4218 }
4219
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004220 const enum CXCursorKind K = clang_getCursorKind(parent);
4221 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004222 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4223 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004224
4225 while (MoreTokens()) {
4226 const unsigned I = NextToken();
4227 SourceLocation TokLoc = GetTokenLoc(I);
4228 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4229 case RangeBefore:
4230 Cursors[I] = updateC;
4231 AdvanceToken();
4232 continue;
4233 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004234 case RangeOverlap:
4235 break;
4236 }
4237 break;
4238 }
4239
4240 // Visit children to get their cursor information.
4241 const unsigned BeforeChildren = NextToken();
4242 VisitChildren(cursor);
4243 const unsigned AfterChildren = NextToken();
4244
4245 // Adjust 'Last' to the last token within the extent of the cursor.
4246 while (MoreTokens()) {
4247 const unsigned I = NextToken();
4248 SourceLocation TokLoc = GetTokenLoc(I);
4249 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4250 case RangeBefore:
4251 assert(0 && "Infeasible");
4252 case RangeAfter:
4253 break;
4254 case RangeOverlap:
4255 Cursors[I] = updateC;
4256 AdvanceToken();
4257 continue;
4258 }
4259 break;
4260 }
4261 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004262
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004263 // Scan the tokens that are at the beginning of the cursor, but are not
4264 // capture by the child cursors.
4265
4266 // For AST elements within macros, rely on a post-annotate pass to
4267 // to correctly annotate the tokens with cursors. Otherwise we can
4268 // get confusing results of having tokens that map to cursors that really
4269 // are expanded by an instantiation.
4270 if (L.isMacroID())
4271 cursor = clang_getNullCursor();
4272
4273 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4274 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4275 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004276
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004277 Cursors[I] = cursor;
4278 }
4279 // Scan the tokens that are at the end of the cursor, but are not captured
4280 // but the child cursors.
4281 for (unsigned I = AfterChildren; I != Last; ++I)
4282 Cursors[I] = cursor;
4283
4284 TokIdx = Last;
4285 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004286}
4287
Ted Kremenek6db61092010-05-05 00:55:15 +00004288static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4289 CXCursor parent,
4290 CXClientData client_data) {
4291 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4292}
4293
Ted Kremenekab979612010-11-11 08:05:23 +00004294// This gets run a separate thread to avoid stack blowout.
4295static void runAnnotateTokensWorker(void *UserData) {
4296 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4297}
4298
Ted Kremenek6db61092010-05-05 00:55:15 +00004299extern "C" {
4300
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004301void clang_annotateTokens(CXTranslationUnit TU,
4302 CXToken *Tokens, unsigned NumTokens,
4303 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004304
4305 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004306 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004307
Douglas Gregor4419b672010-10-21 06:10:04 +00004308 // Any token we don't specifically annotate will have a NULL cursor.
4309 CXCursor C = clang_getNullCursor();
4310 for (unsigned I = 0; I != NumTokens; ++I)
4311 Cursors[I] = C;
4312
Ted Kremeneka60ed472010-11-16 08:15:36 +00004313 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004314 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004315 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004316
Douglas Gregorbdf60622010-03-05 21:16:25 +00004317 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004318
Douglas Gregor0396f462010-03-19 05:22:59 +00004319 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004320 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004321 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4322 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004323 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4324 clang_getTokenLocation(TU,
4325 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004326
Douglas Gregor0396f462010-03-19 05:22:59 +00004327 // A mapping from the source locations found when re-lexing or traversing the
4328 // region of interest to the corresponding cursors.
4329 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004330
4331 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004332 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004333 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4334 std::pair<FileID, unsigned> BeginLocInfo
4335 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4336 std::pair<FileID, unsigned> EndLocInfo
4337 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004338
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004339 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004340 bool Invalid = false;
4341 if (BeginLocInfo.first == EndLocInfo.first &&
4342 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4343 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004344 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4345 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004346 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004347 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004348 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004349
4350 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004351 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004352 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004353 Token Tok;
4354 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004355
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004356 reprocess:
4357 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4358 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004359 // don't see it while preprocessing these tokens later, but keep track
4360 // of all of the token locations inside this preprocessing directive so
4361 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004362 //
4363 // FIXME: Some simple tests here could identify macro definitions and
4364 // #undefs, to provide specific cursor kinds for those.
4365 std::vector<SourceLocation> Locations;
4366 do {
4367 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004368 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004369 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004370
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004371 using namespace cxcursor;
4372 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004373 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4374 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004375 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004376 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4377 Annotated[Locations[I].getRawEncoding()] = Cursor;
4378 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004379
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004380 if (Tok.isAtStartOfLine())
4381 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004382
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004383 continue;
4384 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004385
Douglas Gregor48072312010-03-18 15:23:44 +00004386 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004387 break;
4388 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004389 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004390
Douglas Gregor0396f462010-03-19 05:22:59 +00004391 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004392 // a specific cursor.
4393 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004394 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004395
4396 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004397 // FIXME: We use a ridiculous stack size here because the data-recursion
4398 // algorithm uses a large stack frame than the non-data recursive version,
4399 // and AnnotationTokensWorker currently transforms the data-recursion
4400 // algorithm back into a traditional recursion by explicitly calling
4401 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004402 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004403 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4404 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004405 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4406 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004407}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004408} // end: extern "C"
4409
4410//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004411// Operations for querying linkage of a cursor.
4412//===----------------------------------------------------------------------===//
4413
4414extern "C" {
4415CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004416 if (!clang_isDeclaration(cursor.kind))
4417 return CXLinkage_Invalid;
4418
Ted Kremenek16b42592010-03-03 06:36:57 +00004419 Decl *D = cxcursor::getCursorDecl(cursor);
4420 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4421 switch (ND->getLinkage()) {
4422 case NoLinkage: return CXLinkage_NoLinkage;
4423 case InternalLinkage: return CXLinkage_Internal;
4424 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4425 case ExternalLinkage: return CXLinkage_External;
4426 };
4427
4428 return CXLinkage_Invalid;
4429}
4430} // end: extern "C"
4431
4432//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004433// Operations for querying language of a cursor.
4434//===----------------------------------------------------------------------===//
4435
4436static CXLanguageKind getDeclLanguage(const Decl *D) {
4437 switch (D->getKind()) {
4438 default:
4439 break;
4440 case Decl::ImplicitParam:
4441 case Decl::ObjCAtDefsField:
4442 case Decl::ObjCCategory:
4443 case Decl::ObjCCategoryImpl:
4444 case Decl::ObjCClass:
4445 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004446 case Decl::ObjCForwardProtocol:
4447 case Decl::ObjCImplementation:
4448 case Decl::ObjCInterface:
4449 case Decl::ObjCIvar:
4450 case Decl::ObjCMethod:
4451 case Decl::ObjCProperty:
4452 case Decl::ObjCPropertyImpl:
4453 case Decl::ObjCProtocol:
4454 return CXLanguage_ObjC;
4455 case Decl::CXXConstructor:
4456 case Decl::CXXConversion:
4457 case Decl::CXXDestructor:
4458 case Decl::CXXMethod:
4459 case Decl::CXXRecord:
4460 case Decl::ClassTemplate:
4461 case Decl::ClassTemplatePartialSpecialization:
4462 case Decl::ClassTemplateSpecialization:
4463 case Decl::Friend:
4464 case Decl::FriendTemplate:
4465 case Decl::FunctionTemplate:
4466 case Decl::LinkageSpec:
4467 case Decl::Namespace:
4468 case Decl::NamespaceAlias:
4469 case Decl::NonTypeTemplateParm:
4470 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004471 case Decl::TemplateTemplateParm:
4472 case Decl::TemplateTypeParm:
4473 case Decl::UnresolvedUsingTypename:
4474 case Decl::UnresolvedUsingValue:
4475 case Decl::Using:
4476 case Decl::UsingDirective:
4477 case Decl::UsingShadow:
4478 return CXLanguage_CPlusPlus;
4479 }
4480
4481 return CXLanguage_C;
4482}
4483
4484extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004485
4486enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4487 if (clang_isDeclaration(cursor.kind))
4488 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4489 if (D->hasAttr<UnavailableAttr>() ||
4490 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4491 return CXAvailability_Available;
4492
4493 if (D->hasAttr<DeprecatedAttr>())
4494 return CXAvailability_Deprecated;
4495 }
4496
4497 return CXAvailability_Available;
4498}
4499
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004500CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4501 if (clang_isDeclaration(cursor.kind))
4502 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4503
4504 return CXLanguage_Invalid;
4505}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004506
4507CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4508 if (clang_isDeclaration(cursor.kind)) {
4509 if (Decl *D = getCursorDecl(cursor)) {
4510 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004511 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004512 }
4513 }
4514
4515 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4516 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004517 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004518 }
4519
4520 return clang_getNullCursor();
4521}
4522
4523CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4524 if (clang_isDeclaration(cursor.kind)) {
4525 if (Decl *D = getCursorDecl(cursor)) {
4526 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004527 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004528 }
4529 }
4530
4531 // FIXME: Note that we can't easily compute the lexical context of a
4532 // statement or expression, so we return nothing.
4533 return clang_getNullCursor();
4534}
4535
Douglas Gregor9f592342010-10-01 20:25:15 +00004536static void CollectOverriddenMethods(DeclContext *Ctx,
4537 ObjCMethodDecl *Method,
4538 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4539 if (!Ctx)
4540 return;
4541
4542 // If we have a class or category implementation, jump straight to the
4543 // interface.
4544 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4545 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4546
4547 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4548 if (!Container)
4549 return;
4550
4551 // Check whether we have a matching method at this level.
4552 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4553 Method->isInstanceMethod()))
4554 if (Method != Overridden) {
4555 // We found an override at this level; there is no need to look
4556 // into other protocols or categories.
4557 Methods.push_back(Overridden);
4558 return;
4559 }
4560
4561 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4562 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4563 PEnd = Protocol->protocol_end();
4564 P != PEnd; ++P)
4565 CollectOverriddenMethods(*P, Method, Methods);
4566 }
4567
4568 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4569 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4570 PEnd = Category->protocol_end();
4571 P != PEnd; ++P)
4572 CollectOverriddenMethods(*P, Method, Methods);
4573 }
4574
4575 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4576 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4577 PEnd = Interface->protocol_end();
4578 P != PEnd; ++P)
4579 CollectOverriddenMethods(*P, Method, Methods);
4580
4581 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4582 Category; Category = Category->getNextClassCategory())
4583 CollectOverriddenMethods(Category, Method, Methods);
4584
4585 // We only look into the superclass if we haven't found anything yet.
4586 if (Methods.empty())
4587 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4588 return CollectOverriddenMethods(Super, Method, Methods);
4589 }
4590}
4591
4592void clang_getOverriddenCursors(CXCursor cursor,
4593 CXCursor **overridden,
4594 unsigned *num_overridden) {
4595 if (overridden)
4596 *overridden = 0;
4597 if (num_overridden)
4598 *num_overridden = 0;
4599 if (!overridden || !num_overridden)
4600 return;
4601
4602 if (!clang_isDeclaration(cursor.kind))
4603 return;
4604
4605 Decl *D = getCursorDecl(cursor);
4606 if (!D)
4607 return;
4608
4609 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004610 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004611 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4612 *num_overridden = CXXMethod->size_overridden_methods();
4613 if (!*num_overridden)
4614 return;
4615
4616 *overridden = new CXCursor [*num_overridden];
4617 unsigned I = 0;
4618 for (CXXMethodDecl::method_iterator
4619 M = CXXMethod->begin_overridden_methods(),
4620 MEnd = CXXMethod->end_overridden_methods();
4621 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004622 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004623 return;
4624 }
4625
4626 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4627 if (!Method)
4628 return;
4629
4630 // Handle Objective-C methods.
4631 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4632 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4633
4634 if (Methods.empty())
4635 return;
4636
4637 *num_overridden = Methods.size();
4638 *overridden = new CXCursor [Methods.size()];
4639 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004640 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004641}
4642
4643void clang_disposeOverriddenCursors(CXCursor *overridden) {
4644 delete [] overridden;
4645}
4646
Douglas Gregorecdcb882010-10-20 22:00:55 +00004647CXFile clang_getIncludedFile(CXCursor cursor) {
4648 if (cursor.kind != CXCursor_InclusionDirective)
4649 return 0;
4650
4651 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4652 return (void *)ID->getFile();
4653}
4654
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004655} // end: extern "C"
4656
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004657
4658//===----------------------------------------------------------------------===//
4659// C++ AST instrospection.
4660//===----------------------------------------------------------------------===//
4661
4662extern "C" {
4663unsigned clang_CXXMethod_isStatic(CXCursor C) {
4664 if (!clang_isDeclaration(C.kind))
4665 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004666
4667 CXXMethodDecl *Method = 0;
4668 Decl *D = cxcursor::getCursorDecl(C);
4669 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4670 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4671 else
4672 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4673 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004674}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004675
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004676} // end: extern "C"
4677
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004678//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004679// Attribute introspection.
4680//===----------------------------------------------------------------------===//
4681
4682extern "C" {
4683CXType clang_getIBOutletCollectionType(CXCursor C) {
4684 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004685 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004686
4687 IBOutletCollectionAttr *A =
4688 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4689
Ted Kremeneka60ed472010-11-16 08:15:36 +00004690 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004691}
4692} // end: extern "C"
4693
4694//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004695// Misc. utility functions.
4696//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004697
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004698/// Default to using an 8 MB stack size on "safety" threads.
4699static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004700
4701namespace clang {
4702
4703bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004704 void (*Fn)(void*), void *UserData,
4705 unsigned Size) {
4706 if (!Size)
4707 Size = GetSafetyThreadStackSize();
4708 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004709 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4710 return CRC.RunSafely(Fn, UserData);
4711}
4712
4713unsigned GetSafetyThreadStackSize() {
4714 return SafetyStackThreadSize;
4715}
4716
4717void SetSafetyThreadStackSize(unsigned Value) {
4718 SafetyStackThreadSize = Value;
4719}
4720
4721}
4722
Ted Kremenek04bb7162010-01-22 22:44:15 +00004723extern "C" {
4724
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004725CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004726 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004727}
4728
4729} // end: extern "C"