blob: 1256b6381f2898d0540ca014ec820227f87ebb79 [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"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000043#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000044#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000045#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000046#include "llvm/System/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,
143 DeclarationNameInfoVisitKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000144protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000145 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000146 CXCursor parent;
147 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000148 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
149 : parent(C), K(k) {
150 data[0] = d1;
151 data[1] = d2;
152 data[2] = d3;
153 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000154public:
155 Kind getKind() const { return K; }
156 const CXCursor &getParent() const { return parent; }
157 static bool classof(VisitorJob *VJ) { return true; }
158};
159
160typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
161
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000163class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000164 public TypeLocVisitor<CursorVisitor, bool>,
165 public StmtVisitor<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;
Douglas Gregora59e3902010-01-21 23:27:09 +0000204 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
206 /// \brief Determine whether this particular source range comes before, comes
207 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000209 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
211
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000212 class SetParentRAII {
213 CXCursor &Parent;
214 Decl *&StmtParent;
215 CXCursor OldParent;
216
217 public:
218 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
219 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
220 {
221 Parent = NewParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225
226 ~SetParentRAII() {
227 Parent = OldParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231 };
232
Steve Naroff89922f82009-08-31 00:59:03 +0000233public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000234 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
235 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000238 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
239 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000240 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
241 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 {
243 Parent.kind = CXCursor_NoDeclFound;
244 Parent.data[0] = 0;
245 Parent.data[1] = 0;
246 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000249
Ted Kremenekd1ded662010-11-15 23:31:32 +0000250 ~CursorVisitor() {
251 // Free the pre-allocated worklists for data-recursion.
252 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
253 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
254 delete *I;
255 }
256 }
257
Ted Kremeneka60ed472010-11-16 08:15:36 +0000258 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
259 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000260
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000261 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000262
263 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
264 getPreprocessedEntities();
265
Douglas Gregorb1373d02010-01-20 20:59:29 +0000266 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000267
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000268 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000269 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000270 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000271 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000272 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000274 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
275 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000276 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000277 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000278 bool VisitClassTemplatePartialSpecializationDecl(
279 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000280 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000281 bool VisitEnumConstantDecl(EnumConstantDecl *D);
282 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
283 bool VisitFunctionDecl(FunctionDecl *ND);
284 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000285 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000286 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000287 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000288 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000289 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
291 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
292 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
293 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000294 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000295 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
296 bool VisitObjCImplDecl(ObjCImplDecl *D);
297 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
298 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000299 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
300 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
301 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000302 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000303 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000304 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000305 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000306 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000307 bool VisitUsingDecl(UsingDecl *D);
308 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
309 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000310
Douglas Gregor01829d32010-08-31 14:41:23 +0000311 // Name visitor
312 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000313 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000314
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000315 // Template visitors
316 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000317 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000318 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
319
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000320 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000321 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000323 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000324 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
325 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000326 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000327 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000328 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000329 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
330 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
Douglas Gregora59e3902010-01-21 23:27:09 +0000343 // Statement visitors
344 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000345
Douglas Gregor336fd812010-01-23 00:40:08 +0000346 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000347 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000348 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000349 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000350
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000351 // Data-recursive visitor functions.
352 bool IsInRegionOfInterest(CXCursor C);
353 bool RunVisitorWorkList(VisitorWorkList &WL);
354 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Benjamin Kramere645c722010-11-16 15:45:46 +0000355 LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000356};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000357
Ted Kremenekab188932010-01-05 19:32:54 +0000358} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000359
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000360static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000361static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
362
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000363
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000364RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000365 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366}
367
Douglas Gregorb1373d02010-01-20 20:59:29 +0000368/// \brief Visit the given cursor and, if requested by the visitor,
369/// its children.
370///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371/// \param Cursor the cursor to visit.
372///
373/// \param CheckRegionOfInterest if true, then the caller already checked that
374/// this cursor is within the region of interest.
375///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376/// \returns true if the visitation should be aborted, false if it
377/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000378bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379 if (clang_isInvalid(Cursor.kind))
380 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000381
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382 if (clang_isDeclaration(Cursor.kind)) {
383 Decl *D = getCursorDecl(Cursor);
384 assert(D && "Invalid declaration cursor");
385 if (D->getPCHLevel() > MaxPCHLevel)
386 return false;
387
388 if (D->isImplicit())
389 return false;
390 }
391
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392 // If we have a range of interest, and this cursor doesn't intersect with it,
393 // we're done.
394 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000395 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000396 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000397 return false;
398 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000399
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 switch (Visitor(Cursor, Parent, ClientData)) {
401 case CXChildVisit_Break:
402 return true;
403
404 case CXChildVisit_Continue:
405 return false;
406
407 case CXChildVisit_Recurse:
408 return VisitChildren(Cursor);
409 }
410
Douglas Gregorfd643772010-01-25 16:45:46 +0000411 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412}
413
Douglas Gregor788f5a12010-03-20 00:41:21 +0000414std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
415CursorVisitor::getPreprocessedEntities() {
416 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000417 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000418
419 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000420 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000421
422 // There is no region of interest; we have to walk everything.
423 if (RegionOfInterest.isInvalid())
424 return std::make_pair(PPRec.begin(OnlyLocalDecls),
425 PPRec.end(OnlyLocalDecls));
426
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)
436 return std::make_pair(PPRec.begin(OnlyLocalDecls),
437 PPRec.end(OnlyLocalDecls));
438
439 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000440 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000441 if (ByFileMap.empty()) {
442 // Build the mapping from files to sets of preprocessed entities.
443 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
444 EEnd = PPRec.end(OnlyLocalDecls);
445 E != EEnd; ++E) {
446 std::pair<FileID, unsigned> P
447 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
448 ByFileMap[P.first].push_back(*E);
449 }
450 }
451
452 return std::make_pair(ByFileMap[Begin.first].begin(),
453 ByFileMap[Begin.first].end());
454}
455
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000457///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458/// \returns true if the visitation should be aborted, false if it
459/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000461 if (clang_isReference(Cursor.kind)) {
462 // By definition, references have no children.
463 return false;
464 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
466 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000468 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000469
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470 if (clang_isDeclaration(Cursor.kind)) {
471 Decl *D = getCursorDecl(Cursor);
472 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000473 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000474 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000475
Douglas Gregora59e3902010-01-21 23:27:09 +0000476 if (clang_isStatement(Cursor.kind))
477 return Visit(getCursorStmt(Cursor));
478 if (clang_isExpression(Cursor.kind))
479 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000480
Douglas Gregorb1373d02010-01-20 20:59:29 +0000481 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000482 CXTranslationUnit tu = getCursorTU(Cursor);
483 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000484 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
485 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000486 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
487 TLEnd = CXXUnit->top_level_end();
488 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000489 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000490 return true;
491 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 } else if (VisitDeclContext(
493 CXXUnit->getASTContext().getTranslationUnitDecl()))
494 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000495
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000497 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 // FIXME: Once we have the ability to deserialize a preprocessing record,
499 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000500 PreprocessingRecord::iterator E, EEnd;
501 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000503 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000505
Douglas Gregor0396f462010-03-19 05:22:59 +0000506 continue;
507 }
508
509 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000510 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000511 return true;
512
513 continue;
514 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000515
516 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000517 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000518 return true;
519
520 continue;
521 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000522 }
523 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000524 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000526
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528 return false;
529}
530
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000531bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000532 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
533 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000534
Ted Kremenek664cffd2010-07-22 11:30:19 +0000535 if (Stmt *Body = B->getBody())
536 return Visit(MakeCXCursor(Body, StmtParent, TU));
537
538 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000539}
540
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000541llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
542 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000543 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000544 if (Range.isInvalid())
545 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000546
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000547 switch (CompareRegionOfInterest(Range)) {
548 case RangeBefore:
549 // This declaration comes before the region of interest; skip it.
550 return llvm::Optional<bool>();
551
552 case RangeAfter:
553 // This declaration comes after the region of interest; we're done.
554 return false;
555
556 case RangeOverlap:
557 // This declaration overlaps the region of interest; visit it.
558 break;
559 }
560 }
561 return true;
562}
563
564bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
565 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
566
567 // FIXME: Eventually remove. This part of a hack to support proper
568 // iteration over all Decls contained lexically within an ObjC container.
569 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
570 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
571
572 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000573 Decl *D = *I;
574 if (D->getLexicalDeclContext() != DC)
575 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000576 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000577 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
578 if (!V.hasValue())
579 continue;
580 if (!V.getValue())
581 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000582 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return true;
584 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000586}
587
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000588bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
589 llvm_unreachable("Translation units are visited directly by Visit()");
590 return false;
591}
592
593bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
594 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
595 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000596
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000597 return false;
598}
599
600bool CursorVisitor::VisitTagDecl(TagDecl *D) {
601 return VisitDeclContext(D);
602}
603
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000604bool CursorVisitor::VisitClassTemplateSpecializationDecl(
605 ClassTemplateSpecializationDecl *D) {
606 bool ShouldVisitBody = false;
607 switch (D->getSpecializationKind()) {
608 case TSK_Undeclared:
609 case TSK_ImplicitInstantiation:
610 // Nothing to visit
611 return false;
612
613 case TSK_ExplicitInstantiationDeclaration:
614 case TSK_ExplicitInstantiationDefinition:
615 break;
616
617 case TSK_ExplicitSpecialization:
618 ShouldVisitBody = true;
619 break;
620 }
621
622 // Visit the template arguments used in the specialization.
623 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
624 TypeLoc TL = SpecType->getTypeLoc();
625 if (TemplateSpecializationTypeLoc *TSTLoc
626 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
627 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
628 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
629 return true;
630 }
631 }
632
633 if (ShouldVisitBody && VisitCXXRecordDecl(D))
634 return true;
635
636 return false;
637}
638
Douglas Gregor74dbe642010-08-31 19:31:58 +0000639bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
640 ClassTemplatePartialSpecializationDecl *D) {
641 // FIXME: Visit the "outer" template parameter lists on the TagDecl
642 // before visiting these template parameters.
643 if (VisitTemplateParameters(D->getTemplateParameters()))
644 return true;
645
646 // Visit the partial specialization arguments.
647 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
648 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
649 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
650 return true;
651
652 return VisitCXXRecordDecl(D);
653}
654
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000655bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000656 // Visit the default argument.
657 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
658 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
659 if (Visit(DefArg->getTypeLoc()))
660 return true;
661
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000662 return false;
663}
664
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000665bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
666 if (Expr *Init = D->getInitExpr())
667 return Visit(MakeCXCursor(Init, StmtParent, TU));
668 return false;
669}
670
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000671bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
672 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
673 if (Visit(TSInfo->getTypeLoc()))
674 return true;
675
676 return false;
677}
678
Douglas Gregora67e03f2010-09-09 21:42:20 +0000679/// \brief Compare two base or member initializers based on their source order.
680static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
681 CXXBaseOrMemberInitializer const * const *X
682 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
683 CXXBaseOrMemberInitializer const * const *Y
684 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
685
686 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
687 return -1;
688 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
689 return 1;
690 else
691 return 0;
692}
693
Douglas Gregorb1373d02010-01-20 20:59:29 +0000694bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000695 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
696 // Visit the function declaration's syntactic components in the order
697 // written. This requires a bit of work.
698 TypeLoc TL = TSInfo->getTypeLoc();
699 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
700
701 // If we have a function declared directly (without the use of a typedef),
702 // visit just the return type. Otherwise, just visit the function's type
703 // now.
704 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
705 (!FTL && Visit(TL)))
706 return true;
707
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000708 // Visit the nested-name-specifier, if present.
709 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
710 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
711 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000712
713 // Visit the declaration name.
714 if (VisitDeclarationNameInfo(ND->getNameInfo()))
715 return true;
716
717 // FIXME: Visit explicitly-specified template arguments!
718
719 // Visit the function parameters, if we have a function type.
720 if (FTL && VisitFunctionTypeLoc(*FTL, true))
721 return true;
722
723 // FIXME: Attributes?
724 }
725
Douglas Gregora67e03f2010-09-09 21:42:20 +0000726 if (ND->isThisDeclarationADefinition()) {
727 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
728 // Find the initializers that were written in the source.
729 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
730 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
731 IEnd = Constructor->init_end();
732 I != IEnd; ++I) {
733 if (!(*I)->isWritten())
734 continue;
735
736 WrittenInits.push_back(*I);
737 }
738
739 // Sort the initializers in source order
740 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
741 &CompareCXXBaseOrMemberInitializers);
742
743 // Visit the initializers in source order
744 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
745 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
746 if (Init->isMemberInitializer()) {
747 if (Visit(MakeCursorMemberRef(Init->getMember(),
748 Init->getMemberLocation(), TU)))
749 return true;
750 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
751 if (Visit(BaseInfo->getTypeLoc()))
752 return true;
753 }
754
755 // Visit the initializer value.
756 if (Expr *Initializer = Init->getInit())
757 if (Visit(MakeCXCursor(Initializer, ND, TU)))
758 return true;
759 }
760 }
761
762 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
763 return true;
764 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000765
Douglas Gregorb1373d02010-01-20 20:59:29 +0000766 return false;
767}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000768
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000769bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
770 if (VisitDeclaratorDecl(D))
771 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000772
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000773 if (Expr *BitWidth = D->getBitWidth())
774 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000775
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000776 return false;
777}
778
779bool CursorVisitor::VisitVarDecl(VarDecl *D) {
780 if (VisitDeclaratorDecl(D))
781 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000783 if (Expr *Init = D->getInit())
784 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000786 return false;
787}
788
Douglas Gregor84b51d72010-09-01 20:16:53 +0000789bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
790 if (VisitDeclaratorDecl(D))
791 return true;
792
793 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
794 if (Expr *DefArg = D->getDefaultArgument())
795 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
796
797 return false;
798}
799
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000800bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
801 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
802 // before visiting these template parameters.
803 if (VisitTemplateParameters(D->getTemplateParameters()))
804 return true;
805
806 return VisitFunctionDecl(D->getTemplatedDecl());
807}
808
Douglas Gregor39d6f072010-08-31 19:02:00 +0000809bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
810 // FIXME: Visit the "outer" template parameter lists on the TagDecl
811 // before visiting these template parameters.
812 if (VisitTemplateParameters(D->getTemplateParameters()))
813 return true;
814
815 return VisitCXXRecordDecl(D->getTemplatedDecl());
816}
817
Douglas Gregor84b51d72010-09-01 20:16:53 +0000818bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
819 if (VisitTemplateParameters(D->getTemplateParameters()))
820 return true;
821
822 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
823 VisitTemplateArgumentLoc(D->getDefaultArgument()))
824 return true;
825
826 return false;
827}
828
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000829bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000830 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
831 if (Visit(TSInfo->getTypeLoc()))
832 return true;
833
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000834 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000835 PEnd = ND->param_end();
836 P != PEnd; ++P) {
837 if (Visit(MakeCXCursor(*P, TU)))
838 return true;
839 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841 if (ND->isThisDeclarationADefinition() &&
842 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
843 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000844
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000845 return false;
846}
847
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000848namespace {
849 struct ContainerDeclsSort {
850 SourceManager &SM;
851 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
852 bool operator()(Decl *A, Decl *B) {
853 SourceLocation L_A = A->getLocStart();
854 SourceLocation L_B = B->getLocStart();
855 assert(L_A.isValid() && L_B.isValid());
856 return SM.isBeforeInTranslationUnit(L_A, L_B);
857 }
858 };
859}
860
Douglas Gregora59e3902010-01-21 23:27:09 +0000861bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000862 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
863 // an @implementation can lexically contain Decls that are not properly
864 // nested in the AST. When we identify such cases, we need to retrofit
865 // this nesting here.
866 if (!DI_current)
867 return VisitDeclContext(D);
868
869 // Scan the Decls that immediately come after the container
870 // in the current DeclContext. If any fall within the
871 // container's lexical region, stash them into a vector
872 // for later processing.
873 llvm::SmallVector<Decl *, 24> DeclsInContainer;
874 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000875 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000876 if (EndLoc.isValid()) {
877 DeclContext::decl_iterator next = *DI_current;
878 while (++next != DE_current) {
879 Decl *D_next = *next;
880 if (!D_next)
881 break;
882 SourceLocation L = D_next->getLocStart();
883 if (!L.isValid())
884 break;
885 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
886 *DI_current = next;
887 DeclsInContainer.push_back(D_next);
888 continue;
889 }
890 break;
891 }
892 }
893
894 // The common case.
895 if (DeclsInContainer.empty())
896 return VisitDeclContext(D);
897
898 // Get all the Decls in the DeclContext, and sort them with the
899 // additional ones we've collected. Then visit them.
900 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
901 I!=E; ++I) {
902 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000903 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
904 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000905 continue;
906 DeclsInContainer.push_back(subDecl);
907 }
908
909 // Now sort the Decls so that they appear in lexical order.
910 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
911 ContainerDeclsSort(SM));
912
913 // Now visit the decls.
914 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
915 E = DeclsInContainer.end(); I != E; ++I) {
916 CXCursor Cursor = MakeCXCursor(*I, TU);
917 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
918 if (!V.hasValue())
919 continue;
920 if (!V.getValue())
921 return false;
922 if (Visit(Cursor, true))
923 return true;
924 }
925 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000926}
927
Douglas Gregorb1373d02010-01-20 20:59:29 +0000928bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000929 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
930 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000931 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000932
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000933 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
934 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
935 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000936 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000937 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000938
Douglas Gregora59e3902010-01-21 23:27:09 +0000939 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000940}
941
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000942bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
943 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
944 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
945 E = PID->protocol_end(); I != E; ++I, ++PL)
946 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
947 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000949 return VisitObjCContainerDecl(PID);
950}
951
Ted Kremenek23173d72010-05-18 21:09:07 +0000952bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000953 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000954 return true;
955
Ted Kremenek23173d72010-05-18 21:09:07 +0000956 // FIXME: This implements a workaround with @property declarations also being
957 // installed in the DeclContext for the @interface. Eventually this code
958 // should be removed.
959 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
960 if (!CDecl || !CDecl->IsClassExtension())
961 return false;
962
963 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
964 if (!ID)
965 return false;
966
967 IdentifierInfo *PropertyId = PD->getIdentifier();
968 ObjCPropertyDecl *prevDecl =
969 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
970
971 if (!prevDecl)
972 return false;
973
974 // Visit synthesized methods since they will be skipped when visiting
975 // the @interface.
976 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000977 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000978 if (Visit(MakeCXCursor(MD, TU)))
979 return true;
980
981 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000982 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000983 if (Visit(MakeCXCursor(MD, TU)))
984 return true;
985
986 return false;
987}
988
Douglas Gregorb1373d02010-01-20 20:59:29 +0000989bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000990 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000991 if (D->getSuperClass() &&
992 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000994 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000995 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000996
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000997 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
998 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
999 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001000 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001001 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001002
Douglas Gregora59e3902010-01-21 23:27:09 +00001003 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001004}
1005
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001006bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1007 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001008}
1009
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001010bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001011 // 'ID' could be null when dealing with invalid code.
1012 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1013 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001016 return VisitObjCImplDecl(D);
1017}
1018
1019bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1020#if 0
1021 // Issue callbacks for super class.
1022 // FIXME: No source location information!
1023 if (D->getSuperClass() &&
1024 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026 TU)))
1027 return true;
1028#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001029
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001030 return VisitObjCImplDecl(D);
1031}
1032
1033bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1034 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1035 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1036 E = D->protocol_end();
1037 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001038 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001039 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001040
1041 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001042}
1043
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001044bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1045 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1046 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1047 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001049 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001050}
1051
Douglas Gregora4ffd852010-11-17 01:03:52 +00001052bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1053 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1054 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1055
1056 return false;
1057}
1058
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001059bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1060 return VisitDeclContext(D);
1061}
1062
Douglas Gregor69319002010-08-31 23:48:11 +00001063bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001064 // Visit nested-name-specifier.
1065 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1066 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1067 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001068
1069 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1070 D->getTargetNameLoc(), TU));
1071}
1072
Douglas Gregor7e242562010-09-01 19:52:22 +00001073bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001074 // Visit nested-name-specifier.
1075 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1076 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1077 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001078
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001079 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1080 return true;
1081
Douglas Gregor7e242562010-09-01 19:52:22 +00001082 return VisitDeclarationNameInfo(D->getNameInfo());
1083}
1084
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001085bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 // Visit nested-name-specifier.
1087 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1088 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1089 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001090
1091 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1092 D->getIdentLocation(), TU));
1093}
1094
Douglas Gregor7e242562010-09-01 19:52:22 +00001095bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 // Visit nested-name-specifier.
1097 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1098 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1099 return true;
1100
Douglas Gregor7e242562010-09-01 19:52:22 +00001101 return VisitDeclarationNameInfo(D->getNameInfo());
1102}
1103
1104bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1105 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 // Visit nested-name-specifier.
1107 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1108 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1109 return true;
1110
Douglas Gregor7e242562010-09-01 19:52:22 +00001111 return false;
1112}
1113
Douglas Gregor01829d32010-08-31 14:41:23 +00001114bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1115 switch (Name.getName().getNameKind()) {
1116 case clang::DeclarationName::Identifier:
1117 case clang::DeclarationName::CXXLiteralOperatorName:
1118 case clang::DeclarationName::CXXOperatorName:
1119 case clang::DeclarationName::CXXUsingDirective:
1120 return false;
1121
1122 case clang::DeclarationName::CXXConstructorName:
1123 case clang::DeclarationName::CXXDestructorName:
1124 case clang::DeclarationName::CXXConversionFunctionName:
1125 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1126 return Visit(TSInfo->getTypeLoc());
1127 return false;
1128
1129 case clang::DeclarationName::ObjCZeroArgSelector:
1130 case clang::DeclarationName::ObjCOneArgSelector:
1131 case clang::DeclarationName::ObjCMultiArgSelector:
1132 // FIXME: Per-identifier location info?
1133 return false;
1134 }
1135
1136 return false;
1137}
1138
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001139bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1140 SourceRange Range) {
1141 // FIXME: This whole routine is a hack to work around the lack of proper
1142 // source information in nested-name-specifiers (PR5791). Since we do have
1143 // a beginning source location, we can visit the first component of the
1144 // nested-name-specifier, if it's a single-token component.
1145 if (!NNS)
1146 return false;
1147
1148 // Get the first component in the nested-name-specifier.
1149 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1150 NNS = Prefix;
1151
1152 switch (NNS->getKind()) {
1153 case NestedNameSpecifier::Namespace:
1154 // FIXME: The token at this source location might actually have been a
1155 // namespace alias, but we don't model that. Lame!
1156 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1157 TU));
1158
1159 case NestedNameSpecifier::TypeSpec: {
1160 // If the type has a form where we know that the beginning of the source
1161 // range matches up with a reference cursor. Visit the appropriate reference
1162 // cursor.
1163 Type *T = NNS->getAsType();
1164 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1165 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1166 if (const TagType *Tag = dyn_cast<TagType>(T))
1167 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1168 if (const TemplateSpecializationType *TST
1169 = dyn_cast<TemplateSpecializationType>(T))
1170 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1171 break;
1172 }
1173
1174 case NestedNameSpecifier::TypeSpecWithTemplate:
1175 case NestedNameSpecifier::Global:
1176 case NestedNameSpecifier::Identifier:
1177 break;
1178 }
1179
1180 return false;
1181}
1182
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001183bool CursorVisitor::VisitTemplateParameters(
1184 const TemplateParameterList *Params) {
1185 if (!Params)
1186 return false;
1187
1188 for (TemplateParameterList::const_iterator P = Params->begin(),
1189 PEnd = Params->end();
1190 P != PEnd; ++P) {
1191 if (Visit(MakeCXCursor(*P, TU)))
1192 return true;
1193 }
1194
1195 return false;
1196}
1197
Douglas Gregor0b36e612010-08-31 20:37:03 +00001198bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1199 switch (Name.getKind()) {
1200 case TemplateName::Template:
1201 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1202
1203 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001204 // Visit the overloaded template set.
1205 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1206 return true;
1207
Douglas Gregor0b36e612010-08-31 20:37:03 +00001208 return false;
1209
1210 case TemplateName::DependentTemplate:
1211 // FIXME: Visit nested-name-specifier.
1212 return false;
1213
1214 case TemplateName::QualifiedTemplate:
1215 // FIXME: Visit nested-name-specifier.
1216 return Visit(MakeCursorTemplateRef(
1217 Name.getAsQualifiedTemplateName()->getDecl(),
1218 Loc, TU));
1219 }
1220
1221 return false;
1222}
1223
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001224bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1225 switch (TAL.getArgument().getKind()) {
1226 case TemplateArgument::Null:
1227 case TemplateArgument::Integral:
1228 return false;
1229
1230 case TemplateArgument::Pack:
1231 // FIXME: Implement when variadic templates come along.
1232 return false;
1233
1234 case TemplateArgument::Type:
1235 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1236 return Visit(TSInfo->getTypeLoc());
1237 return false;
1238
1239 case TemplateArgument::Declaration:
1240 if (Expr *E = TAL.getSourceDeclExpression())
1241 return Visit(MakeCXCursor(E, StmtParent, TU));
1242 return false;
1243
1244 case TemplateArgument::Expression:
1245 if (Expr *E = TAL.getSourceExpression())
1246 return Visit(MakeCXCursor(E, StmtParent, TU));
1247 return false;
1248
1249 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001250 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1251 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001252 }
1253
1254 return false;
1255}
1256
Ted Kremeneka0536d82010-05-07 01:04:29 +00001257bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1258 return VisitDeclContext(D);
1259}
1260
Douglas Gregor01829d32010-08-31 14:41:23 +00001261bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1262 return Visit(TL.getUnqualifiedLoc());
1263}
1264
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001265bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001266 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267
1268 // Some builtin types (such as Objective-C's "id", "sel", and
1269 // "Class") have associated declarations. Create cursors for those.
1270 QualType VisitType;
1271 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001272 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001274 case BuiltinType::Char_U:
1275 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 case BuiltinType::Char16:
1277 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001278 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001279 case BuiltinType::UInt:
1280 case BuiltinType::ULong:
1281 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001282 case BuiltinType::UInt128:
1283 case BuiltinType::Char_S:
1284 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001285 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001286 case BuiltinType::Short:
1287 case BuiltinType::Int:
1288 case BuiltinType::Long:
1289 case BuiltinType::LongLong:
1290 case BuiltinType::Int128:
1291 case BuiltinType::Float:
1292 case BuiltinType::Double:
1293 case BuiltinType::LongDouble:
1294 case BuiltinType::NullPtr:
1295 case BuiltinType::Overload:
1296 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001297 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001298
1299 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001300 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001301
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001302 case BuiltinType::ObjCId:
1303 VisitType = Context.getObjCIdType();
1304 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001305
1306 case BuiltinType::ObjCClass:
1307 VisitType = Context.getObjCClassType();
1308 break;
1309
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001310 case BuiltinType::ObjCSel:
1311 VisitType = Context.getObjCSelType();
1312 break;
1313 }
1314
1315 if (!VisitType.isNull()) {
1316 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001317 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001318 TU));
1319 }
1320
1321 return false;
1322}
1323
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001324bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1325 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1326}
1327
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001328bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1329 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1330}
1331
1332bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1333 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1334}
1335
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001336bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001337 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001338 // no context information with which we can match up the depth/index in the
1339 // type to the appropriate
1340 return false;
1341}
1342
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001343bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1344 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1345 return true;
1346
John McCallc12c5bb2010-05-15 11:32:37 +00001347 return false;
1348}
1349
1350bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1351 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1352 return true;
1353
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001354 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1355 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1356 TU)))
1357 return true;
1358 }
1359
1360 return false;
1361}
1362
1363bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001364 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001365}
1366
1367bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1368 return Visit(TL.getPointeeLoc());
1369}
1370
1371bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1372 return Visit(TL.getPointeeLoc());
1373}
1374
1375bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1376 return Visit(TL.getPointeeLoc());
1377}
1378
1379bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001380 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381}
1382
1383bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385}
1386
Douglas Gregor01829d32010-08-31 14:41:23 +00001387bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1388 bool SkipResultType) {
1389 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390 return true;
1391
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001393 if (Decl *D = TL.getArg(I))
1394 if (Visit(MakeCXCursor(D, TU)))
1395 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001396
1397 return false;
1398}
1399
1400bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1401 if (Visit(TL.getElementLoc()))
1402 return true;
1403
1404 if (Expr *Size = TL.getSizeExpr())
1405 return Visit(MakeCXCursor(Size, StmtParent, TU));
1406
1407 return false;
1408}
1409
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001410bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1411 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001412 // Visit the template name.
1413 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1414 TL.getTemplateNameLoc()))
1415 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001416
1417 // Visit the template arguments.
1418 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1419 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1420 return true;
1421
1422 return false;
1423}
1424
Douglas Gregor2332c112010-01-21 20:48:56 +00001425bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1426 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1427}
1428
1429bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1430 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1431 return Visit(TSInfo->getTypeLoc());
1432
1433 return false;
1434}
1435
Douglas Gregora59e3902010-01-21 23:27:09 +00001436bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001437 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001438}
1439
Ted Kremenek3064ef92010-08-27 21:34:58 +00001440bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1441 if (D->isDefinition()) {
1442 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1443 E = D->bases_end(); I != E; ++I) {
1444 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1445 return true;
1446 }
1447 }
1448
1449 return VisitTagDecl(D);
1450}
1451
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001452bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001453 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001454 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1455 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001456
1457 // Visit the components of the offsetof expression.
1458 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1459 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1460 const OffsetOfNode &Node = E->getComponent(I);
1461 switch (Node.getKind()) {
1462 case OffsetOfNode::Array:
1463 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1464 StmtParent, TU)))
1465 return true;
1466 break;
1467
1468 case OffsetOfNode::Field:
1469 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1470 TU)))
1471 return true;
1472 break;
1473
1474 case OffsetOfNode::Identifier:
1475 case OffsetOfNode::Base:
1476 continue;
1477 }
1478 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001479
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001480 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001481}
1482
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001483bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1484 // Visit the designators.
1485 typedef DesignatedInitExpr::Designator Designator;
1486 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1487 DEnd = E->designators_end();
1488 D != DEnd; ++D) {
1489 if (D->isFieldDesignator()) {
1490 if (FieldDecl *Field = D->getField())
1491 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1492 return true;
1493
1494 continue;
1495 }
1496
1497 if (D->isArrayDesignator()) {
1498 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1499 return true;
1500
1501 continue;
1502 }
1503
1504 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1505 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1506 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1507 return true;
1508 }
1509
1510 // Visit the initializer value itself.
1511 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1512}
1513
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001514bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1515 // Visit base expression.
1516 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1517 return true;
1518
1519 // Visit the nested-name-specifier.
1520 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1521 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1522 return true;
1523
1524 // Visit the scope type that looks disturbingly like the nested-name-specifier
1525 // but isn't.
1526 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1527 if (Visit(TSInfo->getTypeLoc()))
1528 return true;
1529
1530 // Visit the name of the type being destroyed.
1531 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1532 if (Visit(TSInfo->getTypeLoc()))
1533 return true;
1534
1535 return false;
1536}
1537
Ted Kremenek09dfa372010-02-18 05:46:33 +00001538bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001539 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1540 i != e; ++i)
1541 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001542 return true;
1543
1544 return false;
1545}
1546
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001547//===----------------------------------------------------------------------===//
1548// Data-recursive visitor methods.
1549//===----------------------------------------------------------------------===//
1550
Ted Kremenek28a71942010-11-13 00:36:47 +00001551namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001552#define DEF_JOB(NAME, DATA, KIND)\
1553class NAME : public VisitorJob {\
1554public:\
1555 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1556 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001557 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001558};
1559
1560DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1561DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001562DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001563DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001564DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1565 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001566#undef DEF_JOB
1567
1568class DeclVisit : public VisitorJob {
1569public:
1570 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1571 VisitorJob(parent, VisitorJob::DeclVisitKind,
1572 d, isFirst ? (void*) 1 : (void*) 0) {}
1573 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001574 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001575 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001576 Decl *get() const { return static_cast<Decl*>(data[0]); }
1577 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001578};
Ted Kremenek035dc412010-11-13 00:36:50 +00001579class TypeLocVisit : public VisitorJob {
1580public:
1581 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1582 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1583 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1584
1585 static bool classof(const VisitorJob *VJ) {
1586 return VJ->getKind() == TypeLocVisitKind;
1587 }
1588
Ted Kremenek82f3c502010-11-15 22:23:26 +00001589 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001590 QualType T = QualType::getFromOpaquePtr(data[0]);
1591 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001592 }
1593};
1594
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001595class LabelRefVisit : public VisitorJob {
1596public:
1597 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1598 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1599 (void*) labelLoc.getRawEncoding()) {}
1600
1601 static bool classof(const VisitorJob *VJ) {
1602 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1603 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001604 LabelStmt *get() const { return static_cast<LabelStmt*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001605 SourceLocation getLoc() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001606 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); }
1607};
1608class NestedNameSpecifierVisit : public VisitorJob {
1609public:
1610 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1611 CXCursor parent)
1612 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
1613 NS, (void*) R.getBegin().getRawEncoding(),
1614 (void*) R.getEnd().getRawEncoding()) {}
1615 static bool classof(const VisitorJob *VJ) {
1616 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1617 }
1618 NestedNameSpecifier *get() const {
1619 return static_cast<NestedNameSpecifier*>(data[0]);
1620 }
1621 SourceRange getSourceRange() const {
1622 SourceLocation A =
1623 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1624 SourceLocation B =
1625 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1626 return SourceRange(A, B);
1627 }
1628};
1629class DeclarationNameInfoVisit : public VisitorJob {
1630public:
1631 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1632 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1633 static bool classof(const VisitorJob *VJ) {
1634 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1635 }
1636 DeclarationNameInfo get() const {
1637 Stmt *S = static_cast<Stmt*>(data[0]);
1638 switch (S->getStmtClass()) {
1639 default:
1640 llvm_unreachable("Unhandled Stmt");
1641 case Stmt::CXXDependentScopeMemberExprClass:
1642 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1643 case Stmt::DependentScopeDeclRefExprClass:
1644 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1645 }
1646 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001647};
1648
Ted Kremenek28a71942010-11-13 00:36:47 +00001649class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1650 VisitorWorkList &WL;
1651 CXCursor Parent;
1652public:
1653 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1654 : WL(wl), Parent(parent) {}
1655
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001656 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001657 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001658 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001659 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001660 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001661 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001662 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001663 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001664 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001665 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001666 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001667 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001668 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001669 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001670 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001671 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001672 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1673 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001674 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001675 void VisitIfStmt(IfStmt *If);
1676 void VisitInitListExpr(InitListExpr *IE);
1677 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001678 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001679 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1680 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001681 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001682 void VisitStmt(Stmt *S);
1683 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001684 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001685 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001686 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001687 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001688 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001689
1690private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001691 void AddDeclarationNameInfo(Stmt *S);
1692 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001693 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenek28a71942010-11-13 00:36:47 +00001694 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001695 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696 void AddTypeLoc(TypeSourceInfo *TI);
1697 void EnqueueChildren(Stmt *S);
1698};
1699} // end anonyous namespace
1700
Ted Kremenekf64d8032010-11-18 00:02:32 +00001701void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1702 // 'S' should always be non-null, since it comes from the
1703 // statement we are visiting.
1704 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1705}
1706void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1707 SourceRange R) {
1708 if (N)
1709 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1710}
Ted Kremenek28a71942010-11-13 00:36:47 +00001711void EnqueueVisitor::AddStmt(Stmt *S) {
1712 if (S)
1713 WL.push_back(StmtVisit(S, Parent));
1714}
Ted Kremenek035dc412010-11-13 00:36:50 +00001715void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001716 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001717 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001718}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001719void EnqueueVisitor::
1720 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1721 if (A)
1722 WL.push_back(ExplicitTemplateArgsVisit(
1723 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1724}
Ted Kremenek28a71942010-11-13 00:36:47 +00001725void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1726 if (TI)
1727 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1728 }
1729void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001730 unsigned size = WL.size();
1731 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1732 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001733 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001734 }
1735 if (size == WL.size())
1736 return;
1737 // Now reverse the entries we just added. This will match the DFS
1738 // ordering performed by the worklist.
1739 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1740 std::reverse(I, E);
1741}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001742void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1743 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1744}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001745void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1746 AddDecl(B->getBlockDecl());
1747}
Ted Kremenek28a71942010-11-13 00:36:47 +00001748void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1749 EnqueueChildren(E);
1750 AddTypeLoc(E->getTypeSourceInfo());
1751}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001752void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1753 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1754 E = S->body_rend(); I != E; ++I) {
1755 AddStmt(*I);
1756 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001757}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001758void EnqueueVisitor::
1759VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1760 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1761 AddDeclarationNameInfo(E);
1762 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1763 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1764 if (!E->isImplicitAccess())
1765 AddStmt(E->getBase());
1766}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001767void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1768 // Enqueue the initializer or constructor arguments.
1769 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1770 AddStmt(E->getConstructorArg(I-1));
1771 // Enqueue the array size, if any.
1772 AddStmt(E->getArraySize());
1773 // Enqueue the allocated type.
1774 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1775 // Enqueue the placement arguments.
1776 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1777 AddStmt(E->getPlacementArg(I-1));
1778}
Ted Kremenek28a71942010-11-13 00:36:47 +00001779void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001780 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1781 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001782 AddStmt(CE->getCallee());
1783 AddStmt(CE->getArg(0));
1784}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001785void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1786 AddTypeLoc(E->getTypeSourceInfo());
1787}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001788void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1789 EnqueueChildren(E);
1790 AddTypeLoc(E->getTypeSourceInfo());
1791}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001792void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1793 EnqueueChildren(E);
1794 if (E->isTypeOperand())
1795 AddTypeLoc(E->getTypeOperandSourceInfo());
1796}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001797
1798void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1799 *E) {
1800 EnqueueChildren(E);
1801 AddTypeLoc(E->getTypeSourceInfo());
1802}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001803void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1804 EnqueueChildren(E);
1805 if (E->isTypeOperand())
1806 AddTypeLoc(E->getTypeOperandSourceInfo());
1807}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001808void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001809 if (DR->hasExplicitTemplateArgs()) {
1810 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1811 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001812 WL.push_back(DeclRefExprParts(DR, Parent));
1813}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001814void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1815 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1816 AddDeclarationNameInfo(E);
1817 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1818 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1819}
Ted Kremenek035dc412010-11-13 00:36:50 +00001820void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1821 unsigned size = WL.size();
1822 bool isFirst = true;
1823 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1824 D != DEnd; ++D) {
1825 AddDecl(*D, isFirst);
1826 isFirst = false;
1827 }
1828 if (size == WL.size())
1829 return;
1830 // Now reverse the entries we just added. This will match the DFS
1831 // ordering performed by the worklist.
1832 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1833 std::reverse(I, E);
1834}
Ted Kremenek28a71942010-11-13 00:36:47 +00001835void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1836 EnqueueChildren(E);
1837 AddTypeLoc(E->getTypeInfoAsWritten());
1838}
1839void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1840 AddStmt(FS->getBody());
1841 AddStmt(FS->getInc());
1842 AddStmt(FS->getCond());
1843 AddDecl(FS->getConditionVariable());
1844 AddStmt(FS->getInit());
1845}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001846void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1847 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1848}
Ted Kremenek28a71942010-11-13 00:36:47 +00001849void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1850 AddStmt(If->getElse());
1851 AddStmt(If->getThen());
1852 AddStmt(If->getCond());
1853 AddDecl(If->getConditionVariable());
1854}
1855void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1856 // We care about the syntactic form of the initializer list, only.
1857 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1858 IE = Syntactic;
1859 EnqueueChildren(IE);
1860}
1861void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001862 WL.push_back(MemberExprParts(M, Parent));
1863
1864 // If the base of the member access expression is an implicit 'this', don't
1865 // visit it.
1866 // FIXME: If we ever want to show these implicit accesses, this will be
1867 // unfortunate. However, clang_getCursor() relies on this behavior.
1868 if (CXXThisExpr *This
1869 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1870 if (This->isImplicit())
1871 return;
1872
Ted Kremenek28a71942010-11-13 00:36:47 +00001873 AddStmt(M->getBase());
1874}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001875void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1876 AddTypeLoc(E->getEncodedTypeSourceInfo());
1877}
Ted Kremenek28a71942010-11-13 00:36:47 +00001878void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1879 EnqueueChildren(M);
1880 AddTypeLoc(M->getClassReceiverTypeInfo());
1881}
1882void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001883 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001884 WL.push_back(OverloadExprParts(E, Parent));
1885}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001886void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1887 EnqueueChildren(E);
1888 if (E->isArgumentType())
1889 AddTypeLoc(E->getArgumentTypeInfo());
1890}
Ted Kremenek28a71942010-11-13 00:36:47 +00001891void EnqueueVisitor::VisitStmt(Stmt *S) {
1892 EnqueueChildren(S);
1893}
1894void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1895 AddStmt(S->getBody());
1896 AddStmt(S->getCond());
1897 AddDecl(S->getConditionVariable());
1898}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001899void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1900 AddTypeLoc(E->getArgTInfo2());
1901 AddTypeLoc(E->getArgTInfo1());
1902}
1903
Ted Kremenek28a71942010-11-13 00:36:47 +00001904void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1905 AddStmt(W->getBody());
1906 AddStmt(W->getCond());
1907 AddDecl(W->getConditionVariable());
1908}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001909void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1910 AddTypeLoc(E->getQueriedTypeSourceInfo());
1911}
Ted Kremenek28a71942010-11-13 00:36:47 +00001912void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1913 VisitOverloadExpr(U);
1914 if (!U->isImplicitAccess())
1915 AddStmt(U->getBase());
1916}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001917void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1918 AddStmt(E->getSubExpr());
1919 AddTypeLoc(E->getWrittenTypeInfo());
1920}
Ted Kremenek60458782010-11-12 21:34:16 +00001921
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001922void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001923 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001924}
1925
1926bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1927 if (RegionOfInterest.isValid()) {
1928 SourceRange Range = getRawCursorExtent(C);
1929 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1930 return false;
1931 }
1932 return true;
1933}
1934
1935bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1936 while (!WL.empty()) {
1937 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001938 VisitorJob LI = WL.back();
1939 WL.pop_back();
1940
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001941 // Set the Parent field, then back to its old value once we're done.
1942 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1943
1944 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001945 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001946 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001947 if (!D)
1948 continue;
1949
1950 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001951 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001952 return true;
1953
1954 continue;
1955 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001956 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1957 const ExplicitTemplateArgumentList *ArgList =
1958 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1959 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1960 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1961 Arg != ArgEnd; ++Arg) {
1962 if (VisitTemplateArgumentLoc(*Arg))
1963 return true;
1964 }
1965 continue;
1966 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001967 case VisitorJob::TypeLocVisitKind: {
1968 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001969 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001970 return true;
1971 continue;
1972 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001973 case VisitorJob::LabelRefVisitKind: {
1974 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1975 if (Visit(MakeCursorLabelRef(LS,
1976 cast<LabelRefVisit>(&LI)->getLoc(),
1977 TU)))
1978 return true;
1979 continue;
1980 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001981 case VisitorJob::NestedNameSpecifierVisitKind: {
1982 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
1983 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
1984 return true;
1985 continue;
1986 }
1987 case VisitorJob::DeclarationNameInfoVisitKind: {
1988 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
1989 ->get()))
1990 return true;
1991 continue;
1992 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001993 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001994 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001995 if (!S)
1996 continue;
1997
Ted Kremenekf1107452010-11-12 18:26:56 +00001998 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001999 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
2000
2001 switch (S->getStmtClass()) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00002002 // Cases not yet handled by the data-recursion
2003 // algorithm.
2004 case Stmt::OffsetOfExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00002005 case Stmt::DesignatedInitExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00002006 case Stmt::CXXPseudoDestructorExprClass:
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00002007 if (Visit(Cursor))
2008 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00002009 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00002010 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002011 if (!IsInRegionOfInterest(Cursor))
2012 continue;
2013 switch (Visitor(Cursor, Parent, ClientData)) {
2014 case CXChildVisit_Break:
2015 return true;
2016 case CXChildVisit_Continue:
2017 break;
2018 case CXChildVisit_Recurse:
2019 EnqueueWorkList(WL, S);
2020 break;
2021 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002022 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002023 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002024 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002025 }
2026 case VisitorJob::MemberExprPartsKind: {
2027 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002028 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002029
2030 // Visit the nested-name-specifier
2031 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2032 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2033 return true;
2034
2035 // Visit the declaration name.
2036 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2037 return true;
2038
2039 // Visit the explicitly-specified template arguments, if any.
2040 if (M->hasExplicitTemplateArgs()) {
2041 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2042 *ArgEnd = Arg + M->getNumTemplateArgs();
2043 Arg != ArgEnd; ++Arg) {
2044 if (VisitTemplateArgumentLoc(*Arg))
2045 return true;
2046 }
2047 }
2048 continue;
2049 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002050 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002051 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002052 // Visit nested-name-specifier, if present.
2053 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2054 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2055 return true;
2056 // Visit declaration name.
2057 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2058 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002059 continue;
2060 }
Ted Kremenek60458782010-11-12 21:34:16 +00002061 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002062 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002063 // Visit the nested-name-specifier.
2064 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2065 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2066 return true;
2067 // Visit the declaration name.
2068 if (VisitDeclarationNameInfo(O->getNameInfo()))
2069 return true;
2070 // Visit the overloaded declaration reference.
2071 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2072 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002073 continue;
2074 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002075 }
2076 }
2077 return false;
2078}
2079
2080bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002081 VisitorWorkList *WL = 0;
2082 if (!WorkListFreeList.empty()) {
2083 WL = WorkListFreeList.back();
2084 WL->clear();
2085 WorkListFreeList.pop_back();
2086 }
2087 else {
2088 WL = new VisitorWorkList();
2089 WorkListCache.push_back(WL);
2090 }
2091 EnqueueWorkList(*WL, S);
2092 bool result = RunVisitorWorkList(*WL);
2093 WorkListFreeList.push_back(WL);
2094 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002095}
2096
2097//===----------------------------------------------------------------------===//
2098// Misc. API hooks.
2099//===----------------------------------------------------------------------===//
2100
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002101static llvm::sys::Mutex EnableMultithreadingMutex;
2102static bool EnabledMultithreading;
2103
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002104extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002105CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2106 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002107 // Disable pretty stack trace functionality, which will otherwise be a very
2108 // poor citizen of the world and set up all sorts of signal handlers.
2109 llvm::DisablePrettyStackTrace = true;
2110
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002111 // We use crash recovery to make some of our APIs more reliable, implicitly
2112 // enable it.
2113 llvm::CrashRecoveryContext::Enable();
2114
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002115 // Enable support for multithreading in LLVM.
2116 {
2117 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2118 if (!EnabledMultithreading) {
2119 llvm::llvm_start_multithreaded();
2120 EnabledMultithreading = true;
2121 }
2122 }
2123
Douglas Gregora030b7c2010-01-22 20:35:53 +00002124 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002125 if (excludeDeclarationsFromPCH)
2126 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002127 if (displayDiagnostics)
2128 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002129 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002130}
2131
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002132void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002133 if (CIdx)
2134 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002135}
2136
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002137CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002138 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002139 if (!CIdx)
2140 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002141
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002142 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002143 FileSystemOptions FileSystemOpts;
2144 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002145
Douglas Gregor28019772010-04-05 23:52:57 +00002146 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002147 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002148 CXXIdx->getOnlyLocalDecls(),
2149 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002150 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002151}
2152
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002153unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002154 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002155 CXTranslationUnit_CacheCompletionResults |
2156 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002157}
2158
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002159CXTranslationUnit
2160clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2161 const char *source_filename,
2162 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002163 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002164 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002165 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002166 return clang_parseTranslationUnit(CIdx, source_filename,
2167 command_line_args, num_command_line_args,
2168 unsaved_files, num_unsaved_files,
2169 CXTranslationUnit_DetailedPreprocessingRecord);
2170}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002171
2172struct ParseTranslationUnitInfo {
2173 CXIndex CIdx;
2174 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002175 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002176 int num_command_line_args;
2177 struct CXUnsavedFile *unsaved_files;
2178 unsigned num_unsaved_files;
2179 unsigned options;
2180 CXTranslationUnit result;
2181};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002182static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002183 ParseTranslationUnitInfo *PTUI =
2184 static_cast<ParseTranslationUnitInfo*>(UserData);
2185 CXIndex CIdx = PTUI->CIdx;
2186 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002187 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002188 int num_command_line_args = PTUI->num_command_line_args;
2189 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2190 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2191 unsigned options = PTUI->options;
2192 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002193
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002194 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002195 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002196
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002197 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2198
Douglas Gregor44c181a2010-07-23 00:33:23 +00002199 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002200 bool CompleteTranslationUnit
2201 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002202 bool CacheCodeCompetionResults
2203 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002204 bool CXXPrecompilePreamble
2205 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2206 bool CXXChainedPCH
2207 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002208
Douglas Gregor5352ac02010-01-28 00:27:43 +00002209 // Configure the diagnostics.
2210 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002211 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2212 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002213
Douglas Gregor4db64a42010-01-23 00:14:00 +00002214 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2215 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002216 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002217 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002218 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002219 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2220 Buffer));
2221 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002222
Douglas Gregorb10daed2010-10-11 16:52:23 +00002223 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002224
Ted Kremenek139ba862009-10-22 00:03:57 +00002225 // The 'source_filename' argument is optional. If the caller does not
2226 // specify it then it is assumed that the source file is specified
2227 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002228 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002229 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002230
2231 // Since the Clang C library is primarily used by batch tools dealing with
2232 // (often very broken) source code, where spell-checking can have a
2233 // significant negative impact on performance (particularly when
2234 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002235 // Only do this if we haven't found a spell-checking-related argument.
2236 bool FoundSpellCheckingArgument = false;
2237 for (int I = 0; I != num_command_line_args; ++I) {
2238 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2239 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2240 FoundSpellCheckingArgument = true;
2241 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002242 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002243 }
2244 if (!FoundSpellCheckingArgument)
2245 Args.push_back("-fno-spell-checking");
2246
2247 Args.insert(Args.end(), command_line_args,
2248 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002249
Douglas Gregor44c181a2010-07-23 00:33:23 +00002250 // Do we need the detailed preprocessing record?
2251 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002252 Args.push_back("-Xclang");
2253 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002254 }
2255
Douglas Gregorb10daed2010-10-11 16:52:23 +00002256 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002257 llvm::OwningPtr<ASTUnit> Unit(
2258 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2259 Diags,
2260 CXXIdx->getClangResourcesPath(),
2261 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002262 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002263 RemappedFiles.data(),
2264 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002265 PrecompilePreamble,
2266 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002267 CacheCodeCompetionResults,
2268 CXXPrecompilePreamble,
2269 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002270
Douglas Gregorb10daed2010-10-11 16:52:23 +00002271 if (NumErrors != Diags->getNumErrors()) {
2272 // Make sure to check that 'Unit' is non-NULL.
2273 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2274 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2275 DEnd = Unit->stored_diag_end();
2276 D != DEnd; ++D) {
2277 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2278 CXString Msg = clang_formatDiagnostic(&Diag,
2279 clang_defaultDiagnosticDisplayOptions());
2280 fprintf(stderr, "%s\n", clang_getCString(Msg));
2281 clang_disposeString(Msg);
2282 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002283#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002284 // On Windows, force a flush, since there may be multiple copies of
2285 // stderr and stdout in the file system, all with different buffers
2286 // but writing to the same device.
2287 fflush(stderr);
2288#endif
2289 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002290 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002291
Ted Kremeneka60ed472010-11-16 08:15:36 +00002292 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002293}
2294CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2295 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002296 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002297 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002298 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002299 unsigned num_unsaved_files,
2300 unsigned options) {
2301 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002302 num_command_line_args, unsaved_files,
2303 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002304 llvm::CrashRecoveryContext CRC;
2305
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002306 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002307 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2308 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2309 fprintf(stderr, " 'command_line_args' : [");
2310 for (int i = 0; i != num_command_line_args; ++i) {
2311 if (i)
2312 fprintf(stderr, ", ");
2313 fprintf(stderr, "'%s'", command_line_args[i]);
2314 }
2315 fprintf(stderr, "],\n");
2316 fprintf(stderr, " 'unsaved_files' : [");
2317 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2318 if (i)
2319 fprintf(stderr, ", ");
2320 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2321 unsaved_files[i].Length);
2322 }
2323 fprintf(stderr, "],\n");
2324 fprintf(stderr, " 'options' : %d,\n", options);
2325 fprintf(stderr, "}\n");
2326
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002327 return 0;
2328 }
2329
2330 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002331}
2332
Douglas Gregor19998442010-08-13 15:35:05 +00002333unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2334 return CXSaveTranslationUnit_None;
2335}
2336
2337int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2338 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002339 if (!TU)
2340 return 1;
2341
Ted Kremeneka60ed472010-11-16 08:15:36 +00002342 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002343}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002344
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002345void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002346 if (CTUnit) {
2347 // If the translation unit has been marked as unsafe to free, just discard
2348 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002349 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002350 return;
2351
Ted Kremeneka60ed472010-11-16 08:15:36 +00002352 delete static_cast<ASTUnit *>(CTUnit->TUData);
2353 disposeCXStringPool(CTUnit->StringPool);
2354 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002355 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002356}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002357
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002358unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2359 return CXReparse_None;
2360}
2361
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002362struct ReparseTranslationUnitInfo {
2363 CXTranslationUnit TU;
2364 unsigned num_unsaved_files;
2365 struct CXUnsavedFile *unsaved_files;
2366 unsigned options;
2367 int result;
2368};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002369
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002370static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002371 ReparseTranslationUnitInfo *RTUI =
2372 static_cast<ReparseTranslationUnitInfo*>(UserData);
2373 CXTranslationUnit TU = RTUI->TU;
2374 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2375 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2376 unsigned options = RTUI->options;
2377 (void) options;
2378 RTUI->result = 1;
2379
Douglas Gregorabc563f2010-07-19 21:46:24 +00002380 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002381 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002382
Ted Kremeneka60ed472010-11-16 08:15:36 +00002383 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002384 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002385
2386 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2387 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2388 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2389 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002390 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002391 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2392 Buffer));
2393 }
2394
Douglas Gregor593b0c12010-09-23 18:47:53 +00002395 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2396 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002397}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002398
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002399int clang_reparseTranslationUnit(CXTranslationUnit TU,
2400 unsigned num_unsaved_files,
2401 struct CXUnsavedFile *unsaved_files,
2402 unsigned options) {
2403 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2404 options, 0 };
2405 llvm::CrashRecoveryContext CRC;
2406
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002407 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002408 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002409 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002410 return 1;
2411 }
2412
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002413
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002414 return RTUI.result;
2415}
2416
Douglas Gregordf95a132010-08-09 20:45:32 +00002417
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002418CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002419 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002420 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002421
Ted Kremeneka60ed472010-11-16 08:15:36 +00002422 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002423 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002424}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002425
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002426CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002427 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002428 return Result;
2429}
2430
Ted Kremenekfb480492010-01-13 21:46:36 +00002431} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002432
Ted Kremenekfb480492010-01-13 21:46:36 +00002433//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002434// CXSourceLocation and CXSourceRange Operations.
2435//===----------------------------------------------------------------------===//
2436
Douglas Gregorb9790342010-01-22 21:44:22 +00002437extern "C" {
2438CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002439 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002440 return Result;
2441}
2442
2443unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002444 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2445 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2446 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002447}
2448
2449CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2450 CXFile file,
2451 unsigned line,
2452 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002453 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002454 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002455
Ted Kremeneka60ed472010-11-16 08:15:36 +00002456 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002457 SourceLocation SLoc
2458 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002459 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002460 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002461 if (SLoc.isInvalid()) return clang_getNullLocation();
2462
2463 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2464}
2465
2466CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2467 CXFile file,
2468 unsigned offset) {
2469 if (!tu || !file)
2470 return clang_getNullLocation();
2471
Ted Kremeneka60ed472010-11-16 08:15:36 +00002472 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002473 SourceLocation Start
2474 = CXXUnit->getSourceManager().getLocation(
2475 static_cast<const FileEntry *>(file),
2476 1, 1);
2477 if (Start.isInvalid()) return clang_getNullLocation();
2478
2479 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2480
2481 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002482
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002483 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002484}
2485
Douglas Gregor5352ac02010-01-28 00:27:43 +00002486CXSourceRange clang_getNullRange() {
2487 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2488 return Result;
2489}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002490
Douglas Gregor5352ac02010-01-28 00:27:43 +00002491CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2492 if (begin.ptr_data[0] != end.ptr_data[0] ||
2493 begin.ptr_data[1] != end.ptr_data[1])
2494 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002495
2496 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002497 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002498 return Result;
2499}
2500
Douglas Gregor46766dc2010-01-26 19:19:08 +00002501void clang_getInstantiationLocation(CXSourceLocation location,
2502 CXFile *file,
2503 unsigned *line,
2504 unsigned *column,
2505 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002506 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2507
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002508 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002509 if (file)
2510 *file = 0;
2511 if (line)
2512 *line = 0;
2513 if (column)
2514 *column = 0;
2515 if (offset)
2516 *offset = 0;
2517 return;
2518 }
2519
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002520 const SourceManager &SM =
2521 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002522 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002523
2524 if (file)
2525 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2526 if (line)
2527 *line = SM.getInstantiationLineNumber(InstLoc);
2528 if (column)
2529 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002530 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002531 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002532}
2533
Douglas Gregora9b06d42010-11-09 06:24:54 +00002534void clang_getSpellingLocation(CXSourceLocation location,
2535 CXFile *file,
2536 unsigned *line,
2537 unsigned *column,
2538 unsigned *offset) {
2539 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2540
2541 if (!location.ptr_data[0] || Loc.isInvalid()) {
2542 if (file)
2543 *file = 0;
2544 if (line)
2545 *line = 0;
2546 if (column)
2547 *column = 0;
2548 if (offset)
2549 *offset = 0;
2550 return;
2551 }
2552
2553 const SourceManager &SM =
2554 *static_cast<const SourceManager*>(location.ptr_data[0]);
2555 SourceLocation SpellLoc = Loc;
2556 if (SpellLoc.isMacroID()) {
2557 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2558 if (SimpleSpellingLoc.isFileID() &&
2559 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2560 SpellLoc = SimpleSpellingLoc;
2561 else
2562 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2563 }
2564
2565 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2566 FileID FID = LocInfo.first;
2567 unsigned FileOffset = LocInfo.second;
2568
2569 if (file)
2570 *file = (void *)SM.getFileEntryForID(FID);
2571 if (line)
2572 *line = SM.getLineNumber(FID, FileOffset);
2573 if (column)
2574 *column = SM.getColumnNumber(FID, FileOffset);
2575 if (offset)
2576 *offset = FileOffset;
2577}
2578
Douglas Gregor1db19de2010-01-19 21:36:55 +00002579CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002580 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002581 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002582 return Result;
2583}
2584
2585CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002586 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002587 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002588 return Result;
2589}
2590
Douglas Gregorb9790342010-01-22 21:44:22 +00002591} // end: extern "C"
2592
Douglas Gregor1db19de2010-01-19 21:36:55 +00002593//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002594// CXFile Operations.
2595//===----------------------------------------------------------------------===//
2596
2597extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002598CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002599 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002600 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002601
Steve Naroff88145032009-10-27 14:35:18 +00002602 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002603 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002604}
2605
2606time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002607 if (!SFile)
2608 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002609
Steve Naroff88145032009-10-27 14:35:18 +00002610 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2611 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002612}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002613
Douglas Gregorb9790342010-01-22 21:44:22 +00002614CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2615 if (!tu)
2616 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002617
Ted Kremeneka60ed472010-11-16 08:15:36 +00002618 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002619
Douglas Gregorb9790342010-01-22 21:44:22 +00002620 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002621 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2622 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002623 return const_cast<FileEntry *>(File);
2624}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002625
Ted Kremenekfb480492010-01-13 21:46:36 +00002626} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002627
Ted Kremenekfb480492010-01-13 21:46:36 +00002628//===----------------------------------------------------------------------===//
2629// CXCursor Operations.
2630//===----------------------------------------------------------------------===//
2631
Ted Kremenekfb480492010-01-13 21:46:36 +00002632static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002633 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2634 return getDeclFromExpr(CE->getSubExpr());
2635
Ted Kremenekfb480492010-01-13 21:46:36 +00002636 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2637 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002638 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2639 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002640 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2641 return ME->getMemberDecl();
2642 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2643 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002644 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2645 return PRE->getProperty();
2646
Ted Kremenekfb480492010-01-13 21:46:36 +00002647 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2648 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002649 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2650 if (!CE->isElidable())
2651 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002652 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2653 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002654
Douglas Gregordb1314e2010-10-01 21:11:22 +00002655 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2656 return PE->getProtocol();
2657
Ted Kremenekfb480492010-01-13 21:46:36 +00002658 return 0;
2659}
2660
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002661static SourceLocation getLocationFromExpr(Expr *E) {
2662 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2663 return /*FIXME:*/Msg->getLeftLoc();
2664 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2665 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002666 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2667 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002668 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2669 return Member->getMemberLoc();
2670 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2671 return Ivar->getLocation();
2672 return E->getLocStart();
2673}
2674
Ted Kremenekfb480492010-01-13 21:46:36 +00002675extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002676
2677unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002678 CXCursorVisitor visitor,
2679 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002680 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2681 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002682 return CursorVis.VisitChildren(parent);
2683}
2684
David Chisnall3387c652010-11-03 14:12:26 +00002685#ifndef __has_feature
2686#define __has_feature(x) 0
2687#endif
2688#if __has_feature(blocks)
2689typedef enum CXChildVisitResult
2690 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2691
2692static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2693 CXClientData client_data) {
2694 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2695 return block(cursor, parent);
2696}
2697#else
2698// If we are compiled with a compiler that doesn't have native blocks support,
2699// define and call the block manually, so the
2700typedef struct _CXChildVisitResult
2701{
2702 void *isa;
2703 int flags;
2704 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002705 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2706 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002707} *CXCursorVisitorBlock;
2708
2709static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2710 CXClientData client_data) {
2711 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2712 return block->invoke(block, cursor, parent);
2713}
2714#endif
2715
2716
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002717unsigned clang_visitChildrenWithBlock(CXCursor parent,
2718 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002719 return clang_visitChildren(parent, visitWithBlock, block);
2720}
2721
Douglas Gregor78205d42010-01-20 21:45:58 +00002722static CXString getDeclSpelling(Decl *D) {
2723 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002724 if (!ND) {
2725 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2726 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2727 return createCXString(Property->getIdentifier()->getName());
2728
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002729 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002730 }
2731
Douglas Gregor78205d42010-01-20 21:45:58 +00002732 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002733 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002734
Douglas Gregor78205d42010-01-20 21:45:58 +00002735 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2736 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2737 // and returns different names. NamedDecl returns the class name and
2738 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002739 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002740
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002741 if (isa<UsingDirectiveDecl>(D))
2742 return createCXString("");
2743
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002744 llvm::SmallString<1024> S;
2745 llvm::raw_svector_ostream os(S);
2746 ND->printName(os);
2747
2748 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002749}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002750
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002751CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002752 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002753 return clang_getTranslationUnitSpelling(
2754 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002755
Steve Narofff334b4e2009-09-02 18:26:48 +00002756 if (clang_isReference(C.kind)) {
2757 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002758 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002759 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002760 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002761 }
2762 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002763 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002764 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002765 }
2766 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002767 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002768 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002769 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002770 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002771 case CXCursor_CXXBaseSpecifier: {
2772 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2773 return createCXString(B->getType().getAsString());
2774 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002775 case CXCursor_TypeRef: {
2776 TypeDecl *Type = getCursorTypeRef(C).first;
2777 assert(Type && "Missing type decl");
2778
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002779 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2780 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002781 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002782 case CXCursor_TemplateRef: {
2783 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002784 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002785
2786 return createCXString(Template->getNameAsString());
2787 }
Douglas Gregor69319002010-08-31 23:48:11 +00002788
2789 case CXCursor_NamespaceRef: {
2790 NamedDecl *NS = getCursorNamespaceRef(C).first;
2791 assert(NS && "Missing namespace decl");
2792
2793 return createCXString(NS->getNameAsString());
2794 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002795
Douglas Gregora67e03f2010-09-09 21:42:20 +00002796 case CXCursor_MemberRef: {
2797 FieldDecl *Field = getCursorMemberRef(C).first;
2798 assert(Field && "Missing member decl");
2799
2800 return createCXString(Field->getNameAsString());
2801 }
2802
Douglas Gregor36897b02010-09-10 00:22:18 +00002803 case CXCursor_LabelRef: {
2804 LabelStmt *Label = getCursorLabelRef(C).first;
2805 assert(Label && "Missing label");
2806
2807 return createCXString(Label->getID()->getName());
2808 }
2809
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002810 case CXCursor_OverloadedDeclRef: {
2811 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2812 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2813 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2814 return createCXString(ND->getNameAsString());
2815 return createCXString("");
2816 }
2817 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2818 return createCXString(E->getName().getAsString());
2819 OverloadedTemplateStorage *Ovl
2820 = Storage.get<OverloadedTemplateStorage*>();
2821 if (Ovl->size() == 0)
2822 return createCXString("");
2823 return createCXString((*Ovl->begin())->getNameAsString());
2824 }
2825
Daniel Dunbaracca7252009-11-30 20:42:49 +00002826 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002827 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002828 }
2829 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002830
2831 if (clang_isExpression(C.kind)) {
2832 Decl *D = getDeclFromExpr(getCursorExpr(C));
2833 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002834 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002835 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002836 }
2837
Douglas Gregor36897b02010-09-10 00:22:18 +00002838 if (clang_isStatement(C.kind)) {
2839 Stmt *S = getCursorStmt(C);
2840 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2841 return createCXString(Label->getID()->getName());
2842
2843 return createCXString("");
2844 }
2845
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002846 if (C.kind == CXCursor_MacroInstantiation)
2847 return createCXString(getCursorMacroInstantiation(C)->getName()
2848 ->getNameStart());
2849
Douglas Gregor572feb22010-03-18 18:04:21 +00002850 if (C.kind == CXCursor_MacroDefinition)
2851 return createCXString(getCursorMacroDefinition(C)->getName()
2852 ->getNameStart());
2853
Douglas Gregorecdcb882010-10-20 22:00:55 +00002854 if (C.kind == CXCursor_InclusionDirective)
2855 return createCXString(getCursorInclusionDirective(C)->getFileName());
2856
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002857 if (clang_isDeclaration(C.kind))
2858 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002859
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002860 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002861}
2862
Douglas Gregor358559d2010-10-02 22:49:11 +00002863CXString clang_getCursorDisplayName(CXCursor C) {
2864 if (!clang_isDeclaration(C.kind))
2865 return clang_getCursorSpelling(C);
2866
2867 Decl *D = getCursorDecl(C);
2868 if (!D)
2869 return createCXString("");
2870
2871 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2872 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2873 D = FunTmpl->getTemplatedDecl();
2874
2875 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2876 llvm::SmallString<64> Str;
2877 llvm::raw_svector_ostream OS(Str);
2878 OS << Function->getNameAsString();
2879 if (Function->getPrimaryTemplate())
2880 OS << "<>";
2881 OS << "(";
2882 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2883 if (I)
2884 OS << ", ";
2885 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2886 }
2887
2888 if (Function->isVariadic()) {
2889 if (Function->getNumParams())
2890 OS << ", ";
2891 OS << "...";
2892 }
2893 OS << ")";
2894 return createCXString(OS.str());
2895 }
2896
2897 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2898 llvm::SmallString<64> Str;
2899 llvm::raw_svector_ostream OS(Str);
2900 OS << ClassTemplate->getNameAsString();
2901 OS << "<";
2902 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2903 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2904 if (I)
2905 OS << ", ";
2906
2907 NamedDecl *Param = Params->getParam(I);
2908 if (Param->getIdentifier()) {
2909 OS << Param->getIdentifier()->getName();
2910 continue;
2911 }
2912
2913 // There is no parameter name, which makes this tricky. Try to come up
2914 // with something useful that isn't too long.
2915 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2916 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2917 else if (NonTypeTemplateParmDecl *NTTP
2918 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2919 OS << NTTP->getType().getAsString(Policy);
2920 else
2921 OS << "template<...> class";
2922 }
2923
2924 OS << ">";
2925 return createCXString(OS.str());
2926 }
2927
2928 if (ClassTemplateSpecializationDecl *ClassSpec
2929 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2930 // If the type was explicitly written, use that.
2931 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2932 return createCXString(TSInfo->getType().getAsString(Policy));
2933
2934 llvm::SmallString<64> Str;
2935 llvm::raw_svector_ostream OS(Str);
2936 OS << ClassSpec->getNameAsString();
2937 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002938 ClassSpec->getTemplateArgs().data(),
2939 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002940 Policy);
2941 return createCXString(OS.str());
2942 }
2943
2944 return clang_getCursorSpelling(C);
2945}
2946
Ted Kremeneke68fff62010-02-17 00:41:32 +00002947CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002948 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002949 case CXCursor_FunctionDecl:
2950 return createCXString("FunctionDecl");
2951 case CXCursor_TypedefDecl:
2952 return createCXString("TypedefDecl");
2953 case CXCursor_EnumDecl:
2954 return createCXString("EnumDecl");
2955 case CXCursor_EnumConstantDecl:
2956 return createCXString("EnumConstantDecl");
2957 case CXCursor_StructDecl:
2958 return createCXString("StructDecl");
2959 case CXCursor_UnionDecl:
2960 return createCXString("UnionDecl");
2961 case CXCursor_ClassDecl:
2962 return createCXString("ClassDecl");
2963 case CXCursor_FieldDecl:
2964 return createCXString("FieldDecl");
2965 case CXCursor_VarDecl:
2966 return createCXString("VarDecl");
2967 case CXCursor_ParmDecl:
2968 return createCXString("ParmDecl");
2969 case CXCursor_ObjCInterfaceDecl:
2970 return createCXString("ObjCInterfaceDecl");
2971 case CXCursor_ObjCCategoryDecl:
2972 return createCXString("ObjCCategoryDecl");
2973 case CXCursor_ObjCProtocolDecl:
2974 return createCXString("ObjCProtocolDecl");
2975 case CXCursor_ObjCPropertyDecl:
2976 return createCXString("ObjCPropertyDecl");
2977 case CXCursor_ObjCIvarDecl:
2978 return createCXString("ObjCIvarDecl");
2979 case CXCursor_ObjCInstanceMethodDecl:
2980 return createCXString("ObjCInstanceMethodDecl");
2981 case CXCursor_ObjCClassMethodDecl:
2982 return createCXString("ObjCClassMethodDecl");
2983 case CXCursor_ObjCImplementationDecl:
2984 return createCXString("ObjCImplementationDecl");
2985 case CXCursor_ObjCCategoryImplDecl:
2986 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002987 case CXCursor_CXXMethod:
2988 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002989 case CXCursor_UnexposedDecl:
2990 return createCXString("UnexposedDecl");
2991 case CXCursor_ObjCSuperClassRef:
2992 return createCXString("ObjCSuperClassRef");
2993 case CXCursor_ObjCProtocolRef:
2994 return createCXString("ObjCProtocolRef");
2995 case CXCursor_ObjCClassRef:
2996 return createCXString("ObjCClassRef");
2997 case CXCursor_TypeRef:
2998 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002999 case CXCursor_TemplateRef:
3000 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003001 case CXCursor_NamespaceRef:
3002 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003003 case CXCursor_MemberRef:
3004 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003005 case CXCursor_LabelRef:
3006 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003007 case CXCursor_OverloadedDeclRef:
3008 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003009 case CXCursor_UnexposedExpr:
3010 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003011 case CXCursor_BlockExpr:
3012 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003013 case CXCursor_DeclRefExpr:
3014 return createCXString("DeclRefExpr");
3015 case CXCursor_MemberRefExpr:
3016 return createCXString("MemberRefExpr");
3017 case CXCursor_CallExpr:
3018 return createCXString("CallExpr");
3019 case CXCursor_ObjCMessageExpr:
3020 return createCXString("ObjCMessageExpr");
3021 case CXCursor_UnexposedStmt:
3022 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003023 case CXCursor_LabelStmt:
3024 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003025 case CXCursor_InvalidFile:
3026 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003027 case CXCursor_InvalidCode:
3028 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003029 case CXCursor_NoDeclFound:
3030 return createCXString("NoDeclFound");
3031 case CXCursor_NotImplemented:
3032 return createCXString("NotImplemented");
3033 case CXCursor_TranslationUnit:
3034 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003035 case CXCursor_UnexposedAttr:
3036 return createCXString("UnexposedAttr");
3037 case CXCursor_IBActionAttr:
3038 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003039 case CXCursor_IBOutletAttr:
3040 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003041 case CXCursor_IBOutletCollectionAttr:
3042 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003043 case CXCursor_PreprocessingDirective:
3044 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003045 case CXCursor_MacroDefinition:
3046 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003047 case CXCursor_MacroInstantiation:
3048 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003049 case CXCursor_InclusionDirective:
3050 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003051 case CXCursor_Namespace:
3052 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003053 case CXCursor_LinkageSpec:
3054 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003055 case CXCursor_CXXBaseSpecifier:
3056 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003057 case CXCursor_Constructor:
3058 return createCXString("CXXConstructor");
3059 case CXCursor_Destructor:
3060 return createCXString("CXXDestructor");
3061 case CXCursor_ConversionFunction:
3062 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003063 case CXCursor_TemplateTypeParameter:
3064 return createCXString("TemplateTypeParameter");
3065 case CXCursor_NonTypeTemplateParameter:
3066 return createCXString("NonTypeTemplateParameter");
3067 case CXCursor_TemplateTemplateParameter:
3068 return createCXString("TemplateTemplateParameter");
3069 case CXCursor_FunctionTemplate:
3070 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003071 case CXCursor_ClassTemplate:
3072 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003073 case CXCursor_ClassTemplatePartialSpecialization:
3074 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003075 case CXCursor_NamespaceAlias:
3076 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003077 case CXCursor_UsingDirective:
3078 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003079 case CXCursor_UsingDeclaration:
3080 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003081 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003082
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003083 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003084 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003085}
Steve Naroff89922f82009-08-31 00:59:03 +00003086
Ted Kremeneke68fff62010-02-17 00:41:32 +00003087enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3088 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003089 CXClientData client_data) {
3090 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003091
3092 // If our current best cursor is the construction of a temporary object,
3093 // don't replace that cursor with a type reference, because we want
3094 // clang_getCursor() to point at the constructor.
3095 if (clang_isExpression(BestCursor->kind) &&
3096 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3097 cursor.kind == CXCursor_TypeRef)
3098 return CXChildVisit_Recurse;
3099
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003100 *BestCursor = cursor;
3101 return CXChildVisit_Recurse;
3102}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003103
Douglas Gregorb9790342010-01-22 21:44:22 +00003104CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3105 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003106 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003107
Ted Kremeneka60ed472010-11-16 08:15:36 +00003108 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003109 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3110
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003111 // Translate the given source location to make it point at the beginning of
3112 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003113 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003114
3115 // Guard against an invalid SourceLocation, or we may assert in one
3116 // of the following calls.
3117 if (SLoc.isInvalid())
3118 return clang_getNullCursor();
3119
Douglas Gregor40749ee2010-11-03 00:35:38 +00003120 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003121 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3122 CXXUnit->getASTContext().getLangOptions());
3123
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003124 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3125 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003126 // FIXME: Would be great to have a "hint" cursor, then walk from that
3127 // hint cursor upward until we find a cursor whose source range encloses
3128 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003129 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3130 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003131 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003132 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003133 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003134
3135 if (Logging) {
3136 CXFile SearchFile;
3137 unsigned SearchLine, SearchColumn;
3138 CXFile ResultFile;
3139 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003140 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3141 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003142 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3143
3144 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3145 0);
3146 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3147 &ResultColumn, 0);
3148 SearchFileName = clang_getFileName(SearchFile);
3149 ResultFileName = clang_getFileName(ResultFile);
3150 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003151 USR = clang_getCursorUSR(Result);
3152 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003153 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3154 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003155 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3156 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003157 clang_disposeString(SearchFileName);
3158 clang_disposeString(ResultFileName);
3159 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003160 clang_disposeString(USR);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003161 }
3162
Ted Kremeneke68fff62010-02-17 00:41:32 +00003163 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003164}
3165
Ted Kremenek73885552009-11-17 19:28:59 +00003166CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003167 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003168}
3169
3170unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003171 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003172}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003173
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003174unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003175 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3176}
3177
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003178unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003179 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3180}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003181
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003182unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003183 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3184}
3185
Douglas Gregor97b98722010-01-19 23:20:36 +00003186unsigned clang_isExpression(enum CXCursorKind K) {
3187 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3188}
3189
3190unsigned clang_isStatement(enum CXCursorKind K) {
3191 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3192}
3193
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003194unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3195 return K == CXCursor_TranslationUnit;
3196}
3197
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003198unsigned clang_isPreprocessing(enum CXCursorKind K) {
3199 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3200}
3201
Ted Kremenekad6eff62010-03-08 21:17:29 +00003202unsigned clang_isUnexposed(enum CXCursorKind K) {
3203 switch (K) {
3204 case CXCursor_UnexposedDecl:
3205 case CXCursor_UnexposedExpr:
3206 case CXCursor_UnexposedStmt:
3207 case CXCursor_UnexposedAttr:
3208 return true;
3209 default:
3210 return false;
3211 }
3212}
3213
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003214CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003215 return C.kind;
3216}
3217
Douglas Gregor98258af2010-01-18 22:46:11 +00003218CXSourceLocation clang_getCursorLocation(CXCursor C) {
3219 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003220 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003221 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003222 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3223 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003224 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003225 }
3226
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003227 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003228 std::pair<ObjCProtocolDecl *, SourceLocation> P
3229 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003230 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003231 }
3232
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003233 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003234 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3235 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003236 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003237 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003238
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003239 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003240 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003241 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003242 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003243
3244 case CXCursor_TemplateRef: {
3245 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3246 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3247 }
3248
Douglas Gregor69319002010-08-31 23:48:11 +00003249 case CXCursor_NamespaceRef: {
3250 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3251 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3252 }
3253
Douglas Gregora67e03f2010-09-09 21:42:20 +00003254 case CXCursor_MemberRef: {
3255 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3256 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3257 }
3258
Ted Kremenek3064ef92010-08-27 21:34:58 +00003259 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003260 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3261 if (!BaseSpec)
3262 return clang_getNullLocation();
3263
3264 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3265 return cxloc::translateSourceLocation(getCursorContext(C),
3266 TSInfo->getTypeLoc().getBeginLoc());
3267
3268 return cxloc::translateSourceLocation(getCursorContext(C),
3269 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003270 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003271
Douglas Gregor36897b02010-09-10 00:22:18 +00003272 case CXCursor_LabelRef: {
3273 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3274 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3275 }
3276
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003277 case CXCursor_OverloadedDeclRef:
3278 return cxloc::translateSourceLocation(getCursorContext(C),
3279 getCursorOverloadedDeclRef(C).second);
3280
Douglas Gregorf46034a2010-01-18 23:41:10 +00003281 default:
3282 // FIXME: Need a way to enumerate all non-reference cases.
3283 llvm_unreachable("Missed a reference kind");
3284 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003285 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003286
3287 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003288 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003289 getLocationFromExpr(getCursorExpr(C)));
3290
Douglas Gregor36897b02010-09-10 00:22:18 +00003291 if (clang_isStatement(C.kind))
3292 return cxloc::translateSourceLocation(getCursorContext(C),
3293 getCursorStmt(C)->getLocStart());
3294
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003295 if (C.kind == CXCursor_PreprocessingDirective) {
3296 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3297 return cxloc::translateSourceLocation(getCursorContext(C), L);
3298 }
Douglas Gregor48072312010-03-18 15:23:44 +00003299
3300 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003301 SourceLocation L
3302 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003303 return cxloc::translateSourceLocation(getCursorContext(C), L);
3304 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003305
3306 if (C.kind == CXCursor_MacroDefinition) {
3307 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3308 return cxloc::translateSourceLocation(getCursorContext(C), L);
3309 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003310
3311 if (C.kind == CXCursor_InclusionDirective) {
3312 SourceLocation L
3313 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3314 return cxloc::translateSourceLocation(getCursorContext(C), L);
3315 }
3316
Ted Kremenek9a700d22010-05-12 06:16:13 +00003317 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003318 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003319
Douglas Gregorf46034a2010-01-18 23:41:10 +00003320 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003321 SourceLocation Loc = D->getLocation();
3322 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3323 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003324 // FIXME: Multiple variables declared in a single declaration
3325 // currently lack the information needed to correctly determine their
3326 // ranges when accounting for the type-specifier. We use context
3327 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3328 // and if so, whether it is the first decl.
3329 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3330 if (!cxcursor::isFirstInDeclGroup(C))
3331 Loc = VD->getLocation();
3332 }
3333
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003334 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003335}
Douglas Gregora7bde202010-01-19 00:34:46 +00003336
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003337} // end extern "C"
3338
3339static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003340 if (clang_isReference(C.kind)) {
3341 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003342 case CXCursor_ObjCSuperClassRef:
3343 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003344
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003345 case CXCursor_ObjCProtocolRef:
3346 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003347
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003348 case CXCursor_ObjCClassRef:
3349 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003350
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003351 case CXCursor_TypeRef:
3352 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003353
3354 case CXCursor_TemplateRef:
3355 return getCursorTemplateRef(C).second;
3356
Douglas Gregor69319002010-08-31 23:48:11 +00003357 case CXCursor_NamespaceRef:
3358 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003359
3360 case CXCursor_MemberRef:
3361 return getCursorMemberRef(C).second;
3362
Ted Kremenek3064ef92010-08-27 21:34:58 +00003363 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003364 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003365
Douglas Gregor36897b02010-09-10 00:22:18 +00003366 case CXCursor_LabelRef:
3367 return getCursorLabelRef(C).second;
3368
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003369 case CXCursor_OverloadedDeclRef:
3370 return getCursorOverloadedDeclRef(C).second;
3371
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003372 default:
3373 // FIXME: Need a way to enumerate all non-reference cases.
3374 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003375 }
3376 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003377
3378 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003379 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003380
3381 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003382 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003383
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003384 if (C.kind == CXCursor_PreprocessingDirective)
3385 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003386
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003387 if (C.kind == CXCursor_MacroInstantiation)
3388 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003389
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003390 if (C.kind == CXCursor_MacroDefinition)
3391 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003392
3393 if (C.kind == CXCursor_InclusionDirective)
3394 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3395
Ted Kremenek007a7c92010-11-01 23:26:51 +00003396 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3397 Decl *D = cxcursor::getCursorDecl(C);
3398 SourceRange R = D->getSourceRange();
3399 // FIXME: Multiple variables declared in a single declaration
3400 // currently lack the information needed to correctly determine their
3401 // ranges when accounting for the type-specifier. We use context
3402 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3403 // and if so, whether it is the first decl.
3404 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3405 if (!cxcursor::isFirstInDeclGroup(C))
3406 R.setBegin(VD->getLocation());
3407 }
3408 return R;
3409 }
Douglas Gregor66537982010-11-17 17:14:07 +00003410 return SourceRange();
3411}
3412
3413/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3414/// the decl-specifier-seq for declarations.
3415static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3416 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3417 Decl *D = cxcursor::getCursorDecl(C);
3418 SourceRange R = D->getSourceRange();
3419
3420 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3421 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3422 TypeLoc TL = TI->getTypeLoc();
3423 SourceLocation TLoc = TL.getSourceRange().getBegin();
3424 if (TLoc.isValid() && R.getBegin().isValid() &&
3425 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3426 R.setBegin(TLoc);
3427 }
3428
3429 // FIXME: Multiple variables declared in a single declaration
3430 // currently lack the information needed to correctly determine their
3431 // ranges when accounting for the type-specifier. We use context
3432 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3433 // and if so, whether it is the first decl.
3434 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3435 if (!cxcursor::isFirstInDeclGroup(C))
3436 R.setBegin(VD->getLocation());
3437 }
3438 }
3439
3440 return R;
3441 }
3442
3443 return getRawCursorExtent(C);
3444}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003445
3446extern "C" {
3447
3448CXSourceRange clang_getCursorExtent(CXCursor C) {
3449 SourceRange R = getRawCursorExtent(C);
3450 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003451 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003452
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003453 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003454}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003455
3456CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003457 if (clang_isInvalid(C.kind))
3458 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003459
Ted Kremeneka60ed472010-11-16 08:15:36 +00003460 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003461 if (clang_isDeclaration(C.kind)) {
3462 Decl *D = getCursorDecl(C);
3463 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003464 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003465 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003466 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003467 if (ObjCForwardProtocolDecl *Protocols
3468 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003469 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003470 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3471 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3472 return MakeCXCursor(Property, tu);
3473
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003474 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003475 }
3476
Douglas Gregor97b98722010-01-19 23:20:36 +00003477 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003478 Expr *E = getCursorExpr(C);
3479 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003480 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003481 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003482
3483 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003484 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003485
Douglas Gregor97b98722010-01-19 23:20:36 +00003486 return clang_getNullCursor();
3487 }
3488
Douglas Gregor36897b02010-09-10 00:22:18 +00003489 if (clang_isStatement(C.kind)) {
3490 Stmt *S = getCursorStmt(C);
3491 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003492 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003493
3494 return clang_getNullCursor();
3495 }
3496
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003497 if (C.kind == CXCursor_MacroInstantiation) {
3498 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003499 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003500 }
3501
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003502 if (!clang_isReference(C.kind))
3503 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003504
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003505 switch (C.kind) {
3506 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003507 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003508
3509 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003510 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003511
3512 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003513 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003514
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003515 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003516 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003517
3518 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003519 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003520
Douglas Gregor69319002010-08-31 23:48:11 +00003521 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003522 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003523
Douglas Gregora67e03f2010-09-09 21:42:20 +00003524 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003525 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003526
Ted Kremenek3064ef92010-08-27 21:34:58 +00003527 case CXCursor_CXXBaseSpecifier: {
3528 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3529 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003530 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003531 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003532
Douglas Gregor36897b02010-09-10 00:22:18 +00003533 case CXCursor_LabelRef:
3534 // FIXME: We end up faking the "parent" declaration here because we
3535 // don't want to make CXCursor larger.
3536 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003537 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3538 .getTranslationUnitDecl(),
3539 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003540
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003541 case CXCursor_OverloadedDeclRef:
3542 return C;
3543
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003544 default:
3545 // We would prefer to enumerate all non-reference cursor kinds here.
3546 llvm_unreachable("Unhandled reference cursor kind");
3547 break;
3548 }
3549 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003550
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003551 return clang_getNullCursor();
3552}
3553
Douglas Gregorb6998662010-01-19 19:34:47 +00003554CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003555 if (clang_isInvalid(C.kind))
3556 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003557
Ted Kremeneka60ed472010-11-16 08:15:36 +00003558 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003559
Douglas Gregorb6998662010-01-19 19:34:47 +00003560 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003561 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003562 C = clang_getCursorReferenced(C);
3563 WasReference = true;
3564 }
3565
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003566 if (C.kind == CXCursor_MacroInstantiation)
3567 return clang_getCursorReferenced(C);
3568
Douglas Gregorb6998662010-01-19 19:34:47 +00003569 if (!clang_isDeclaration(C.kind))
3570 return clang_getNullCursor();
3571
3572 Decl *D = getCursorDecl(C);
3573 if (!D)
3574 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003575
Douglas Gregorb6998662010-01-19 19:34:47 +00003576 switch (D->getKind()) {
3577 // Declaration kinds that don't really separate the notions of
3578 // declaration and definition.
3579 case Decl::Namespace:
3580 case Decl::Typedef:
3581 case Decl::TemplateTypeParm:
3582 case Decl::EnumConstant:
3583 case Decl::Field:
3584 case Decl::ObjCIvar:
3585 case Decl::ObjCAtDefsField:
3586 case Decl::ImplicitParam:
3587 case Decl::ParmVar:
3588 case Decl::NonTypeTemplateParm:
3589 case Decl::TemplateTemplateParm:
3590 case Decl::ObjCCategoryImpl:
3591 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003592 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003593 case Decl::LinkageSpec:
3594 case Decl::ObjCPropertyImpl:
3595 case Decl::FileScopeAsm:
3596 case Decl::StaticAssert:
3597 case Decl::Block:
3598 return C;
3599
3600 // Declaration kinds that don't make any sense here, but are
3601 // nonetheless harmless.
3602 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003603 break;
3604
3605 // Declaration kinds for which the definition is not resolvable.
3606 case Decl::UnresolvedUsingTypename:
3607 case Decl::UnresolvedUsingValue:
3608 break;
3609
3610 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003611 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003612 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003613
3614 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003615 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003616
3617 case Decl::Enum:
3618 case Decl::Record:
3619 case Decl::CXXRecord:
3620 case Decl::ClassTemplateSpecialization:
3621 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003622 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003623 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003624 return clang_getNullCursor();
3625
3626 case Decl::Function:
3627 case Decl::CXXMethod:
3628 case Decl::CXXConstructor:
3629 case Decl::CXXDestructor:
3630 case Decl::CXXConversion: {
3631 const FunctionDecl *Def = 0;
3632 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003633 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003634 return clang_getNullCursor();
3635 }
3636
3637 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003638 // Ask the variable if it has a definition.
3639 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003640 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003641 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003642 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003643
Douglas Gregorb6998662010-01-19 19:34:47 +00003644 case Decl::FunctionTemplate: {
3645 const FunctionDecl *Def = 0;
3646 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003647 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003648 return clang_getNullCursor();
3649 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003650
Douglas Gregorb6998662010-01-19 19:34:47 +00003651 case Decl::ClassTemplate: {
3652 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003653 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003654 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003655 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003656 return clang_getNullCursor();
3657 }
3658
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003659 case Decl::Using:
3660 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003661 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003662
3663 case Decl::UsingShadow:
3664 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003665 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003666 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003667
3668 case Decl::ObjCMethod: {
3669 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3670 if (Method->isThisDeclarationADefinition())
3671 return C;
3672
3673 // Dig out the method definition in the associated
3674 // @implementation, if we have it.
3675 // FIXME: The ASTs should make finding the definition easier.
3676 if (ObjCInterfaceDecl *Class
3677 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3678 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3679 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3680 Method->isInstanceMethod()))
3681 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003682 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003683
3684 return clang_getNullCursor();
3685 }
3686
3687 case Decl::ObjCCategory:
3688 if (ObjCCategoryImplDecl *Impl
3689 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003690 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003691 return clang_getNullCursor();
3692
3693 case Decl::ObjCProtocol:
3694 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3695 return C;
3696 return clang_getNullCursor();
3697
3698 case Decl::ObjCInterface:
3699 // There are two notions of a "definition" for an Objective-C
3700 // class: the interface and its implementation. When we resolved a
3701 // reference to an Objective-C class, produce the @interface as
3702 // the definition; when we were provided with the interface,
3703 // produce the @implementation as the definition.
3704 if (WasReference) {
3705 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3706 return C;
3707 } else if (ObjCImplementationDecl *Impl
3708 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003709 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003710 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003711
Douglas Gregorb6998662010-01-19 19:34:47 +00003712 case Decl::ObjCProperty:
3713 // FIXME: We don't really know where to find the
3714 // ObjCPropertyImplDecls that implement this property.
3715 return clang_getNullCursor();
3716
3717 case Decl::ObjCCompatibleAlias:
3718 if (ObjCInterfaceDecl *Class
3719 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3720 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003721 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003722
Douglas Gregorb6998662010-01-19 19:34:47 +00003723 return clang_getNullCursor();
3724
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003725 case Decl::ObjCForwardProtocol:
3726 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003727 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003728
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003729 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003730 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003731 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003732
3733 case Decl::Friend:
3734 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003735 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003736 return clang_getNullCursor();
3737
3738 case Decl::FriendTemplate:
3739 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003740 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003741 return clang_getNullCursor();
3742 }
3743
3744 return clang_getNullCursor();
3745}
3746
3747unsigned clang_isCursorDefinition(CXCursor C) {
3748 if (!clang_isDeclaration(C.kind))
3749 return 0;
3750
3751 return clang_getCursorDefinition(C) == C;
3752}
3753
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003754unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003755 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003756 return 0;
3757
3758 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3759 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3760 return E->getNumDecls();
3761
3762 if (OverloadedTemplateStorage *S
3763 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3764 return S->size();
3765
3766 Decl *D = Storage.get<Decl*>();
3767 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003768 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003769 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3770 return Classes->size();
3771 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3772 return Protocols->protocol_size();
3773
3774 return 0;
3775}
3776
3777CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003778 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003779 return clang_getNullCursor();
3780
3781 if (index >= clang_getNumOverloadedDecls(cursor))
3782 return clang_getNullCursor();
3783
Ted Kremeneka60ed472010-11-16 08:15:36 +00003784 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003785 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3786 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003787 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003788
3789 if (OverloadedTemplateStorage *S
3790 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003791 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003792
3793 Decl *D = Storage.get<Decl*>();
3794 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3795 // FIXME: This is, unfortunately, linear time.
3796 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3797 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003798 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003799 }
3800
3801 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003802 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003803
3804 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003805 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003806
3807 return clang_getNullCursor();
3808}
3809
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003810void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003811 const char **startBuf,
3812 const char **endBuf,
3813 unsigned *startLine,
3814 unsigned *startColumn,
3815 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003816 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003817 assert(getCursorDecl(C) && "CXCursor has null decl");
3818 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003819 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3820 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003821
Steve Naroff4ade6d62009-09-23 17:52:52 +00003822 SourceManager &SM = FD->getASTContext().getSourceManager();
3823 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3824 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3825 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3826 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3827 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3828 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3829}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003830
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003831void clang_enableStackTraces(void) {
3832 llvm::sys::PrintStackTraceOnErrorSignal();
3833}
3834
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003835void clang_executeOnThread(void (*fn)(void*), void *user_data,
3836 unsigned stack_size) {
3837 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3838}
3839
Ted Kremenekfb480492010-01-13 21:46:36 +00003840} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003841
Ted Kremenekfb480492010-01-13 21:46:36 +00003842//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003843// Token-based Operations.
3844//===----------------------------------------------------------------------===//
3845
3846/* CXToken layout:
3847 * int_data[0]: a CXTokenKind
3848 * int_data[1]: starting token location
3849 * int_data[2]: token length
3850 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003852 * otherwise unused.
3853 */
3854extern "C" {
3855
3856CXTokenKind clang_getTokenKind(CXToken CXTok) {
3857 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3858}
3859
3860CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3861 switch (clang_getTokenKind(CXTok)) {
3862 case CXToken_Identifier:
3863 case CXToken_Keyword:
3864 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003865 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3866 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003867
3868 case CXToken_Literal: {
3869 // We have stashed the starting pointer in the ptr_data field. Use it.
3870 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003871 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003872 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003873
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 case CXToken_Punctuation:
3875 case CXToken_Comment:
3876 break;
3877 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003878
3879 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003880 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003881 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003882 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003883 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003884
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003885 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3886 std::pair<FileID, unsigned> LocInfo
3887 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003888 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003889 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003890 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3891 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003892 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003894 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003896
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003897CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003898 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003899 if (!CXXUnit)
3900 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003901
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003902 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3903 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3904}
3905
3906CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003907 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003908 if (!CXXUnit)
3909 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003910
3911 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003912 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3913}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003914
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003915void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3916 CXToken **Tokens, unsigned *NumTokens) {
3917 if (Tokens)
3918 *Tokens = 0;
3919 if (NumTokens)
3920 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003921
Ted Kremeneka60ed472010-11-16 08:15:36 +00003922 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003923 if (!CXXUnit || !Tokens || !NumTokens)
3924 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003925
Douglas Gregorbdf60622010-03-05 21:16:25 +00003926 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3927
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003928 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003929 if (R.isInvalid())
3930 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003931
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003932 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3933 std::pair<FileID, unsigned> BeginLocInfo
3934 = SourceMgr.getDecomposedLoc(R.getBegin());
3935 std::pair<FileID, unsigned> EndLocInfo
3936 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003937
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003938 // Cannot tokenize across files.
3939 if (BeginLocInfo.first != EndLocInfo.first)
3940 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003941
3942 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003943 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003944 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003945 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003946 if (Invalid)
3947 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003948
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003949 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3950 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003951 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003952 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003953
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003954 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003955 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003956 llvm::SmallVector<CXToken, 32> CXTokens;
3957 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003958 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003959 do {
3960 // Lex the next token
3961 Lex.LexFromRawLexer(Tok);
3962 if (Tok.is(tok::eof))
3963 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003964
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003965 // Initialize the CXToken.
3966 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003967
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003968 // - Common fields
3969 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3970 CXTok.int_data[2] = Tok.getLength();
3971 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003972
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003973 // - Kind-specific fields
3974 if (Tok.isLiteral()) {
3975 CXTok.int_data[0] = CXToken_Literal;
3976 CXTok.ptr_data = (void *)Tok.getLiteralData();
3977 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003978 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003979 std::pair<FileID, unsigned> LocInfo
3980 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003981 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003982 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003983 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3984 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003985 return;
3986
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003987 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003988 IdentifierInfo *II
3989 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003990
David Chisnall096428b2010-10-13 21:44:48 +00003991 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003992 CXTok.int_data[0] = CXToken_Keyword;
3993 }
3994 else {
3995 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3996 CXToken_Identifier
3997 : CXToken_Keyword;
3998 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003999 CXTok.ptr_data = II;
4000 } else if (Tok.is(tok::comment)) {
4001 CXTok.int_data[0] = CXToken_Comment;
4002 CXTok.ptr_data = 0;
4003 } else {
4004 CXTok.int_data[0] = CXToken_Punctuation;
4005 CXTok.ptr_data = 0;
4006 }
4007 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004008 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004009 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004010
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004011 if (CXTokens.empty())
4012 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004013
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004014 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4015 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4016 *NumTokens = CXTokens.size();
4017}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004018
Ted Kremenek6db61092010-05-05 00:55:15 +00004019void clang_disposeTokens(CXTranslationUnit TU,
4020 CXToken *Tokens, unsigned NumTokens) {
4021 free(Tokens);
4022}
4023
4024} // end: extern "C"
4025
4026//===----------------------------------------------------------------------===//
4027// Token annotation APIs.
4028//===----------------------------------------------------------------------===//
4029
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004030typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004031static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4032 CXCursor parent,
4033 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004034namespace {
4035class AnnotateTokensWorker {
4036 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004037 CXToken *Tokens;
4038 CXCursor *Cursors;
4039 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004040 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004041 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004042 CursorVisitor AnnotateVis;
4043 SourceManager &SrcMgr;
4044
4045 bool MoreTokens() const { return TokIdx < NumTokens; }
4046 unsigned NextToken() const { return TokIdx; }
4047 void AdvanceToken() { ++TokIdx; }
4048 SourceLocation GetTokenLoc(unsigned tokI) {
4049 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4050 }
4051
Ted Kremenek6db61092010-05-05 00:55:15 +00004052public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004053 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004054 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004055 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004056 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004057 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004058 AnnotateVis(tu,
4059 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004060 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004061 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004062
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004063 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004064 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004065 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004066 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004067 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004068 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004069};
4070}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004071
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004072void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4073 // Walk the AST within the region of interest, annotating tokens
4074 // along the way.
4075 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004076
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004077 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4078 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004079 if (Pos != Annotated.end() &&
4080 (clang_isInvalid(Cursors[I].kind) ||
4081 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004082 Cursors[I] = Pos->second;
4083 }
4084
4085 // Finish up annotating any tokens left.
4086 if (!MoreTokens())
4087 return;
4088
4089 const CXCursor &C = clang_getNullCursor();
4090 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4091 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4092 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004093 }
4094}
4095
Ted Kremenek6db61092010-05-05 00:55:15 +00004096enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004097AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004098 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004099 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004100 if (cursorRange.isInvalid())
4101 return CXChildVisit_Recurse;
4102
Douglas Gregor4419b672010-10-21 06:10:04 +00004103 if (clang_isPreprocessing(cursor.kind)) {
4104 // For macro instantiations, just note where the beginning of the macro
4105 // instantiation occurs.
4106 if (cursor.kind == CXCursor_MacroInstantiation) {
4107 Annotated[Loc.int_data] = cursor;
4108 return CXChildVisit_Recurse;
4109 }
4110
Douglas Gregor4419b672010-10-21 06:10:04 +00004111 // Items in the preprocessing record are kept separate from items in
4112 // declarations, so we keep a separate token index.
4113 unsigned SavedTokIdx = TokIdx;
4114 TokIdx = PreprocessingTokIdx;
4115
4116 // Skip tokens up until we catch up to the beginning of the preprocessing
4117 // entry.
4118 while (MoreTokens()) {
4119 const unsigned I = NextToken();
4120 SourceLocation TokLoc = GetTokenLoc(I);
4121 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4122 case RangeBefore:
4123 AdvanceToken();
4124 continue;
4125 case RangeAfter:
4126 case RangeOverlap:
4127 break;
4128 }
4129 break;
4130 }
4131
4132 // Look at all of the tokens within this range.
4133 while (MoreTokens()) {
4134 const unsigned I = NextToken();
4135 SourceLocation TokLoc = GetTokenLoc(I);
4136 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4137 case RangeBefore:
4138 assert(0 && "Infeasible");
4139 case RangeAfter:
4140 break;
4141 case RangeOverlap:
4142 Cursors[I] = cursor;
4143 AdvanceToken();
4144 continue;
4145 }
4146 break;
4147 }
4148
4149 // Save the preprocessing token index; restore the non-preprocessing
4150 // token index.
4151 PreprocessingTokIdx = TokIdx;
4152 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004153 return CXChildVisit_Recurse;
4154 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004155
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004156 if (cursorRange.isInvalid())
4157 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004158
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004159 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4160
Ted Kremeneka333c662010-05-12 05:29:33 +00004161 // Adjust the annotated range based specific declarations.
4162 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4163 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004164 Decl *D = cxcursor::getCursorDecl(cursor);
4165 // Don't visit synthesized ObjC methods, since they have no syntatic
4166 // representation in the source.
4167 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4168 if (MD->isSynthesized())
4169 return CXChildVisit_Continue;
4170 }
4171 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004172 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4173 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004174 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004175 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004176 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004177 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004178 }
4179 }
4180 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004181
Ted Kremenek3f404602010-08-14 01:14:06 +00004182 // If the location of the cursor occurs within a macro instantiation, record
4183 // the spelling location of the cursor in our annotation map. We can then
4184 // paper over the token labelings during a post-processing step to try and
4185 // get cursor mappings for tokens that are the *arguments* of a macro
4186 // instantiation.
4187 if (L.isMacroID()) {
4188 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4189 // Only invalidate the old annotation if it isn't part of a preprocessing
4190 // directive. Here we assume that the default construction of CXCursor
4191 // results in CXCursor.kind being an initialized value (i.e., 0). If
4192 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004193
Ted Kremenek3f404602010-08-14 01:14:06 +00004194 CXCursor &oldC = Annotated[rawEncoding];
4195 if (!clang_isPreprocessing(oldC.kind))
4196 oldC = cursor;
4197 }
4198
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004199 const enum CXCursorKind K = clang_getCursorKind(parent);
4200 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004201 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4202 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004203
4204 while (MoreTokens()) {
4205 const unsigned I = NextToken();
4206 SourceLocation TokLoc = GetTokenLoc(I);
4207 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4208 case RangeBefore:
4209 Cursors[I] = updateC;
4210 AdvanceToken();
4211 continue;
4212 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004213 case RangeOverlap:
4214 break;
4215 }
4216 break;
4217 }
4218
4219 // Visit children to get their cursor information.
4220 const unsigned BeforeChildren = NextToken();
4221 VisitChildren(cursor);
4222 const unsigned AfterChildren = NextToken();
4223
4224 // Adjust 'Last' to the last token within the extent of the cursor.
4225 while (MoreTokens()) {
4226 const unsigned I = NextToken();
4227 SourceLocation TokLoc = GetTokenLoc(I);
4228 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4229 case RangeBefore:
4230 assert(0 && "Infeasible");
4231 case RangeAfter:
4232 break;
4233 case RangeOverlap:
4234 Cursors[I] = updateC;
4235 AdvanceToken();
4236 continue;
4237 }
4238 break;
4239 }
4240 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004241
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004242 // Scan the tokens that are at the beginning of the cursor, but are not
4243 // capture by the child cursors.
4244
4245 // For AST elements within macros, rely on a post-annotate pass to
4246 // to correctly annotate the tokens with cursors. Otherwise we can
4247 // get confusing results of having tokens that map to cursors that really
4248 // are expanded by an instantiation.
4249 if (L.isMacroID())
4250 cursor = clang_getNullCursor();
4251
4252 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4253 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4254 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004255
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004256 Cursors[I] = cursor;
4257 }
4258 // Scan the tokens that are at the end of the cursor, but are not captured
4259 // but the child cursors.
4260 for (unsigned I = AfterChildren; I != Last; ++I)
4261 Cursors[I] = cursor;
4262
4263 TokIdx = Last;
4264 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004265}
4266
Ted Kremenek6db61092010-05-05 00:55:15 +00004267static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4268 CXCursor parent,
4269 CXClientData client_data) {
4270 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4271}
4272
Ted Kremenekab979612010-11-11 08:05:23 +00004273// This gets run a separate thread to avoid stack blowout.
4274static void runAnnotateTokensWorker(void *UserData) {
4275 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4276}
4277
Ted Kremenek6db61092010-05-05 00:55:15 +00004278extern "C" {
4279
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004280void clang_annotateTokens(CXTranslationUnit TU,
4281 CXToken *Tokens, unsigned NumTokens,
4282 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004283
4284 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004285 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004286
Douglas Gregor4419b672010-10-21 06:10:04 +00004287 // Any token we don't specifically annotate will have a NULL cursor.
4288 CXCursor C = clang_getNullCursor();
4289 for (unsigned I = 0; I != NumTokens; ++I)
4290 Cursors[I] = C;
4291
Ted Kremeneka60ed472010-11-16 08:15:36 +00004292 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004293 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004294 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004295
Douglas Gregorbdf60622010-03-05 21:16:25 +00004296 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004297
Douglas Gregor0396f462010-03-19 05:22:59 +00004298 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004299 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004300 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4301 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004302 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4303 clang_getTokenLocation(TU,
4304 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004305
Douglas Gregor0396f462010-03-19 05:22:59 +00004306 // A mapping from the source locations found when re-lexing or traversing the
4307 // region of interest to the corresponding cursors.
4308 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004309
4310 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004311 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004312 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4313 std::pair<FileID, unsigned> BeginLocInfo
4314 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4315 std::pair<FileID, unsigned> EndLocInfo
4316 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004317
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004318 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004319 bool Invalid = false;
4320 if (BeginLocInfo.first == EndLocInfo.first &&
4321 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4322 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004323 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4324 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004325 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004326 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004327 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004328
4329 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004330 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004331 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004332 Token Tok;
4333 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004334
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004335 reprocess:
4336 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4337 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004338 // don't see it while preprocessing these tokens later, but keep track
4339 // of all of the token locations inside this preprocessing directive so
4340 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004341 //
4342 // FIXME: Some simple tests here could identify macro definitions and
4343 // #undefs, to provide specific cursor kinds for those.
4344 std::vector<SourceLocation> Locations;
4345 do {
4346 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004347 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004348 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004349
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004350 using namespace cxcursor;
4351 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004352 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4353 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004354 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004355 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4356 Annotated[Locations[I].getRawEncoding()] = Cursor;
4357 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004358
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004359 if (Tok.isAtStartOfLine())
4360 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004361
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004362 continue;
4363 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004364
Douglas Gregor48072312010-03-18 15:23:44 +00004365 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004366 break;
4367 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004368 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004369
Douglas Gregor0396f462010-03-19 05:22:59 +00004370 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004371 // a specific cursor.
4372 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004373 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004374
4375 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004376 // FIXME: We use a ridiculous stack size here because the data-recursion
4377 // algorithm uses a large stack frame than the non-data recursive version,
4378 // and AnnotationTokensWorker currently transforms the data-recursion
4379 // algorithm back into a traditional recursion by explicitly calling
4380 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004381 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004382 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4383 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004384 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4385 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004387} // end: extern "C"
4388
4389//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004390// Operations for querying linkage of a cursor.
4391//===----------------------------------------------------------------------===//
4392
4393extern "C" {
4394CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004395 if (!clang_isDeclaration(cursor.kind))
4396 return CXLinkage_Invalid;
4397
Ted Kremenek16b42592010-03-03 06:36:57 +00004398 Decl *D = cxcursor::getCursorDecl(cursor);
4399 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4400 switch (ND->getLinkage()) {
4401 case NoLinkage: return CXLinkage_NoLinkage;
4402 case InternalLinkage: return CXLinkage_Internal;
4403 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4404 case ExternalLinkage: return CXLinkage_External;
4405 };
4406
4407 return CXLinkage_Invalid;
4408}
4409} // end: extern "C"
4410
4411//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004412// Operations for querying language of a cursor.
4413//===----------------------------------------------------------------------===//
4414
4415static CXLanguageKind getDeclLanguage(const Decl *D) {
4416 switch (D->getKind()) {
4417 default:
4418 break;
4419 case Decl::ImplicitParam:
4420 case Decl::ObjCAtDefsField:
4421 case Decl::ObjCCategory:
4422 case Decl::ObjCCategoryImpl:
4423 case Decl::ObjCClass:
4424 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004425 case Decl::ObjCForwardProtocol:
4426 case Decl::ObjCImplementation:
4427 case Decl::ObjCInterface:
4428 case Decl::ObjCIvar:
4429 case Decl::ObjCMethod:
4430 case Decl::ObjCProperty:
4431 case Decl::ObjCPropertyImpl:
4432 case Decl::ObjCProtocol:
4433 return CXLanguage_ObjC;
4434 case Decl::CXXConstructor:
4435 case Decl::CXXConversion:
4436 case Decl::CXXDestructor:
4437 case Decl::CXXMethod:
4438 case Decl::CXXRecord:
4439 case Decl::ClassTemplate:
4440 case Decl::ClassTemplatePartialSpecialization:
4441 case Decl::ClassTemplateSpecialization:
4442 case Decl::Friend:
4443 case Decl::FriendTemplate:
4444 case Decl::FunctionTemplate:
4445 case Decl::LinkageSpec:
4446 case Decl::Namespace:
4447 case Decl::NamespaceAlias:
4448 case Decl::NonTypeTemplateParm:
4449 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004450 case Decl::TemplateTemplateParm:
4451 case Decl::TemplateTypeParm:
4452 case Decl::UnresolvedUsingTypename:
4453 case Decl::UnresolvedUsingValue:
4454 case Decl::Using:
4455 case Decl::UsingDirective:
4456 case Decl::UsingShadow:
4457 return CXLanguage_CPlusPlus;
4458 }
4459
4460 return CXLanguage_C;
4461}
4462
4463extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004464
4465enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4466 if (clang_isDeclaration(cursor.kind))
4467 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4468 if (D->hasAttr<UnavailableAttr>() ||
4469 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4470 return CXAvailability_Available;
4471
4472 if (D->hasAttr<DeprecatedAttr>())
4473 return CXAvailability_Deprecated;
4474 }
4475
4476 return CXAvailability_Available;
4477}
4478
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004479CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4480 if (clang_isDeclaration(cursor.kind))
4481 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4482
4483 return CXLanguage_Invalid;
4484}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004485
4486CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4487 if (clang_isDeclaration(cursor.kind)) {
4488 if (Decl *D = getCursorDecl(cursor)) {
4489 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004490 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004491 }
4492 }
4493
4494 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4495 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004496 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004497 }
4498
4499 return clang_getNullCursor();
4500}
4501
4502CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4503 if (clang_isDeclaration(cursor.kind)) {
4504 if (Decl *D = getCursorDecl(cursor)) {
4505 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004506 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004507 }
4508 }
4509
4510 // FIXME: Note that we can't easily compute the lexical context of a
4511 // statement or expression, so we return nothing.
4512 return clang_getNullCursor();
4513}
4514
Douglas Gregor9f592342010-10-01 20:25:15 +00004515static void CollectOverriddenMethods(DeclContext *Ctx,
4516 ObjCMethodDecl *Method,
4517 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4518 if (!Ctx)
4519 return;
4520
4521 // If we have a class or category implementation, jump straight to the
4522 // interface.
4523 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4524 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4525
4526 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4527 if (!Container)
4528 return;
4529
4530 // Check whether we have a matching method at this level.
4531 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4532 Method->isInstanceMethod()))
4533 if (Method != Overridden) {
4534 // We found an override at this level; there is no need to look
4535 // into other protocols or categories.
4536 Methods.push_back(Overridden);
4537 return;
4538 }
4539
4540 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4541 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4542 PEnd = Protocol->protocol_end();
4543 P != PEnd; ++P)
4544 CollectOverriddenMethods(*P, Method, Methods);
4545 }
4546
4547 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4548 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4549 PEnd = Category->protocol_end();
4550 P != PEnd; ++P)
4551 CollectOverriddenMethods(*P, Method, Methods);
4552 }
4553
4554 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4555 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4556 PEnd = Interface->protocol_end();
4557 P != PEnd; ++P)
4558 CollectOverriddenMethods(*P, Method, Methods);
4559
4560 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4561 Category; Category = Category->getNextClassCategory())
4562 CollectOverriddenMethods(Category, Method, Methods);
4563
4564 // We only look into the superclass if we haven't found anything yet.
4565 if (Methods.empty())
4566 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4567 return CollectOverriddenMethods(Super, Method, Methods);
4568 }
4569}
4570
4571void clang_getOverriddenCursors(CXCursor cursor,
4572 CXCursor **overridden,
4573 unsigned *num_overridden) {
4574 if (overridden)
4575 *overridden = 0;
4576 if (num_overridden)
4577 *num_overridden = 0;
4578 if (!overridden || !num_overridden)
4579 return;
4580
4581 if (!clang_isDeclaration(cursor.kind))
4582 return;
4583
4584 Decl *D = getCursorDecl(cursor);
4585 if (!D)
4586 return;
4587
4588 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004589 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004590 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4591 *num_overridden = CXXMethod->size_overridden_methods();
4592 if (!*num_overridden)
4593 return;
4594
4595 *overridden = new CXCursor [*num_overridden];
4596 unsigned I = 0;
4597 for (CXXMethodDecl::method_iterator
4598 M = CXXMethod->begin_overridden_methods(),
4599 MEnd = CXXMethod->end_overridden_methods();
4600 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004601 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004602 return;
4603 }
4604
4605 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4606 if (!Method)
4607 return;
4608
4609 // Handle Objective-C methods.
4610 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4611 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4612
4613 if (Methods.empty())
4614 return;
4615
4616 *num_overridden = Methods.size();
4617 *overridden = new CXCursor [Methods.size()];
4618 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004619 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004620}
4621
4622void clang_disposeOverriddenCursors(CXCursor *overridden) {
4623 delete [] overridden;
4624}
4625
Douglas Gregorecdcb882010-10-20 22:00:55 +00004626CXFile clang_getIncludedFile(CXCursor cursor) {
4627 if (cursor.kind != CXCursor_InclusionDirective)
4628 return 0;
4629
4630 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4631 return (void *)ID->getFile();
4632}
4633
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004634} // end: extern "C"
4635
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004636
4637//===----------------------------------------------------------------------===//
4638// C++ AST instrospection.
4639//===----------------------------------------------------------------------===//
4640
4641extern "C" {
4642unsigned clang_CXXMethod_isStatic(CXCursor C) {
4643 if (!clang_isDeclaration(C.kind))
4644 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004645
4646 CXXMethodDecl *Method = 0;
4647 Decl *D = cxcursor::getCursorDecl(C);
4648 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4649 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4650 else
4651 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4652 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004653}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004654
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004655} // end: extern "C"
4656
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004657//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004658// Attribute introspection.
4659//===----------------------------------------------------------------------===//
4660
4661extern "C" {
4662CXType clang_getIBOutletCollectionType(CXCursor C) {
4663 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004664 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004665
4666 IBOutletCollectionAttr *A =
4667 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4668
Ted Kremeneka60ed472010-11-16 08:15:36 +00004669 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004670}
4671} // end: extern "C"
4672
4673//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004674// Misc. utility functions.
4675//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004676
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004677/// Default to using an 8 MB stack size on "safety" threads.
4678static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004679
4680namespace clang {
4681
4682bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004683 void (*Fn)(void*), void *UserData,
4684 unsigned Size) {
4685 if (!Size)
4686 Size = GetSafetyThreadStackSize();
4687 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004688 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4689 return CRC.RunSafely(Fn, UserData);
4690}
4691
4692unsigned GetSafetyThreadStackSize() {
4693 return SafetyStackThreadSize;
4694}
4695
4696void SetSafetyThreadStackSize(unsigned Value) {
4697 SafetyStackThreadSize = Value;
4698}
4699
4700}
4701
Ted Kremenek04bb7162010-01-22 22:44:15 +00004702extern "C" {
4703
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004704CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004705 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004706}
4707
4708} // end: extern "C"