blob: 2bc362adfc523d7d2cfb04ac80471da38e92919c [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,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000143 DeclarationNameInfoVisitKind,
144 MemberRefVisitKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000145protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000146 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147 CXCursor parent;
148 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
150 : parent(C), K(k) {
151 data[0] = d1;
152 data[1] = d2;
153 data[2] = d3;
154 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000155public:
156 Kind getKind() const { return K; }
157 const CXCursor &getParent() const { return parent; }
158 static bool classof(VisitorJob *VJ) { return true; }
159};
160
161typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
162
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000164class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000165 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000168 CXTranslationUnit TU;
169 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The declaration that serves at the parent of any statement or
175 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000176 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000178 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000179 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000184 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
185 // to the visitor. Declarations with a PCH level greater than this value will
186 // be suppressed.
187 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188
189 /// \brief When valid, a source range to which the cursor should restrict
190 /// its search.
191 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000193 // FIXME: Eventually remove. This part of a hack to support proper
194 // iteration over all Decls contained lexically within an ObjC container.
195 DeclContext::decl_iterator *DI_current;
196 DeclContext::decl_iterator DE_current;
197
Ted Kremenekd1ded662010-11-15 23:31:32 +0000198 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
199 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
200 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000204
205 /// \brief Determine whether this particular source range comes before, comes
206 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000208 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
210
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000211 class SetParentRAII {
212 CXCursor &Parent;
213 Decl *&StmtParent;
214 CXCursor OldParent;
215
216 public:
217 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
218 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
219 {
220 Parent = NewParent;
221 if (clang_isDeclaration(Parent.kind))
222 StmtParent = getCursorDecl(Parent);
223 }
224
225 ~SetParentRAII() {
226 Parent = OldParent;
227 if (clang_isDeclaration(Parent.kind))
228 StmtParent = getCursorDecl(Parent);
229 }
230 };
231
Steve Naroff89922f82009-08-31 00:59:03 +0000232public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000233 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
234 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000237 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
238 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000239 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
240 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 {
242 Parent.kind = CXCursor_NoDeclFound;
243 Parent.data[0] = 0;
244 Parent.data[1] = 0;
245 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000246 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000247 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000248
Ted Kremenekd1ded662010-11-15 23:31:32 +0000249 ~CursorVisitor() {
250 // Free the pre-allocated worklists for data-recursion.
251 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
252 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
253 delete *I;
254 }
255 }
256
Ted Kremeneka60ed472010-11-16 08:15:36 +0000257 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
258 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000259
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000260 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000261
262 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
263 getPreprocessedEntities();
264
Douglas Gregorb1373d02010-01-20 20:59:29 +0000265 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000266
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000268 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000269 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000270 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000271 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000273 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
274 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000276 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000277 bool VisitClassTemplatePartialSpecializationDecl(
278 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000279 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000280 bool VisitEnumConstantDecl(EnumConstantDecl *D);
281 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
282 bool VisitFunctionDecl(FunctionDecl *ND);
283 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000284 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000285 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000287 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000288 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
290 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
291 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
292 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000293 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
295 bool VisitObjCImplDecl(ObjCImplDecl *D);
296 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
297 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
299 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
300 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000301 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000302 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000303 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000304 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000305 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000306 bool VisitUsingDecl(UsingDecl *D);
307 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
308 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000309
Douglas Gregor01829d32010-08-31 14:41:23 +0000310 // Name visitor
311 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000312 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000313
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000314 // Template visitors
315 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000316 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000317 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
318
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000319 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000320 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000322 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
324 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000325 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000326 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000327 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
329 bool VisitPointerTypeLoc(PointerTypeLoc TL);
330 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
331 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
332 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
333 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000334 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000335 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000336 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000337 // FIXME: Implement visitors here when the unimplemented TypeLocs get
338 // implemented
339 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
340 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000341
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000342 // Data-recursive visitor functions.
343 bool IsInRegionOfInterest(CXCursor C);
344 bool RunVisitorWorkList(VisitorWorkList &WL);
345 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000346 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000347};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000348
Ted Kremenekab188932010-01-05 19:32:54 +0000349} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000350
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000351static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000352static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
353
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000354
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000355RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000356 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357}
358
Douglas Gregorb1373d02010-01-20 20:59:29 +0000359/// \brief Visit the given cursor and, if requested by the visitor,
360/// its children.
361///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362/// \param Cursor the cursor to visit.
363///
364/// \param CheckRegionOfInterest if true, then the caller already checked that
365/// this cursor is within the region of interest.
366///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000367/// \returns true if the visitation should be aborted, false if it
368/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000369bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370 if (clang_isInvalid(Cursor.kind))
371 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000372
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373 if (clang_isDeclaration(Cursor.kind)) {
374 Decl *D = getCursorDecl(Cursor);
375 assert(D && "Invalid declaration cursor");
376 if (D->getPCHLevel() > MaxPCHLevel)
377 return false;
378
379 if (D->isImplicit())
380 return false;
381 }
382
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000383 // If we have a range of interest, and this cursor doesn't intersect with it,
384 // we're done.
385 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000386 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000387 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388 return false;
389 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000390
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391 switch (Visitor(Cursor, Parent, ClientData)) {
392 case CXChildVisit_Break:
393 return true;
394
395 case CXChildVisit_Continue:
396 return false;
397
398 case CXChildVisit_Recurse:
399 return VisitChildren(Cursor);
400 }
401
Douglas Gregorfd643772010-01-25 16:45:46 +0000402 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403}
404
Douglas Gregor788f5a12010-03-20 00:41:21 +0000405std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
406CursorVisitor::getPreprocessedEntities() {
407 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000408 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000409
410 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000411 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000412
413 // There is no region of interest; we have to walk everything.
414 if (RegionOfInterest.isInvalid())
415 return std::make_pair(PPRec.begin(OnlyLocalDecls),
416 PPRec.end(OnlyLocalDecls));
417
418 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000419 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000420 std::pair<FileID, unsigned> Begin
421 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
422 std::pair<FileID, unsigned> End
423 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
424
425 // The region of interest spans files; we have to walk everything.
426 if (Begin.first != End.first)
427 return std::make_pair(PPRec.begin(OnlyLocalDecls),
428 PPRec.end(OnlyLocalDecls));
429
430 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000431 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000432 if (ByFileMap.empty()) {
433 // Build the mapping from files to sets of preprocessed entities.
434 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
435 EEnd = PPRec.end(OnlyLocalDecls);
436 E != EEnd; ++E) {
437 std::pair<FileID, unsigned> P
438 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
439 ByFileMap[P.first].push_back(*E);
440 }
441 }
442
443 return std::make_pair(ByFileMap[Begin.first].begin(),
444 ByFileMap[Begin.first].end());
445}
446
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000448///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000449/// \returns true if the visitation should be aborted, false if it
450/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000451bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000452 if (clang_isReference(Cursor.kind)) {
453 // By definition, references have no children.
454 return false;
455 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456
457 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000459 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460
Douglas Gregorb1373d02010-01-20 20:59:29 +0000461 if (clang_isDeclaration(Cursor.kind)) {
462 Decl *D = getCursorDecl(Cursor);
463 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000464 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000465 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
Douglas Gregora59e3902010-01-21 23:27:09 +0000467 if (clang_isStatement(Cursor.kind))
468 return Visit(getCursorStmt(Cursor));
469 if (clang_isExpression(Cursor.kind))
470 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000473 CXTranslationUnit tu = getCursorTU(Cursor);
474 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000475 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
476 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000477 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
478 TLEnd = CXXUnit->top_level_end();
479 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000480 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000481 return true;
482 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000483 } else if (VisitDeclContext(
484 CXXUnit->getASTContext().getTranslationUnitDecl()))
485 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000486
Douglas Gregor0396f462010-03-19 05:22:59 +0000487 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000488 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000489 // FIXME: Once we have the ability to deserialize a preprocessing record,
490 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000491 PreprocessingRecord::iterator E, EEnd;
492 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000494 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000496
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 continue;
498 }
499
500 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000501 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 return true;
503
504 continue;
505 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000506
507 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000508 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000509 return true;
510
511 continue;
512 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000513 }
514 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000515 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000517
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000519 return false;
520}
521
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000522bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000523 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
524 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000525
Ted Kremenek664cffd2010-07-22 11:30:19 +0000526 if (Stmt *Body = B->getBody())
527 return Visit(MakeCXCursor(Body, StmtParent, TU));
528
529 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530}
531
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000532llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
533 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000534 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000535 if (Range.isInvalid())
536 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000537
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000538 switch (CompareRegionOfInterest(Range)) {
539 case RangeBefore:
540 // This declaration comes before the region of interest; skip it.
541 return llvm::Optional<bool>();
542
543 case RangeAfter:
544 // This declaration comes after the region of interest; we're done.
545 return false;
546
547 case RangeOverlap:
548 // This declaration overlaps the region of interest; visit it.
549 break;
550 }
551 }
552 return true;
553}
554
555bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
556 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
557
558 // FIXME: Eventually remove. This part of a hack to support proper
559 // iteration over all Decls contained lexically within an ObjC container.
560 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
561 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
562
563 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000564 Decl *D = *I;
565 if (D->getLexicalDeclContext() != DC)
566 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000567 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000568 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
569 if (!V.hasValue())
570 continue;
571 if (!V.getValue())
572 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000573 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000574 return true;
575 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000576 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000577}
578
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000579bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
580 llvm_unreachable("Translation units are visited directly by Visit()");
581 return false;
582}
583
584bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
585 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
586 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000587
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000588 return false;
589}
590
591bool CursorVisitor::VisitTagDecl(TagDecl *D) {
592 return VisitDeclContext(D);
593}
594
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000595bool CursorVisitor::VisitClassTemplateSpecializationDecl(
596 ClassTemplateSpecializationDecl *D) {
597 bool ShouldVisitBody = false;
598 switch (D->getSpecializationKind()) {
599 case TSK_Undeclared:
600 case TSK_ImplicitInstantiation:
601 // Nothing to visit
602 return false;
603
604 case TSK_ExplicitInstantiationDeclaration:
605 case TSK_ExplicitInstantiationDefinition:
606 break;
607
608 case TSK_ExplicitSpecialization:
609 ShouldVisitBody = true;
610 break;
611 }
612
613 // Visit the template arguments used in the specialization.
614 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
615 TypeLoc TL = SpecType->getTypeLoc();
616 if (TemplateSpecializationTypeLoc *TSTLoc
617 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
618 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
619 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
620 return true;
621 }
622 }
623
624 if (ShouldVisitBody && VisitCXXRecordDecl(D))
625 return true;
626
627 return false;
628}
629
Douglas Gregor74dbe642010-08-31 19:31:58 +0000630bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
631 ClassTemplatePartialSpecializationDecl *D) {
632 // FIXME: Visit the "outer" template parameter lists on the TagDecl
633 // before visiting these template parameters.
634 if (VisitTemplateParameters(D->getTemplateParameters()))
635 return true;
636
637 // Visit the partial specialization arguments.
638 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
639 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
640 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
641 return true;
642
643 return VisitCXXRecordDecl(D);
644}
645
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000646bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000647 // Visit the default argument.
648 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
649 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
650 if (Visit(DefArg->getTypeLoc()))
651 return true;
652
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000653 return false;
654}
655
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000656bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
657 if (Expr *Init = D->getInitExpr())
658 return Visit(MakeCXCursor(Init, StmtParent, TU));
659 return false;
660}
661
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000662bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
663 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
664 if (Visit(TSInfo->getTypeLoc()))
665 return true;
666
667 return false;
668}
669
Douglas Gregora67e03f2010-09-09 21:42:20 +0000670/// \brief Compare two base or member initializers based on their source order.
671static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
672 CXXBaseOrMemberInitializer const * const *X
673 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
674 CXXBaseOrMemberInitializer const * const *Y
675 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
676
677 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
678 return -1;
679 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
680 return 1;
681 else
682 return 0;
683}
684
Douglas Gregorb1373d02010-01-20 20:59:29 +0000685bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000686 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
687 // Visit the function declaration's syntactic components in the order
688 // written. This requires a bit of work.
689 TypeLoc TL = TSInfo->getTypeLoc();
690 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
691
692 // If we have a function declared directly (without the use of a typedef),
693 // visit just the return type. Otherwise, just visit the function's type
694 // now.
695 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
696 (!FTL && Visit(TL)))
697 return true;
698
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000699 // Visit the nested-name-specifier, if present.
700 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
701 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
702 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000703
704 // Visit the declaration name.
705 if (VisitDeclarationNameInfo(ND->getNameInfo()))
706 return true;
707
708 // FIXME: Visit explicitly-specified template arguments!
709
710 // Visit the function parameters, if we have a function type.
711 if (FTL && VisitFunctionTypeLoc(*FTL, true))
712 return true;
713
714 // FIXME: Attributes?
715 }
716
Douglas Gregora67e03f2010-09-09 21:42:20 +0000717 if (ND->isThisDeclarationADefinition()) {
718 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
719 // Find the initializers that were written in the source.
720 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
721 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
722 IEnd = Constructor->init_end();
723 I != IEnd; ++I) {
724 if (!(*I)->isWritten())
725 continue;
726
727 WrittenInits.push_back(*I);
728 }
729
730 // Sort the initializers in source order
731 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
732 &CompareCXXBaseOrMemberInitializers);
733
734 // Visit the initializers in source order
735 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
736 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
737 if (Init->isMemberInitializer()) {
738 if (Visit(MakeCursorMemberRef(Init->getMember(),
739 Init->getMemberLocation(), TU)))
740 return true;
741 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
742 if (Visit(BaseInfo->getTypeLoc()))
743 return true;
744 }
745
746 // Visit the initializer value.
747 if (Expr *Initializer = Init->getInit())
748 if (Visit(MakeCXCursor(Initializer, ND, TU)))
749 return true;
750 }
751 }
752
753 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
754 return true;
755 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000756
Douglas Gregorb1373d02010-01-20 20:59:29 +0000757 return false;
758}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000759
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000760bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
761 if (VisitDeclaratorDecl(D))
762 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000763
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000764 if (Expr *BitWidth = D->getBitWidth())
765 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000766
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000767 return false;
768}
769
770bool CursorVisitor::VisitVarDecl(VarDecl *D) {
771 if (VisitDeclaratorDecl(D))
772 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000773
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000774 if (Expr *Init = D->getInit())
775 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000777 return false;
778}
779
Douglas Gregor84b51d72010-09-01 20:16:53 +0000780bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
781 if (VisitDeclaratorDecl(D))
782 return true;
783
784 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
785 if (Expr *DefArg = D->getDefaultArgument())
786 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
787
788 return false;
789}
790
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000791bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
792 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
793 // before visiting these template parameters.
794 if (VisitTemplateParameters(D->getTemplateParameters()))
795 return true;
796
797 return VisitFunctionDecl(D->getTemplatedDecl());
798}
799
Douglas Gregor39d6f072010-08-31 19:02:00 +0000800bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
801 // FIXME: Visit the "outer" template parameter lists on the TagDecl
802 // before visiting these template parameters.
803 if (VisitTemplateParameters(D->getTemplateParameters()))
804 return true;
805
806 return VisitCXXRecordDecl(D->getTemplatedDecl());
807}
808
Douglas Gregor84b51d72010-09-01 20:16:53 +0000809bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
810 if (VisitTemplateParameters(D->getTemplateParameters()))
811 return true;
812
813 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
814 VisitTemplateArgumentLoc(D->getDefaultArgument()))
815 return true;
816
817 return false;
818}
819
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000820bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000821 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
822 if (Visit(TSInfo->getTypeLoc()))
823 return true;
824
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000825 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000826 PEnd = ND->param_end();
827 P != PEnd; ++P) {
828 if (Visit(MakeCXCursor(*P, TU)))
829 return true;
830 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832 if (ND->isThisDeclarationADefinition() &&
833 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
834 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000835
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836 return false;
837}
838
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000839namespace {
840 struct ContainerDeclsSort {
841 SourceManager &SM;
842 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
843 bool operator()(Decl *A, Decl *B) {
844 SourceLocation L_A = A->getLocStart();
845 SourceLocation L_B = B->getLocStart();
846 assert(L_A.isValid() && L_B.isValid());
847 return SM.isBeforeInTranslationUnit(L_A, L_B);
848 }
849 };
850}
851
Douglas Gregora59e3902010-01-21 23:27:09 +0000852bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000853 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
854 // an @implementation can lexically contain Decls that are not properly
855 // nested in the AST. When we identify such cases, we need to retrofit
856 // this nesting here.
857 if (!DI_current)
858 return VisitDeclContext(D);
859
860 // Scan the Decls that immediately come after the container
861 // in the current DeclContext. If any fall within the
862 // container's lexical region, stash them into a vector
863 // for later processing.
864 llvm::SmallVector<Decl *, 24> DeclsInContainer;
865 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000866 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000867 if (EndLoc.isValid()) {
868 DeclContext::decl_iterator next = *DI_current;
869 while (++next != DE_current) {
870 Decl *D_next = *next;
871 if (!D_next)
872 break;
873 SourceLocation L = D_next->getLocStart();
874 if (!L.isValid())
875 break;
876 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
877 *DI_current = next;
878 DeclsInContainer.push_back(D_next);
879 continue;
880 }
881 break;
882 }
883 }
884
885 // The common case.
886 if (DeclsInContainer.empty())
887 return VisitDeclContext(D);
888
889 // Get all the Decls in the DeclContext, and sort them with the
890 // additional ones we've collected. Then visit them.
891 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
892 I!=E; ++I) {
893 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000894 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
895 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000896 continue;
897 DeclsInContainer.push_back(subDecl);
898 }
899
900 // Now sort the Decls so that they appear in lexical order.
901 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
902 ContainerDeclsSort(SM));
903
904 // Now visit the decls.
905 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
906 E = DeclsInContainer.end(); I != E; ++I) {
907 CXCursor Cursor = MakeCXCursor(*I, TU);
908 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
909 if (!V.hasValue())
910 continue;
911 if (!V.getValue())
912 return false;
913 if (Visit(Cursor, true))
914 return true;
915 }
916 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000917}
918
Douglas Gregorb1373d02010-01-20 20:59:29 +0000919bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000920 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
921 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000922 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000923
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000924 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
925 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
926 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000927 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000928 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000929
Douglas Gregora59e3902010-01-21 23:27:09 +0000930 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000931}
932
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000933bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
934 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
935 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
936 E = PID->protocol_end(); I != E; ++I, ++PL)
937 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
938 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000939
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000940 return VisitObjCContainerDecl(PID);
941}
942
Ted Kremenek23173d72010-05-18 21:09:07 +0000943bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000944 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000945 return true;
946
Ted Kremenek23173d72010-05-18 21:09:07 +0000947 // FIXME: This implements a workaround with @property declarations also being
948 // installed in the DeclContext for the @interface. Eventually this code
949 // should be removed.
950 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
951 if (!CDecl || !CDecl->IsClassExtension())
952 return false;
953
954 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
955 if (!ID)
956 return false;
957
958 IdentifierInfo *PropertyId = PD->getIdentifier();
959 ObjCPropertyDecl *prevDecl =
960 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
961
962 if (!prevDecl)
963 return false;
964
965 // Visit synthesized methods since they will be skipped when visiting
966 // the @interface.
967 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000968 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000969 if (Visit(MakeCXCursor(MD, TU)))
970 return true;
971
972 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000973 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000974 if (Visit(MakeCXCursor(MD, TU)))
975 return true;
976
977 return false;
978}
979
Douglas Gregorb1373d02010-01-20 20:59:29 +0000980bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000981 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000982 if (D->getSuperClass() &&
983 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000984 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000985 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000986 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000987
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000988 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
989 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
990 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000991 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000992 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993
Douglas Gregora59e3902010-01-21 23:27:09 +0000994 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000995}
996
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000997bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
998 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000999}
1000
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001001bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001002 // 'ID' could be null when dealing with invalid code.
1003 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1004 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1005 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001007 return VisitObjCImplDecl(D);
1008}
1009
1010bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1011#if 0
1012 // Issue callbacks for super class.
1013 // FIXME: No source location information!
1014 if (D->getSuperClass() &&
1015 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001017 TU)))
1018 return true;
1019#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001020
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001021 return VisitObjCImplDecl(D);
1022}
1023
1024bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1025 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1026 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1027 E = D->protocol_end();
1028 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001029 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001030 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
1032 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001033}
1034
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001035bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1036 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1037 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1038 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001040 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001041}
1042
Douglas Gregora4ffd852010-11-17 01:03:52 +00001043bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1044 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1045 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1046
1047 return false;
1048}
1049
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001050bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1051 return VisitDeclContext(D);
1052}
1053
Douglas Gregor69319002010-08-31 23:48:11 +00001054bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001055 // Visit nested-name-specifier.
1056 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1057 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1058 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001059
1060 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1061 D->getTargetNameLoc(), TU));
1062}
1063
Douglas Gregor7e242562010-09-01 19:52:22 +00001064bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001065 // Visit nested-name-specifier.
1066 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1067 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1068 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001069
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001070 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1071 return true;
1072
Douglas Gregor7e242562010-09-01 19:52:22 +00001073 return VisitDeclarationNameInfo(D->getNameInfo());
1074}
1075
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001076bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
1078 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1079 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1080 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001081
1082 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1083 D->getIdentLocation(), TU));
1084}
1085
Douglas Gregor7e242562010-09-01 19:52:22 +00001086bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 // Visit nested-name-specifier.
1088 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1089 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1090 return true;
1091
Douglas Gregor7e242562010-09-01 19:52:22 +00001092 return VisitDeclarationNameInfo(D->getNameInfo());
1093}
1094
1095bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1096 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001097 // Visit nested-name-specifier.
1098 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1099 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1100 return true;
1101
Douglas Gregor7e242562010-09-01 19:52:22 +00001102 return false;
1103}
1104
Douglas Gregor01829d32010-08-31 14:41:23 +00001105bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1106 switch (Name.getName().getNameKind()) {
1107 case clang::DeclarationName::Identifier:
1108 case clang::DeclarationName::CXXLiteralOperatorName:
1109 case clang::DeclarationName::CXXOperatorName:
1110 case clang::DeclarationName::CXXUsingDirective:
1111 return false;
1112
1113 case clang::DeclarationName::CXXConstructorName:
1114 case clang::DeclarationName::CXXDestructorName:
1115 case clang::DeclarationName::CXXConversionFunctionName:
1116 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1117 return Visit(TSInfo->getTypeLoc());
1118 return false;
1119
1120 case clang::DeclarationName::ObjCZeroArgSelector:
1121 case clang::DeclarationName::ObjCOneArgSelector:
1122 case clang::DeclarationName::ObjCMultiArgSelector:
1123 // FIXME: Per-identifier location info?
1124 return false;
1125 }
1126
1127 return false;
1128}
1129
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001130bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1131 SourceRange Range) {
1132 // FIXME: This whole routine is a hack to work around the lack of proper
1133 // source information in nested-name-specifiers (PR5791). Since we do have
1134 // a beginning source location, we can visit the first component of the
1135 // nested-name-specifier, if it's a single-token component.
1136 if (!NNS)
1137 return false;
1138
1139 // Get the first component in the nested-name-specifier.
1140 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1141 NNS = Prefix;
1142
1143 switch (NNS->getKind()) {
1144 case NestedNameSpecifier::Namespace:
1145 // FIXME: The token at this source location might actually have been a
1146 // namespace alias, but we don't model that. Lame!
1147 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1148 TU));
1149
1150 case NestedNameSpecifier::TypeSpec: {
1151 // If the type has a form where we know that the beginning of the source
1152 // range matches up with a reference cursor. Visit the appropriate reference
1153 // cursor.
1154 Type *T = NNS->getAsType();
1155 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1156 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1157 if (const TagType *Tag = dyn_cast<TagType>(T))
1158 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1159 if (const TemplateSpecializationType *TST
1160 = dyn_cast<TemplateSpecializationType>(T))
1161 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1162 break;
1163 }
1164
1165 case NestedNameSpecifier::TypeSpecWithTemplate:
1166 case NestedNameSpecifier::Global:
1167 case NestedNameSpecifier::Identifier:
1168 break;
1169 }
1170
1171 return false;
1172}
1173
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001174bool CursorVisitor::VisitTemplateParameters(
1175 const TemplateParameterList *Params) {
1176 if (!Params)
1177 return false;
1178
1179 for (TemplateParameterList::const_iterator P = Params->begin(),
1180 PEnd = Params->end();
1181 P != PEnd; ++P) {
1182 if (Visit(MakeCXCursor(*P, TU)))
1183 return true;
1184 }
1185
1186 return false;
1187}
1188
Douglas Gregor0b36e612010-08-31 20:37:03 +00001189bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1190 switch (Name.getKind()) {
1191 case TemplateName::Template:
1192 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1193
1194 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001195 // Visit the overloaded template set.
1196 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1197 return true;
1198
Douglas Gregor0b36e612010-08-31 20:37:03 +00001199 return false;
1200
1201 case TemplateName::DependentTemplate:
1202 // FIXME: Visit nested-name-specifier.
1203 return false;
1204
1205 case TemplateName::QualifiedTemplate:
1206 // FIXME: Visit nested-name-specifier.
1207 return Visit(MakeCursorTemplateRef(
1208 Name.getAsQualifiedTemplateName()->getDecl(),
1209 Loc, TU));
1210 }
1211
1212 return false;
1213}
1214
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001215bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1216 switch (TAL.getArgument().getKind()) {
1217 case TemplateArgument::Null:
1218 case TemplateArgument::Integral:
1219 return false;
1220
1221 case TemplateArgument::Pack:
1222 // FIXME: Implement when variadic templates come along.
1223 return false;
1224
1225 case TemplateArgument::Type:
1226 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1227 return Visit(TSInfo->getTypeLoc());
1228 return false;
1229
1230 case TemplateArgument::Declaration:
1231 if (Expr *E = TAL.getSourceDeclExpression())
1232 return Visit(MakeCXCursor(E, StmtParent, TU));
1233 return false;
1234
1235 case TemplateArgument::Expression:
1236 if (Expr *E = TAL.getSourceExpression())
1237 return Visit(MakeCXCursor(E, StmtParent, TU));
1238 return false;
1239
1240 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001241 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1242 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001243 }
1244
1245 return false;
1246}
1247
Ted Kremeneka0536d82010-05-07 01:04:29 +00001248bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1249 return VisitDeclContext(D);
1250}
1251
Douglas Gregor01829d32010-08-31 14:41:23 +00001252bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1253 return Visit(TL.getUnqualifiedLoc());
1254}
1255
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001256bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001257 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001258
1259 // Some builtin types (such as Objective-C's "id", "sel", and
1260 // "Class") have associated declarations. Create cursors for those.
1261 QualType VisitType;
1262 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001263 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001264 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001265 case BuiltinType::Char_U:
1266 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267 case BuiltinType::Char16:
1268 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001269 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270 case BuiltinType::UInt:
1271 case BuiltinType::ULong:
1272 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001273 case BuiltinType::UInt128:
1274 case BuiltinType::Char_S:
1275 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277 case BuiltinType::Short:
1278 case BuiltinType::Int:
1279 case BuiltinType::Long:
1280 case BuiltinType::LongLong:
1281 case BuiltinType::Int128:
1282 case BuiltinType::Float:
1283 case BuiltinType::Double:
1284 case BuiltinType::LongDouble:
1285 case BuiltinType::NullPtr:
1286 case BuiltinType::Overload:
1287 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001288 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001289
1290 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001292
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001293 case BuiltinType::ObjCId:
1294 VisitType = Context.getObjCIdType();
1295 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001296
1297 case BuiltinType::ObjCClass:
1298 VisitType = Context.getObjCClassType();
1299 break;
1300
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001301 case BuiltinType::ObjCSel:
1302 VisitType = Context.getObjCSelType();
1303 break;
1304 }
1305
1306 if (!VisitType.isNull()) {
1307 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001308 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001309 TU));
1310 }
1311
1312 return false;
1313}
1314
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001315bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1316 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1317}
1318
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001319bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1320 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1321}
1322
1323bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1324 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1325}
1326
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001327bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001328 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001329 // no context information with which we can match up the depth/index in the
1330 // type to the appropriate
1331 return false;
1332}
1333
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1335 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1336 return true;
1337
John McCallc12c5bb2010-05-15 11:32:37 +00001338 return false;
1339}
1340
1341bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1342 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1343 return true;
1344
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001345 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1346 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1347 TU)))
1348 return true;
1349 }
1350
1351 return false;
1352}
1353
1354bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001355 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001356}
1357
1358bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1359 return Visit(TL.getPointeeLoc());
1360}
1361
1362bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1363 return Visit(TL.getPointeeLoc());
1364}
1365
1366bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1367 return Visit(TL.getPointeeLoc());
1368}
1369
1370bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001371 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001372}
1373
1374bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001375 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376}
1377
Douglas Gregor01829d32010-08-31 14:41:23 +00001378bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1379 bool SkipResultType) {
1380 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381 return true;
1382
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001383 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001384 if (Decl *D = TL.getArg(I))
1385 if (Visit(MakeCXCursor(D, TU)))
1386 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387
1388 return false;
1389}
1390
1391bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1392 if (Visit(TL.getElementLoc()))
1393 return true;
1394
1395 if (Expr *Size = TL.getSizeExpr())
1396 return Visit(MakeCXCursor(Size, StmtParent, TU));
1397
1398 return false;
1399}
1400
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001401bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1402 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001403 // Visit the template name.
1404 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1405 TL.getTemplateNameLoc()))
1406 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001407
1408 // Visit the template arguments.
1409 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1410 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1411 return true;
1412
1413 return false;
1414}
1415
Douglas Gregor2332c112010-01-21 20:48:56 +00001416bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1417 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1418}
1419
1420bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1421 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1422 return Visit(TSInfo->getTypeLoc());
1423
1424 return false;
1425}
1426
Ted Kremenek3064ef92010-08-27 21:34:58 +00001427bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1428 if (D->isDefinition()) {
1429 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1430 E = D->bases_end(); I != E; ++I) {
1431 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1432 return true;
1433 }
1434 }
1435
1436 return VisitTagDecl(D);
1437}
1438
Ted Kremenek09dfa372010-02-18 05:46:33 +00001439bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001440 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1441 i != e; ++i)
1442 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001443 return true;
1444
1445 return false;
1446}
1447
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001448//===----------------------------------------------------------------------===//
1449// Data-recursive visitor methods.
1450//===----------------------------------------------------------------------===//
1451
Ted Kremenek28a71942010-11-13 00:36:47 +00001452namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001453#define DEF_JOB(NAME, DATA, KIND)\
1454class NAME : public VisitorJob {\
1455public:\
1456 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1457 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001458 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001459};
1460
1461DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1462DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001463DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001464DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001465DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1466 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001467#undef DEF_JOB
1468
1469class DeclVisit : public VisitorJob {
1470public:
1471 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1472 VisitorJob(parent, VisitorJob::DeclVisitKind,
1473 d, isFirst ? (void*) 1 : (void*) 0) {}
1474 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001475 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001476 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001477 Decl *get() const { return static_cast<Decl*>(data[0]); }
1478 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001479};
Ted Kremenek035dc412010-11-13 00:36:50 +00001480class TypeLocVisit : public VisitorJob {
1481public:
1482 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1483 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1484 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1485
1486 static bool classof(const VisitorJob *VJ) {
1487 return VJ->getKind() == TypeLocVisitKind;
1488 }
1489
Ted Kremenek82f3c502010-11-15 22:23:26 +00001490 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001491 QualType T = QualType::getFromOpaquePtr(data[0]);
1492 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001493 }
1494};
1495
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001496class LabelRefVisit : public VisitorJob {
1497public:
1498 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1499 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1500 (void*) labelLoc.getRawEncoding()) {}
1501
1502 static bool classof(const VisitorJob *VJ) {
1503 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1504 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001505 LabelStmt *get() const { return static_cast<LabelStmt*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001506 SourceLocation getLoc() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001507 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); }
1508};
1509class NestedNameSpecifierVisit : public VisitorJob {
1510public:
1511 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1512 CXCursor parent)
1513 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
1514 NS, (void*) R.getBegin().getRawEncoding(),
1515 (void*) R.getEnd().getRawEncoding()) {}
1516 static bool classof(const VisitorJob *VJ) {
1517 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1518 }
1519 NestedNameSpecifier *get() const {
1520 return static_cast<NestedNameSpecifier*>(data[0]);
1521 }
1522 SourceRange getSourceRange() const {
1523 SourceLocation A =
1524 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1525 SourceLocation B =
1526 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1527 return SourceRange(A, B);
1528 }
1529};
1530class DeclarationNameInfoVisit : public VisitorJob {
1531public:
1532 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1533 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1534 static bool classof(const VisitorJob *VJ) {
1535 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1536 }
1537 DeclarationNameInfo get() const {
1538 Stmt *S = static_cast<Stmt*>(data[0]);
1539 switch (S->getStmtClass()) {
1540 default:
1541 llvm_unreachable("Unhandled Stmt");
1542 case Stmt::CXXDependentScopeMemberExprClass:
1543 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1544 case Stmt::DependentScopeDeclRefExprClass:
1545 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1546 }
1547 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001548};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001549class MemberRefVisit : public VisitorJob {
1550public:
1551 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1552 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1553 (void*) L.getRawEncoding()) {}
1554 static bool classof(const VisitorJob *VJ) {
1555 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1556 }
1557 FieldDecl *get() const {
1558 return static_cast<FieldDecl*>(data[0]);
1559 }
1560 SourceLocation getLoc() const {
1561 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1562 }
1563};
Ted Kremenek28a71942010-11-13 00:36:47 +00001564class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1565 VisitorWorkList &WL;
1566 CXCursor Parent;
1567public:
1568 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1569 : WL(wl), Parent(parent) {}
1570
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001571 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001572 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001573 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001574 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001575 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001576 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001577 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001578 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001579 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001580 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001581 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001582 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001583 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001584 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001585 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001586 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001587 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001588 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001589 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1590 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001591 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001592 void VisitIfStmt(IfStmt *If);
1593 void VisitInitListExpr(InitListExpr *IE);
1594 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001595 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001596 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001597 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1598 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001599 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001600 void VisitStmt(Stmt *S);
1601 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001602 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001603 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001604 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001605 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001606 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001607
1608private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001609 void AddDeclarationNameInfo(Stmt *S);
1610 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001611 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001612 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001613 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001614 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001615 void AddTypeLoc(TypeSourceInfo *TI);
1616 void EnqueueChildren(Stmt *S);
1617};
1618} // end anonyous namespace
1619
Ted Kremenekf64d8032010-11-18 00:02:32 +00001620void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1621 // 'S' should always be non-null, since it comes from the
1622 // statement we are visiting.
1623 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1624}
1625void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1626 SourceRange R) {
1627 if (N)
1628 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1629}
Ted Kremenek28a71942010-11-13 00:36:47 +00001630void EnqueueVisitor::AddStmt(Stmt *S) {
1631 if (S)
1632 WL.push_back(StmtVisit(S, Parent));
1633}
Ted Kremenek035dc412010-11-13 00:36:50 +00001634void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001635 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001636 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001637}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001638void EnqueueVisitor::
1639 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1640 if (A)
1641 WL.push_back(ExplicitTemplateArgsVisit(
1642 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1643}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001644void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1645 if (D)
1646 WL.push_back(MemberRefVisit(D, L, Parent));
1647}
Ted Kremenek28a71942010-11-13 00:36:47 +00001648void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1649 if (TI)
1650 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1651 }
1652void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001653 unsigned size = WL.size();
1654 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1655 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001656 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001657 }
1658 if (size == WL.size())
1659 return;
1660 // Now reverse the entries we just added. This will match the DFS
1661 // ordering performed by the worklist.
1662 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1663 std::reverse(I, E);
1664}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001665void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1666 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1667}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001668void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1669 AddDecl(B->getBlockDecl());
1670}
Ted Kremenek28a71942010-11-13 00:36:47 +00001671void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1672 EnqueueChildren(E);
1673 AddTypeLoc(E->getTypeSourceInfo());
1674}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001675void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1676 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1677 E = S->body_rend(); I != E; ++I) {
1678 AddStmt(*I);
1679 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001680}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001681void EnqueueVisitor::
1682VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1683 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1684 AddDeclarationNameInfo(E);
1685 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1686 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1687 if (!E->isImplicitAccess())
1688 AddStmt(E->getBase());
1689}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001690void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1691 // Enqueue the initializer or constructor arguments.
1692 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1693 AddStmt(E->getConstructorArg(I-1));
1694 // Enqueue the array size, if any.
1695 AddStmt(E->getArraySize());
1696 // Enqueue the allocated type.
1697 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1698 // Enqueue the placement arguments.
1699 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1700 AddStmt(E->getPlacementArg(I-1));
1701}
Ted Kremenek28a71942010-11-13 00:36:47 +00001702void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001703 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1704 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001705 AddStmt(CE->getCallee());
1706 AddStmt(CE->getArg(0));
1707}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001708void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1709 // Visit the name of the type being destroyed.
1710 AddTypeLoc(E->getDestroyedTypeInfo());
1711 // Visit the scope type that looks disturbingly like the nested-name-specifier
1712 // but isn't.
1713 AddTypeLoc(E->getScopeTypeInfo());
1714 // Visit the nested-name-specifier.
1715 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1716 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1717 // Visit base expression.
1718 AddStmt(E->getBase());
1719}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001720void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1721 AddTypeLoc(E->getTypeSourceInfo());
1722}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001723void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1724 EnqueueChildren(E);
1725 AddTypeLoc(E->getTypeSourceInfo());
1726}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001727void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1728 EnqueueChildren(E);
1729 if (E->isTypeOperand())
1730 AddTypeLoc(E->getTypeOperandSourceInfo());
1731}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001732
1733void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1734 *E) {
1735 EnqueueChildren(E);
1736 AddTypeLoc(E->getTypeSourceInfo());
1737}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001738void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1739 EnqueueChildren(E);
1740 if (E->isTypeOperand())
1741 AddTypeLoc(E->getTypeOperandSourceInfo());
1742}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001743void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001744 if (DR->hasExplicitTemplateArgs()) {
1745 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1746 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001747 WL.push_back(DeclRefExprParts(DR, Parent));
1748}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001749void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1750 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1751 AddDeclarationNameInfo(E);
1752 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1753 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1754}
Ted Kremenek035dc412010-11-13 00:36:50 +00001755void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1756 unsigned size = WL.size();
1757 bool isFirst = true;
1758 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1759 D != DEnd; ++D) {
1760 AddDecl(*D, isFirst);
1761 isFirst = false;
1762 }
1763 if (size == WL.size())
1764 return;
1765 // Now reverse the entries we just added. This will match the DFS
1766 // ordering performed by the worklist.
1767 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1768 std::reverse(I, E);
1769}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001770void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1771 AddStmt(E->getInit());
1772 typedef DesignatedInitExpr::Designator Designator;
1773 for (DesignatedInitExpr::reverse_designators_iterator
1774 D = E->designators_rbegin(), DEnd = E->designators_rend();
1775 D != DEnd; ++D) {
1776 if (D->isFieldDesignator()) {
1777 if (FieldDecl *Field = D->getField())
1778 AddMemberRef(Field, D->getFieldLoc());
1779 continue;
1780 }
1781 if (D->isArrayDesignator()) {
1782 AddStmt(E->getArrayIndex(*D));
1783 continue;
1784 }
1785 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1786 AddStmt(E->getArrayRangeEnd(*D));
1787 AddStmt(E->getArrayRangeStart(*D));
1788 }
1789}
Ted Kremenek28a71942010-11-13 00:36:47 +00001790void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1791 EnqueueChildren(E);
1792 AddTypeLoc(E->getTypeInfoAsWritten());
1793}
1794void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1795 AddStmt(FS->getBody());
1796 AddStmt(FS->getInc());
1797 AddStmt(FS->getCond());
1798 AddDecl(FS->getConditionVariable());
1799 AddStmt(FS->getInit());
1800}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001801void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1802 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1803}
Ted Kremenek28a71942010-11-13 00:36:47 +00001804void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1805 AddStmt(If->getElse());
1806 AddStmt(If->getThen());
1807 AddStmt(If->getCond());
1808 AddDecl(If->getConditionVariable());
1809}
1810void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1811 // We care about the syntactic form of the initializer list, only.
1812 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1813 IE = Syntactic;
1814 EnqueueChildren(IE);
1815}
1816void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001817 WL.push_back(MemberExprParts(M, Parent));
1818
1819 // If the base of the member access expression is an implicit 'this', don't
1820 // visit it.
1821 // FIXME: If we ever want to show these implicit accesses, this will be
1822 // unfortunate. However, clang_getCursor() relies on this behavior.
1823 if (CXXThisExpr *This
1824 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1825 if (This->isImplicit())
1826 return;
1827
Ted Kremenek28a71942010-11-13 00:36:47 +00001828 AddStmt(M->getBase());
1829}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001830void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1831 AddTypeLoc(E->getEncodedTypeSourceInfo());
1832}
Ted Kremenek28a71942010-11-13 00:36:47 +00001833void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1834 EnqueueChildren(M);
1835 AddTypeLoc(M->getClassReceiverTypeInfo());
1836}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001837void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1838 // Visit the components of the offsetof expression.
1839 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1840 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1841 const OffsetOfNode &Node = E->getComponent(I-1);
1842 switch (Node.getKind()) {
1843 case OffsetOfNode::Array:
1844 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1845 break;
1846 case OffsetOfNode::Field:
1847 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1848 break;
1849 case OffsetOfNode::Identifier:
1850 case OffsetOfNode::Base:
1851 continue;
1852 }
1853 }
1854 // Visit the type into which we're computing the offset.
1855 AddTypeLoc(E->getTypeSourceInfo());
1856}
Ted Kremenek28a71942010-11-13 00:36:47 +00001857void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001858 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001859 WL.push_back(OverloadExprParts(E, Parent));
1860}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001861void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1862 EnqueueChildren(E);
1863 if (E->isArgumentType())
1864 AddTypeLoc(E->getArgumentTypeInfo());
1865}
Ted Kremenek28a71942010-11-13 00:36:47 +00001866void EnqueueVisitor::VisitStmt(Stmt *S) {
1867 EnqueueChildren(S);
1868}
1869void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1870 AddStmt(S->getBody());
1871 AddStmt(S->getCond());
1872 AddDecl(S->getConditionVariable());
1873}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001874void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1875 AddTypeLoc(E->getArgTInfo2());
1876 AddTypeLoc(E->getArgTInfo1());
1877}
1878
Ted Kremenek28a71942010-11-13 00:36:47 +00001879void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1880 AddStmt(W->getBody());
1881 AddStmt(W->getCond());
1882 AddDecl(W->getConditionVariable());
1883}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001884void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1885 AddTypeLoc(E->getQueriedTypeSourceInfo());
1886}
Ted Kremenek28a71942010-11-13 00:36:47 +00001887void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1888 VisitOverloadExpr(U);
1889 if (!U->isImplicitAccess())
1890 AddStmt(U->getBase());
1891}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001892void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1893 AddStmt(E->getSubExpr());
1894 AddTypeLoc(E->getWrittenTypeInfo());
1895}
Ted Kremenek60458782010-11-12 21:34:16 +00001896
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001897void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001898 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001899}
1900
1901bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1902 if (RegionOfInterest.isValid()) {
1903 SourceRange Range = getRawCursorExtent(C);
1904 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1905 return false;
1906 }
1907 return true;
1908}
1909
1910bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1911 while (!WL.empty()) {
1912 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001913 VisitorJob LI = WL.back();
1914 WL.pop_back();
1915
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001916 // Set the Parent field, then back to its old value once we're done.
1917 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1918
1919 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001920 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001921 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001922 if (!D)
1923 continue;
1924
1925 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001926 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001927 return true;
1928
1929 continue;
1930 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001931 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1932 const ExplicitTemplateArgumentList *ArgList =
1933 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1934 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1935 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1936 Arg != ArgEnd; ++Arg) {
1937 if (VisitTemplateArgumentLoc(*Arg))
1938 return true;
1939 }
1940 continue;
1941 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001942 case VisitorJob::TypeLocVisitKind: {
1943 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001944 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001945 return true;
1946 continue;
1947 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001948 case VisitorJob::LabelRefVisitKind: {
1949 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1950 if (Visit(MakeCursorLabelRef(LS,
1951 cast<LabelRefVisit>(&LI)->getLoc(),
1952 TU)))
1953 return true;
1954 continue;
1955 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001956 case VisitorJob::NestedNameSpecifierVisitKind: {
1957 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
1958 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
1959 return true;
1960 continue;
1961 }
1962 case VisitorJob::DeclarationNameInfoVisitKind: {
1963 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
1964 ->get()))
1965 return true;
1966 continue;
1967 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00001968 case VisitorJob::MemberRefVisitKind: {
1969 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
1970 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
1971 return true;
1972 continue;
1973 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001974 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001975 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001976 if (!S)
1977 continue;
1978
Ted Kremenekf1107452010-11-12 18:26:56 +00001979 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001980 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001981 if (!IsInRegionOfInterest(Cursor))
1982 continue;
1983 switch (Visitor(Cursor, Parent, ClientData)) {
1984 case CXChildVisit_Break: return true;
1985 case CXChildVisit_Continue: break;
1986 case CXChildVisit_Recurse:
1987 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00001988 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001989 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001990 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001991 }
1992 case VisitorJob::MemberExprPartsKind: {
1993 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001994 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001995
1996 // Visit the nested-name-specifier
1997 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1998 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1999 return true;
2000
2001 // Visit the declaration name.
2002 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2003 return true;
2004
2005 // Visit the explicitly-specified template arguments, if any.
2006 if (M->hasExplicitTemplateArgs()) {
2007 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2008 *ArgEnd = Arg + M->getNumTemplateArgs();
2009 Arg != ArgEnd; ++Arg) {
2010 if (VisitTemplateArgumentLoc(*Arg))
2011 return true;
2012 }
2013 }
2014 continue;
2015 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002016 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002017 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002018 // Visit nested-name-specifier, if present.
2019 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2020 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2021 return true;
2022 // Visit declaration name.
2023 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2024 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002025 continue;
2026 }
Ted Kremenek60458782010-11-12 21:34:16 +00002027 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002028 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002029 // Visit the nested-name-specifier.
2030 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2031 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2032 return true;
2033 // Visit the declaration name.
2034 if (VisitDeclarationNameInfo(O->getNameInfo()))
2035 return true;
2036 // Visit the overloaded declaration reference.
2037 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2038 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002039 continue;
2040 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002041 }
2042 }
2043 return false;
2044}
2045
Ted Kremenekcdba6592010-11-18 00:42:18 +00002046bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002047 VisitorWorkList *WL = 0;
2048 if (!WorkListFreeList.empty()) {
2049 WL = WorkListFreeList.back();
2050 WL->clear();
2051 WorkListFreeList.pop_back();
2052 }
2053 else {
2054 WL = new VisitorWorkList();
2055 WorkListCache.push_back(WL);
2056 }
2057 EnqueueWorkList(*WL, S);
2058 bool result = RunVisitorWorkList(*WL);
2059 WorkListFreeList.push_back(WL);
2060 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002061}
2062
2063//===----------------------------------------------------------------------===//
2064// Misc. API hooks.
2065//===----------------------------------------------------------------------===//
2066
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002067static llvm::sys::Mutex EnableMultithreadingMutex;
2068static bool EnabledMultithreading;
2069
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002070extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002071CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2072 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002073 // Disable pretty stack trace functionality, which will otherwise be a very
2074 // poor citizen of the world and set up all sorts of signal handlers.
2075 llvm::DisablePrettyStackTrace = true;
2076
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002077 // We use crash recovery to make some of our APIs more reliable, implicitly
2078 // enable it.
2079 llvm::CrashRecoveryContext::Enable();
2080
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002081 // Enable support for multithreading in LLVM.
2082 {
2083 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2084 if (!EnabledMultithreading) {
2085 llvm::llvm_start_multithreaded();
2086 EnabledMultithreading = true;
2087 }
2088 }
2089
Douglas Gregora030b7c2010-01-22 20:35:53 +00002090 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002091 if (excludeDeclarationsFromPCH)
2092 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002093 if (displayDiagnostics)
2094 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002095 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002096}
2097
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002098void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002099 if (CIdx)
2100 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002101}
2102
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002103CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002104 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002105 if (!CIdx)
2106 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002107
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002108 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002109 FileSystemOptions FileSystemOpts;
2110 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002111
Douglas Gregor28019772010-04-05 23:52:57 +00002112 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002113 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002114 CXXIdx->getOnlyLocalDecls(),
2115 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002116 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002117}
2118
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002119unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002120 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002121 CXTranslationUnit_CacheCompletionResults |
2122 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002123}
2124
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002125CXTranslationUnit
2126clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2127 const char *source_filename,
2128 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002129 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002130 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002131 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002132 return clang_parseTranslationUnit(CIdx, source_filename,
2133 command_line_args, num_command_line_args,
2134 unsaved_files, num_unsaved_files,
2135 CXTranslationUnit_DetailedPreprocessingRecord);
2136}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002137
2138struct ParseTranslationUnitInfo {
2139 CXIndex CIdx;
2140 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002141 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002142 int num_command_line_args;
2143 struct CXUnsavedFile *unsaved_files;
2144 unsigned num_unsaved_files;
2145 unsigned options;
2146 CXTranslationUnit result;
2147};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002148static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002149 ParseTranslationUnitInfo *PTUI =
2150 static_cast<ParseTranslationUnitInfo*>(UserData);
2151 CXIndex CIdx = PTUI->CIdx;
2152 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002153 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002154 int num_command_line_args = PTUI->num_command_line_args;
2155 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2156 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2157 unsigned options = PTUI->options;
2158 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002159
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002160 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002161 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002162
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002163 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2164
Douglas Gregor44c181a2010-07-23 00:33:23 +00002165 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002166 bool CompleteTranslationUnit
2167 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002168 bool CacheCodeCompetionResults
2169 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002170 bool CXXPrecompilePreamble
2171 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2172 bool CXXChainedPCH
2173 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002174
Douglas Gregor5352ac02010-01-28 00:27:43 +00002175 // Configure the diagnostics.
2176 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002177 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2178 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179
Douglas Gregor4db64a42010-01-23 00:14:00 +00002180 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2181 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002182 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002183 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002184 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002185 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2186 Buffer));
2187 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002188
Douglas Gregorb10daed2010-10-11 16:52:23 +00002189 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002190
Ted Kremenek139ba862009-10-22 00:03:57 +00002191 // The 'source_filename' argument is optional. If the caller does not
2192 // specify it then it is assumed that the source file is specified
2193 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002194 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002195 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002196
2197 // Since the Clang C library is primarily used by batch tools dealing with
2198 // (often very broken) source code, where spell-checking can have a
2199 // significant negative impact on performance (particularly when
2200 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002201 // Only do this if we haven't found a spell-checking-related argument.
2202 bool FoundSpellCheckingArgument = false;
2203 for (int I = 0; I != num_command_line_args; ++I) {
2204 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2205 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2206 FoundSpellCheckingArgument = true;
2207 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002208 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002209 }
2210 if (!FoundSpellCheckingArgument)
2211 Args.push_back("-fno-spell-checking");
2212
2213 Args.insert(Args.end(), command_line_args,
2214 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002215
Douglas Gregor44c181a2010-07-23 00:33:23 +00002216 // Do we need the detailed preprocessing record?
2217 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 Args.push_back("-Xclang");
2219 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002220 }
2221
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002222 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002223 llvm::OwningPtr<ASTUnit> Unit(
2224 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2225 Diags,
2226 CXXIdx->getClangResourcesPath(),
2227 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002228 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002229 RemappedFiles.data(),
2230 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002231 PrecompilePreamble,
2232 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002233 CacheCodeCompetionResults,
2234 CXXPrecompilePreamble,
2235 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002236
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002237 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002238 // Make sure to check that 'Unit' is non-NULL.
2239 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2240 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2241 DEnd = Unit->stored_diag_end();
2242 D != DEnd; ++D) {
2243 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2244 CXString Msg = clang_formatDiagnostic(&Diag,
2245 clang_defaultDiagnosticDisplayOptions());
2246 fprintf(stderr, "%s\n", clang_getCString(Msg));
2247 clang_disposeString(Msg);
2248 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002249#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002250 // On Windows, force a flush, since there may be multiple copies of
2251 // stderr and stdout in the file system, all with different buffers
2252 // but writing to the same device.
2253 fflush(stderr);
2254#endif
2255 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002256 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002257
Ted Kremeneka60ed472010-11-16 08:15:36 +00002258 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002259}
2260CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2261 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002262 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002263 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002264 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002265 unsigned num_unsaved_files,
2266 unsigned options) {
2267 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002268 num_command_line_args, unsaved_files,
2269 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002270 llvm::CrashRecoveryContext CRC;
2271
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002272 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002273 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2274 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2275 fprintf(stderr, " 'command_line_args' : [");
2276 for (int i = 0; i != num_command_line_args; ++i) {
2277 if (i)
2278 fprintf(stderr, ", ");
2279 fprintf(stderr, "'%s'", command_line_args[i]);
2280 }
2281 fprintf(stderr, "],\n");
2282 fprintf(stderr, " 'unsaved_files' : [");
2283 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2284 if (i)
2285 fprintf(stderr, ", ");
2286 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2287 unsaved_files[i].Length);
2288 }
2289 fprintf(stderr, "],\n");
2290 fprintf(stderr, " 'options' : %d,\n", options);
2291 fprintf(stderr, "}\n");
2292
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002293 return 0;
2294 }
2295
2296 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002297}
2298
Douglas Gregor19998442010-08-13 15:35:05 +00002299unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2300 return CXSaveTranslationUnit_None;
2301}
2302
2303int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2304 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002305 if (!TU)
2306 return 1;
2307
Ted Kremeneka60ed472010-11-16 08:15:36 +00002308 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002309}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002310
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002311void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002312 if (CTUnit) {
2313 // If the translation unit has been marked as unsafe to free, just discard
2314 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002315 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002316 return;
2317
Ted Kremeneka60ed472010-11-16 08:15:36 +00002318 delete static_cast<ASTUnit *>(CTUnit->TUData);
2319 disposeCXStringPool(CTUnit->StringPool);
2320 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002321 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002322}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002323
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002324unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2325 return CXReparse_None;
2326}
2327
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002328struct ReparseTranslationUnitInfo {
2329 CXTranslationUnit TU;
2330 unsigned num_unsaved_files;
2331 struct CXUnsavedFile *unsaved_files;
2332 unsigned options;
2333 int result;
2334};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002335
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002336static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002337 ReparseTranslationUnitInfo *RTUI =
2338 static_cast<ReparseTranslationUnitInfo*>(UserData);
2339 CXTranslationUnit TU = RTUI->TU;
2340 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2341 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2342 unsigned options = RTUI->options;
2343 (void) options;
2344 RTUI->result = 1;
2345
Douglas Gregorabc563f2010-07-19 21:46:24 +00002346 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002347 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002348
Ted Kremeneka60ed472010-11-16 08:15:36 +00002349 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002350 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002351
2352 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2353 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2354 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2355 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002356 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002357 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2358 Buffer));
2359 }
2360
Douglas Gregor593b0c12010-09-23 18:47:53 +00002361 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2362 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002363}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002364
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002365int clang_reparseTranslationUnit(CXTranslationUnit TU,
2366 unsigned num_unsaved_files,
2367 struct CXUnsavedFile *unsaved_files,
2368 unsigned options) {
2369 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2370 options, 0 };
2371 llvm::CrashRecoveryContext CRC;
2372
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002373 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002374 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002375 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002376 return 1;
2377 }
2378
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002379
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002380 return RTUI.result;
2381}
2382
Douglas Gregordf95a132010-08-09 20:45:32 +00002383
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002384CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002385 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002386 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002387
Ted Kremeneka60ed472010-11-16 08:15:36 +00002388 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002389 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002390}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002391
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002392CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002393 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002394 return Result;
2395}
2396
Ted Kremenekfb480492010-01-13 21:46:36 +00002397} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002398
Ted Kremenekfb480492010-01-13 21:46:36 +00002399//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002400// CXSourceLocation and CXSourceRange Operations.
2401//===----------------------------------------------------------------------===//
2402
Douglas Gregorb9790342010-01-22 21:44:22 +00002403extern "C" {
2404CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002405 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002406 return Result;
2407}
2408
2409unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002410 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2411 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2412 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002413}
2414
2415CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2416 CXFile file,
2417 unsigned line,
2418 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002419 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002420 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002421
Ted Kremeneka60ed472010-11-16 08:15:36 +00002422 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002423 SourceLocation SLoc
2424 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002426 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002427 if (SLoc.isInvalid()) return clang_getNullLocation();
2428
2429 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2430}
2431
2432CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2433 CXFile file,
2434 unsigned offset) {
2435 if (!tu || !file)
2436 return clang_getNullLocation();
2437
Ted Kremeneka60ed472010-11-16 08:15:36 +00002438 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002439 SourceLocation Start
2440 = CXXUnit->getSourceManager().getLocation(
2441 static_cast<const FileEntry *>(file),
2442 1, 1);
2443 if (Start.isInvalid()) return clang_getNullLocation();
2444
2445 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2446
2447 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002448
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002449 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002450}
2451
Douglas Gregor5352ac02010-01-28 00:27:43 +00002452CXSourceRange clang_getNullRange() {
2453 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2454 return Result;
2455}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002456
Douglas Gregor5352ac02010-01-28 00:27:43 +00002457CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2458 if (begin.ptr_data[0] != end.ptr_data[0] ||
2459 begin.ptr_data[1] != end.ptr_data[1])
2460 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002461
2462 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002463 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002464 return Result;
2465}
2466
Douglas Gregor46766dc2010-01-26 19:19:08 +00002467void clang_getInstantiationLocation(CXSourceLocation location,
2468 CXFile *file,
2469 unsigned *line,
2470 unsigned *column,
2471 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002472 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2473
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002474 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002475 if (file)
2476 *file = 0;
2477 if (line)
2478 *line = 0;
2479 if (column)
2480 *column = 0;
2481 if (offset)
2482 *offset = 0;
2483 return;
2484 }
2485
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002486 const SourceManager &SM =
2487 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002488 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002489
2490 if (file)
2491 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2492 if (line)
2493 *line = SM.getInstantiationLineNumber(InstLoc);
2494 if (column)
2495 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002496 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002497 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002498}
2499
Douglas Gregora9b06d42010-11-09 06:24:54 +00002500void clang_getSpellingLocation(CXSourceLocation location,
2501 CXFile *file,
2502 unsigned *line,
2503 unsigned *column,
2504 unsigned *offset) {
2505 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2506
2507 if (!location.ptr_data[0] || Loc.isInvalid()) {
2508 if (file)
2509 *file = 0;
2510 if (line)
2511 *line = 0;
2512 if (column)
2513 *column = 0;
2514 if (offset)
2515 *offset = 0;
2516 return;
2517 }
2518
2519 const SourceManager &SM =
2520 *static_cast<const SourceManager*>(location.ptr_data[0]);
2521 SourceLocation SpellLoc = Loc;
2522 if (SpellLoc.isMacroID()) {
2523 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2524 if (SimpleSpellingLoc.isFileID() &&
2525 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2526 SpellLoc = SimpleSpellingLoc;
2527 else
2528 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2529 }
2530
2531 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2532 FileID FID = LocInfo.first;
2533 unsigned FileOffset = LocInfo.second;
2534
2535 if (file)
2536 *file = (void *)SM.getFileEntryForID(FID);
2537 if (line)
2538 *line = SM.getLineNumber(FID, FileOffset);
2539 if (column)
2540 *column = SM.getColumnNumber(FID, FileOffset);
2541 if (offset)
2542 *offset = FileOffset;
2543}
2544
Douglas Gregor1db19de2010-01-19 21:36:55 +00002545CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002546 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002547 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002548 return Result;
2549}
2550
2551CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002552 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002553 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002554 return Result;
2555}
2556
Douglas Gregorb9790342010-01-22 21:44:22 +00002557} // end: extern "C"
2558
Douglas Gregor1db19de2010-01-19 21:36:55 +00002559//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002560// CXFile Operations.
2561//===----------------------------------------------------------------------===//
2562
2563extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002564CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002565 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002566 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002567
Steve Naroff88145032009-10-27 14:35:18 +00002568 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002569 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002570}
2571
2572time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002573 if (!SFile)
2574 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002575
Steve Naroff88145032009-10-27 14:35:18 +00002576 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2577 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002578}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002579
Douglas Gregorb9790342010-01-22 21:44:22 +00002580CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2581 if (!tu)
2582 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002583
Ted Kremeneka60ed472010-11-16 08:15:36 +00002584 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Douglas Gregorb9790342010-01-22 21:44:22 +00002586 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner65382272010-11-21 09:55:08 +00002587 const FileEntry *File = FMgr.getFile(file_name, CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002588 return const_cast<FileEntry *>(File);
2589}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590
Ted Kremenekfb480492010-01-13 21:46:36 +00002591} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002592
Ted Kremenekfb480492010-01-13 21:46:36 +00002593//===----------------------------------------------------------------------===//
2594// CXCursor Operations.
2595//===----------------------------------------------------------------------===//
2596
Ted Kremenekfb480492010-01-13 21:46:36 +00002597static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002598 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2599 return getDeclFromExpr(CE->getSubExpr());
2600
Ted Kremenekfb480492010-01-13 21:46:36 +00002601 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2602 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002603 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2604 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002605 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2606 return ME->getMemberDecl();
2607 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2608 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002609 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2610 return PRE->getProperty();
2611
Ted Kremenekfb480492010-01-13 21:46:36 +00002612 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2613 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002614 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2615 if (!CE->isElidable())
2616 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002617 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2618 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002619
Douglas Gregordb1314e2010-10-01 21:11:22 +00002620 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2621 return PE->getProtocol();
2622
Ted Kremenekfb480492010-01-13 21:46:36 +00002623 return 0;
2624}
2625
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002626static SourceLocation getLocationFromExpr(Expr *E) {
2627 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2628 return /*FIXME:*/Msg->getLeftLoc();
2629 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2630 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002631 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2632 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002633 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2634 return Member->getMemberLoc();
2635 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2636 return Ivar->getLocation();
2637 return E->getLocStart();
2638}
2639
Ted Kremenekfb480492010-01-13 21:46:36 +00002640extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002641
2642unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002643 CXCursorVisitor visitor,
2644 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002645 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2646 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002647 return CursorVis.VisitChildren(parent);
2648}
2649
David Chisnall3387c652010-11-03 14:12:26 +00002650#ifndef __has_feature
2651#define __has_feature(x) 0
2652#endif
2653#if __has_feature(blocks)
2654typedef enum CXChildVisitResult
2655 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2656
2657static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2658 CXClientData client_data) {
2659 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2660 return block(cursor, parent);
2661}
2662#else
2663// If we are compiled with a compiler that doesn't have native blocks support,
2664// define and call the block manually, so the
2665typedef struct _CXChildVisitResult
2666{
2667 void *isa;
2668 int flags;
2669 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002670 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2671 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002672} *CXCursorVisitorBlock;
2673
2674static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2675 CXClientData client_data) {
2676 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2677 return block->invoke(block, cursor, parent);
2678}
2679#endif
2680
2681
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002682unsigned clang_visitChildrenWithBlock(CXCursor parent,
2683 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002684 return clang_visitChildren(parent, visitWithBlock, block);
2685}
2686
Douglas Gregor78205d42010-01-20 21:45:58 +00002687static CXString getDeclSpelling(Decl *D) {
2688 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002689 if (!ND) {
2690 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2691 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2692 return createCXString(Property->getIdentifier()->getName());
2693
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002694 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002695 }
2696
Douglas Gregor78205d42010-01-20 21:45:58 +00002697 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002698 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002699
Douglas Gregor78205d42010-01-20 21:45:58 +00002700 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2701 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2702 // and returns different names. NamedDecl returns the class name and
2703 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002704 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002705
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002706 if (isa<UsingDirectiveDecl>(D))
2707 return createCXString("");
2708
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002709 llvm::SmallString<1024> S;
2710 llvm::raw_svector_ostream os(S);
2711 ND->printName(os);
2712
2713 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002714}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002716CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002717 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002718 return clang_getTranslationUnitSpelling(
2719 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002720
Steve Narofff334b4e2009-09-02 18:26:48 +00002721 if (clang_isReference(C.kind)) {
2722 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002723 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002724 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002725 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002726 }
2727 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002728 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002729 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002730 }
2731 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002732 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002733 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002734 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002735 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002736 case CXCursor_CXXBaseSpecifier: {
2737 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2738 return createCXString(B->getType().getAsString());
2739 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002740 case CXCursor_TypeRef: {
2741 TypeDecl *Type = getCursorTypeRef(C).first;
2742 assert(Type && "Missing type decl");
2743
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002744 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2745 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002746 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002747 case CXCursor_TemplateRef: {
2748 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002749 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002750
2751 return createCXString(Template->getNameAsString());
2752 }
Douglas Gregor69319002010-08-31 23:48:11 +00002753
2754 case CXCursor_NamespaceRef: {
2755 NamedDecl *NS = getCursorNamespaceRef(C).first;
2756 assert(NS && "Missing namespace decl");
2757
2758 return createCXString(NS->getNameAsString());
2759 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002760
Douglas Gregora67e03f2010-09-09 21:42:20 +00002761 case CXCursor_MemberRef: {
2762 FieldDecl *Field = getCursorMemberRef(C).first;
2763 assert(Field && "Missing member decl");
2764
2765 return createCXString(Field->getNameAsString());
2766 }
2767
Douglas Gregor36897b02010-09-10 00:22:18 +00002768 case CXCursor_LabelRef: {
2769 LabelStmt *Label = getCursorLabelRef(C).first;
2770 assert(Label && "Missing label");
2771
2772 return createCXString(Label->getID()->getName());
2773 }
2774
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002775 case CXCursor_OverloadedDeclRef: {
2776 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2777 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2778 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2779 return createCXString(ND->getNameAsString());
2780 return createCXString("");
2781 }
2782 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2783 return createCXString(E->getName().getAsString());
2784 OverloadedTemplateStorage *Ovl
2785 = Storage.get<OverloadedTemplateStorage*>();
2786 if (Ovl->size() == 0)
2787 return createCXString("");
2788 return createCXString((*Ovl->begin())->getNameAsString());
2789 }
2790
Daniel Dunbaracca7252009-11-30 20:42:49 +00002791 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002792 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002793 }
2794 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002795
2796 if (clang_isExpression(C.kind)) {
2797 Decl *D = getDeclFromExpr(getCursorExpr(C));
2798 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002799 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002800 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002801 }
2802
Douglas Gregor36897b02010-09-10 00:22:18 +00002803 if (clang_isStatement(C.kind)) {
2804 Stmt *S = getCursorStmt(C);
2805 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2806 return createCXString(Label->getID()->getName());
2807
2808 return createCXString("");
2809 }
2810
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002811 if (C.kind == CXCursor_MacroInstantiation)
2812 return createCXString(getCursorMacroInstantiation(C)->getName()
2813 ->getNameStart());
2814
Douglas Gregor572feb22010-03-18 18:04:21 +00002815 if (C.kind == CXCursor_MacroDefinition)
2816 return createCXString(getCursorMacroDefinition(C)->getName()
2817 ->getNameStart());
2818
Douglas Gregorecdcb882010-10-20 22:00:55 +00002819 if (C.kind == CXCursor_InclusionDirective)
2820 return createCXString(getCursorInclusionDirective(C)->getFileName());
2821
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002822 if (clang_isDeclaration(C.kind))
2823 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002824
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002825 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002826}
2827
Douglas Gregor358559d2010-10-02 22:49:11 +00002828CXString clang_getCursorDisplayName(CXCursor C) {
2829 if (!clang_isDeclaration(C.kind))
2830 return clang_getCursorSpelling(C);
2831
2832 Decl *D = getCursorDecl(C);
2833 if (!D)
2834 return createCXString("");
2835
2836 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2837 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2838 D = FunTmpl->getTemplatedDecl();
2839
2840 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2841 llvm::SmallString<64> Str;
2842 llvm::raw_svector_ostream OS(Str);
2843 OS << Function->getNameAsString();
2844 if (Function->getPrimaryTemplate())
2845 OS << "<>";
2846 OS << "(";
2847 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2848 if (I)
2849 OS << ", ";
2850 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2851 }
2852
2853 if (Function->isVariadic()) {
2854 if (Function->getNumParams())
2855 OS << ", ";
2856 OS << "...";
2857 }
2858 OS << ")";
2859 return createCXString(OS.str());
2860 }
2861
2862 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2863 llvm::SmallString<64> Str;
2864 llvm::raw_svector_ostream OS(Str);
2865 OS << ClassTemplate->getNameAsString();
2866 OS << "<";
2867 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2868 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2869 if (I)
2870 OS << ", ";
2871
2872 NamedDecl *Param = Params->getParam(I);
2873 if (Param->getIdentifier()) {
2874 OS << Param->getIdentifier()->getName();
2875 continue;
2876 }
2877
2878 // There is no parameter name, which makes this tricky. Try to come up
2879 // with something useful that isn't too long.
2880 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2881 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2882 else if (NonTypeTemplateParmDecl *NTTP
2883 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2884 OS << NTTP->getType().getAsString(Policy);
2885 else
2886 OS << "template<...> class";
2887 }
2888
2889 OS << ">";
2890 return createCXString(OS.str());
2891 }
2892
2893 if (ClassTemplateSpecializationDecl *ClassSpec
2894 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2895 // If the type was explicitly written, use that.
2896 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2897 return createCXString(TSInfo->getType().getAsString(Policy));
2898
2899 llvm::SmallString<64> Str;
2900 llvm::raw_svector_ostream OS(Str);
2901 OS << ClassSpec->getNameAsString();
2902 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002903 ClassSpec->getTemplateArgs().data(),
2904 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002905 Policy);
2906 return createCXString(OS.str());
2907 }
2908
2909 return clang_getCursorSpelling(C);
2910}
2911
Ted Kremeneke68fff62010-02-17 00:41:32 +00002912CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002913 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002914 case CXCursor_FunctionDecl:
2915 return createCXString("FunctionDecl");
2916 case CXCursor_TypedefDecl:
2917 return createCXString("TypedefDecl");
2918 case CXCursor_EnumDecl:
2919 return createCXString("EnumDecl");
2920 case CXCursor_EnumConstantDecl:
2921 return createCXString("EnumConstantDecl");
2922 case CXCursor_StructDecl:
2923 return createCXString("StructDecl");
2924 case CXCursor_UnionDecl:
2925 return createCXString("UnionDecl");
2926 case CXCursor_ClassDecl:
2927 return createCXString("ClassDecl");
2928 case CXCursor_FieldDecl:
2929 return createCXString("FieldDecl");
2930 case CXCursor_VarDecl:
2931 return createCXString("VarDecl");
2932 case CXCursor_ParmDecl:
2933 return createCXString("ParmDecl");
2934 case CXCursor_ObjCInterfaceDecl:
2935 return createCXString("ObjCInterfaceDecl");
2936 case CXCursor_ObjCCategoryDecl:
2937 return createCXString("ObjCCategoryDecl");
2938 case CXCursor_ObjCProtocolDecl:
2939 return createCXString("ObjCProtocolDecl");
2940 case CXCursor_ObjCPropertyDecl:
2941 return createCXString("ObjCPropertyDecl");
2942 case CXCursor_ObjCIvarDecl:
2943 return createCXString("ObjCIvarDecl");
2944 case CXCursor_ObjCInstanceMethodDecl:
2945 return createCXString("ObjCInstanceMethodDecl");
2946 case CXCursor_ObjCClassMethodDecl:
2947 return createCXString("ObjCClassMethodDecl");
2948 case CXCursor_ObjCImplementationDecl:
2949 return createCXString("ObjCImplementationDecl");
2950 case CXCursor_ObjCCategoryImplDecl:
2951 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002952 case CXCursor_CXXMethod:
2953 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002954 case CXCursor_UnexposedDecl:
2955 return createCXString("UnexposedDecl");
2956 case CXCursor_ObjCSuperClassRef:
2957 return createCXString("ObjCSuperClassRef");
2958 case CXCursor_ObjCProtocolRef:
2959 return createCXString("ObjCProtocolRef");
2960 case CXCursor_ObjCClassRef:
2961 return createCXString("ObjCClassRef");
2962 case CXCursor_TypeRef:
2963 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002964 case CXCursor_TemplateRef:
2965 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002966 case CXCursor_NamespaceRef:
2967 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002968 case CXCursor_MemberRef:
2969 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002970 case CXCursor_LabelRef:
2971 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002972 case CXCursor_OverloadedDeclRef:
2973 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002974 case CXCursor_UnexposedExpr:
2975 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002976 case CXCursor_BlockExpr:
2977 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002978 case CXCursor_DeclRefExpr:
2979 return createCXString("DeclRefExpr");
2980 case CXCursor_MemberRefExpr:
2981 return createCXString("MemberRefExpr");
2982 case CXCursor_CallExpr:
2983 return createCXString("CallExpr");
2984 case CXCursor_ObjCMessageExpr:
2985 return createCXString("ObjCMessageExpr");
2986 case CXCursor_UnexposedStmt:
2987 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002988 case CXCursor_LabelStmt:
2989 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002990 case CXCursor_InvalidFile:
2991 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002992 case CXCursor_InvalidCode:
2993 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002994 case CXCursor_NoDeclFound:
2995 return createCXString("NoDeclFound");
2996 case CXCursor_NotImplemented:
2997 return createCXString("NotImplemented");
2998 case CXCursor_TranslationUnit:
2999 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003000 case CXCursor_UnexposedAttr:
3001 return createCXString("UnexposedAttr");
3002 case CXCursor_IBActionAttr:
3003 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003004 case CXCursor_IBOutletAttr:
3005 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003006 case CXCursor_IBOutletCollectionAttr:
3007 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003008 case CXCursor_PreprocessingDirective:
3009 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003010 case CXCursor_MacroDefinition:
3011 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003012 case CXCursor_MacroInstantiation:
3013 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003014 case CXCursor_InclusionDirective:
3015 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003016 case CXCursor_Namespace:
3017 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003018 case CXCursor_LinkageSpec:
3019 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003020 case CXCursor_CXXBaseSpecifier:
3021 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003022 case CXCursor_Constructor:
3023 return createCXString("CXXConstructor");
3024 case CXCursor_Destructor:
3025 return createCXString("CXXDestructor");
3026 case CXCursor_ConversionFunction:
3027 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003028 case CXCursor_TemplateTypeParameter:
3029 return createCXString("TemplateTypeParameter");
3030 case CXCursor_NonTypeTemplateParameter:
3031 return createCXString("NonTypeTemplateParameter");
3032 case CXCursor_TemplateTemplateParameter:
3033 return createCXString("TemplateTemplateParameter");
3034 case CXCursor_FunctionTemplate:
3035 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003036 case CXCursor_ClassTemplate:
3037 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003038 case CXCursor_ClassTemplatePartialSpecialization:
3039 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003040 case CXCursor_NamespaceAlias:
3041 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003042 case CXCursor_UsingDirective:
3043 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003044 case CXCursor_UsingDeclaration:
3045 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003046 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003047
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003048 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003049 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003050}
Steve Naroff89922f82009-08-31 00:59:03 +00003051
Ted Kremeneke68fff62010-02-17 00:41:32 +00003052enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3053 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003054 CXClientData client_data) {
3055 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003056
3057 // If our current best cursor is the construction of a temporary object,
3058 // don't replace that cursor with a type reference, because we want
3059 // clang_getCursor() to point at the constructor.
3060 if (clang_isExpression(BestCursor->kind) &&
3061 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3062 cursor.kind == CXCursor_TypeRef)
3063 return CXChildVisit_Recurse;
3064
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003065 *BestCursor = cursor;
3066 return CXChildVisit_Recurse;
3067}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003068
Douglas Gregorb9790342010-01-22 21:44:22 +00003069CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3070 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003071 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003072
Ted Kremeneka60ed472010-11-16 08:15:36 +00003073 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003074 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3075
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003076 // Translate the given source location to make it point at the beginning of
3077 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003078 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003079
3080 // Guard against an invalid SourceLocation, or we may assert in one
3081 // of the following calls.
3082 if (SLoc.isInvalid())
3083 return clang_getNullCursor();
3084
Douglas Gregor40749ee2010-11-03 00:35:38 +00003085 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003086 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3087 CXXUnit->getASTContext().getLangOptions());
3088
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003089 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3090 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003091 // FIXME: Would be great to have a "hint" cursor, then walk from that
3092 // hint cursor upward until we find a cursor whose source range encloses
3093 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003094 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3095 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003096 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003097 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003098 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003099
3100 if (Logging) {
3101 CXFile SearchFile;
3102 unsigned SearchLine, SearchColumn;
3103 CXFile ResultFile;
3104 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003105 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3106 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003107 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3108
3109 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3110 0);
3111 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3112 &ResultColumn, 0);
3113 SearchFileName = clang_getFileName(SearchFile);
3114 ResultFileName = clang_getFileName(ResultFile);
3115 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003116 USR = clang_getCursorUSR(Result);
3117 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003118 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3119 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003120 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3121 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003122 clang_disposeString(SearchFileName);
3123 clang_disposeString(ResultFileName);
3124 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003125 clang_disposeString(USR);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003126 }
3127
Ted Kremeneke68fff62010-02-17 00:41:32 +00003128 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003129}
3130
Ted Kremenek73885552009-11-17 19:28:59 +00003131CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003132 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003133}
3134
3135unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003136 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003137}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003138
Douglas Gregor9ce55842010-11-20 00:09:34 +00003139unsigned clang_hashCursor(CXCursor C) {
3140 unsigned Index = 0;
3141 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3142 Index = 1;
3143
3144 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3145 std::make_pair(C.kind, C.data[Index]));
3146}
3147
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003148unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003149 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3150}
3151
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003152unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003153 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3154}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003155
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003156unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003157 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3158}
3159
Douglas Gregor97b98722010-01-19 23:20:36 +00003160unsigned clang_isExpression(enum CXCursorKind K) {
3161 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3162}
3163
3164unsigned clang_isStatement(enum CXCursorKind K) {
3165 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3166}
3167
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003168unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3169 return K == CXCursor_TranslationUnit;
3170}
3171
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003172unsigned clang_isPreprocessing(enum CXCursorKind K) {
3173 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3174}
3175
Ted Kremenekad6eff62010-03-08 21:17:29 +00003176unsigned clang_isUnexposed(enum CXCursorKind K) {
3177 switch (K) {
3178 case CXCursor_UnexposedDecl:
3179 case CXCursor_UnexposedExpr:
3180 case CXCursor_UnexposedStmt:
3181 case CXCursor_UnexposedAttr:
3182 return true;
3183 default:
3184 return false;
3185 }
3186}
3187
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003188CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003189 return C.kind;
3190}
3191
Douglas Gregor98258af2010-01-18 22:46:11 +00003192CXSourceLocation clang_getCursorLocation(CXCursor C) {
3193 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003194 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003195 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003196 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3197 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003198 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003199 }
3200
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003201 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003202 std::pair<ObjCProtocolDecl *, SourceLocation> P
3203 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003204 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003205 }
3206
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003207 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003208 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3209 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003210 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003211 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003212
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003213 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003214 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003215 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003216 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003217
3218 case CXCursor_TemplateRef: {
3219 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3220 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3221 }
3222
Douglas Gregor69319002010-08-31 23:48:11 +00003223 case CXCursor_NamespaceRef: {
3224 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3225 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3226 }
3227
Douglas Gregora67e03f2010-09-09 21:42:20 +00003228 case CXCursor_MemberRef: {
3229 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3230 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3231 }
3232
Ted Kremenek3064ef92010-08-27 21:34:58 +00003233 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003234 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3235 if (!BaseSpec)
3236 return clang_getNullLocation();
3237
3238 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3239 return cxloc::translateSourceLocation(getCursorContext(C),
3240 TSInfo->getTypeLoc().getBeginLoc());
3241
3242 return cxloc::translateSourceLocation(getCursorContext(C),
3243 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003244 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003245
Douglas Gregor36897b02010-09-10 00:22:18 +00003246 case CXCursor_LabelRef: {
3247 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3248 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3249 }
3250
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003251 case CXCursor_OverloadedDeclRef:
3252 return cxloc::translateSourceLocation(getCursorContext(C),
3253 getCursorOverloadedDeclRef(C).second);
3254
Douglas Gregorf46034a2010-01-18 23:41:10 +00003255 default:
3256 // FIXME: Need a way to enumerate all non-reference cases.
3257 llvm_unreachable("Missed a reference kind");
3258 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003259 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003260
3261 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003262 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003263 getLocationFromExpr(getCursorExpr(C)));
3264
Douglas Gregor36897b02010-09-10 00:22:18 +00003265 if (clang_isStatement(C.kind))
3266 return cxloc::translateSourceLocation(getCursorContext(C),
3267 getCursorStmt(C)->getLocStart());
3268
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003269 if (C.kind == CXCursor_PreprocessingDirective) {
3270 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3271 return cxloc::translateSourceLocation(getCursorContext(C), L);
3272 }
Douglas Gregor48072312010-03-18 15:23:44 +00003273
3274 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003275 SourceLocation L
3276 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003277 return cxloc::translateSourceLocation(getCursorContext(C), L);
3278 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003279
3280 if (C.kind == CXCursor_MacroDefinition) {
3281 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3282 return cxloc::translateSourceLocation(getCursorContext(C), L);
3283 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003284
3285 if (C.kind == CXCursor_InclusionDirective) {
3286 SourceLocation L
3287 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3288 return cxloc::translateSourceLocation(getCursorContext(C), L);
3289 }
3290
Ted Kremenek9a700d22010-05-12 06:16:13 +00003291 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003292 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003293
Douglas Gregorf46034a2010-01-18 23:41:10 +00003294 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003295 SourceLocation Loc = D->getLocation();
3296 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3297 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003298 // FIXME: Multiple variables declared in a single declaration
3299 // currently lack the information needed to correctly determine their
3300 // ranges when accounting for the type-specifier. We use context
3301 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3302 // and if so, whether it is the first decl.
3303 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3304 if (!cxcursor::isFirstInDeclGroup(C))
3305 Loc = VD->getLocation();
3306 }
3307
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003308 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003309}
Douglas Gregora7bde202010-01-19 00:34:46 +00003310
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003311} // end extern "C"
3312
3313static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003314 if (clang_isReference(C.kind)) {
3315 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003316 case CXCursor_ObjCSuperClassRef:
3317 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003318
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003319 case CXCursor_ObjCProtocolRef:
3320 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003321
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003322 case CXCursor_ObjCClassRef:
3323 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003324
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003325 case CXCursor_TypeRef:
3326 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003327
3328 case CXCursor_TemplateRef:
3329 return getCursorTemplateRef(C).second;
3330
Douglas Gregor69319002010-08-31 23:48:11 +00003331 case CXCursor_NamespaceRef:
3332 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003333
3334 case CXCursor_MemberRef:
3335 return getCursorMemberRef(C).second;
3336
Ted Kremenek3064ef92010-08-27 21:34:58 +00003337 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003338 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003339
Douglas Gregor36897b02010-09-10 00:22:18 +00003340 case CXCursor_LabelRef:
3341 return getCursorLabelRef(C).second;
3342
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003343 case CXCursor_OverloadedDeclRef:
3344 return getCursorOverloadedDeclRef(C).second;
3345
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003346 default:
3347 // FIXME: Need a way to enumerate all non-reference cases.
3348 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003349 }
3350 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003351
3352 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003353 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003354
3355 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003356 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003357
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003358 if (C.kind == CXCursor_PreprocessingDirective)
3359 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003360
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003361 if (C.kind == CXCursor_MacroInstantiation)
3362 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003363
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003364 if (C.kind == CXCursor_MacroDefinition)
3365 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003366
3367 if (C.kind == CXCursor_InclusionDirective)
3368 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3369
Ted Kremenek007a7c92010-11-01 23:26:51 +00003370 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3371 Decl *D = cxcursor::getCursorDecl(C);
3372 SourceRange R = D->getSourceRange();
3373 // FIXME: Multiple variables declared in a single declaration
3374 // currently lack the information needed to correctly determine their
3375 // ranges when accounting for the type-specifier. We use context
3376 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3377 // and if so, whether it is the first decl.
3378 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3379 if (!cxcursor::isFirstInDeclGroup(C))
3380 R.setBegin(VD->getLocation());
3381 }
3382 return R;
3383 }
Douglas Gregor66537982010-11-17 17:14:07 +00003384 return SourceRange();
3385}
3386
3387/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3388/// the decl-specifier-seq for declarations.
3389static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3390 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3391 Decl *D = cxcursor::getCursorDecl(C);
3392 SourceRange R = D->getSourceRange();
3393
3394 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3395 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3396 TypeLoc TL = TI->getTypeLoc();
3397 SourceLocation TLoc = TL.getSourceRange().getBegin();
3398 if (TLoc.isValid() && R.getBegin().isValid() &&
3399 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3400 R.setBegin(TLoc);
3401 }
3402
3403 // FIXME: Multiple variables declared in a single declaration
3404 // currently lack the information needed to correctly determine their
3405 // ranges when accounting for the type-specifier. We use context
3406 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3407 // and if so, whether it is the first decl.
3408 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3409 if (!cxcursor::isFirstInDeclGroup(C))
3410 R.setBegin(VD->getLocation());
3411 }
3412 }
3413
3414 return R;
3415 }
3416
3417 return getRawCursorExtent(C);
3418}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003419
3420extern "C" {
3421
3422CXSourceRange clang_getCursorExtent(CXCursor C) {
3423 SourceRange R = getRawCursorExtent(C);
3424 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003425 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003426
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003427 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003428}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003429
3430CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003431 if (clang_isInvalid(C.kind))
3432 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003433
Ted Kremeneka60ed472010-11-16 08:15:36 +00003434 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003435 if (clang_isDeclaration(C.kind)) {
3436 Decl *D = getCursorDecl(C);
3437 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003438 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003439 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003440 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003441 if (ObjCForwardProtocolDecl *Protocols
3442 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003443 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003444 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3445 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3446 return MakeCXCursor(Property, tu);
3447
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003448 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003449 }
3450
Douglas Gregor97b98722010-01-19 23:20:36 +00003451 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003452 Expr *E = getCursorExpr(C);
3453 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003454 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003455 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003456
3457 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003458 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003459
Douglas Gregor97b98722010-01-19 23:20:36 +00003460 return clang_getNullCursor();
3461 }
3462
Douglas Gregor36897b02010-09-10 00:22:18 +00003463 if (clang_isStatement(C.kind)) {
3464 Stmt *S = getCursorStmt(C);
3465 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003466 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003467
3468 return clang_getNullCursor();
3469 }
3470
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003471 if (C.kind == CXCursor_MacroInstantiation) {
3472 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003473 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003474 }
3475
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003476 if (!clang_isReference(C.kind))
3477 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003478
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003479 switch (C.kind) {
3480 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003481 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003482
3483 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003484 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003485
3486 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003487 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003488
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003489 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003490 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003491
3492 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003493 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003494
Douglas Gregor69319002010-08-31 23:48:11 +00003495 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003496 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003497
Douglas Gregora67e03f2010-09-09 21:42:20 +00003498 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003499 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003500
Ted Kremenek3064ef92010-08-27 21:34:58 +00003501 case CXCursor_CXXBaseSpecifier: {
3502 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3503 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003504 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003505 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003506
Douglas Gregor36897b02010-09-10 00:22:18 +00003507 case CXCursor_LabelRef:
3508 // FIXME: We end up faking the "parent" declaration here because we
3509 // don't want to make CXCursor larger.
3510 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003511 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3512 .getTranslationUnitDecl(),
3513 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003514
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003515 case CXCursor_OverloadedDeclRef:
3516 return C;
3517
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003518 default:
3519 // We would prefer to enumerate all non-reference cursor kinds here.
3520 llvm_unreachable("Unhandled reference cursor kind");
3521 break;
3522 }
3523 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003524
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003525 return clang_getNullCursor();
3526}
3527
Douglas Gregorb6998662010-01-19 19:34:47 +00003528CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003529 if (clang_isInvalid(C.kind))
3530 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003531
Ted Kremeneka60ed472010-11-16 08:15:36 +00003532 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003533
Douglas Gregorb6998662010-01-19 19:34:47 +00003534 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003535 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003536 C = clang_getCursorReferenced(C);
3537 WasReference = true;
3538 }
3539
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003540 if (C.kind == CXCursor_MacroInstantiation)
3541 return clang_getCursorReferenced(C);
3542
Douglas Gregorb6998662010-01-19 19:34:47 +00003543 if (!clang_isDeclaration(C.kind))
3544 return clang_getNullCursor();
3545
3546 Decl *D = getCursorDecl(C);
3547 if (!D)
3548 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003549
Douglas Gregorb6998662010-01-19 19:34:47 +00003550 switch (D->getKind()) {
3551 // Declaration kinds that don't really separate the notions of
3552 // declaration and definition.
3553 case Decl::Namespace:
3554 case Decl::Typedef:
3555 case Decl::TemplateTypeParm:
3556 case Decl::EnumConstant:
3557 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003558 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003559 case Decl::ObjCIvar:
3560 case Decl::ObjCAtDefsField:
3561 case Decl::ImplicitParam:
3562 case Decl::ParmVar:
3563 case Decl::NonTypeTemplateParm:
3564 case Decl::TemplateTemplateParm:
3565 case Decl::ObjCCategoryImpl:
3566 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003567 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003568 case Decl::LinkageSpec:
3569 case Decl::ObjCPropertyImpl:
3570 case Decl::FileScopeAsm:
3571 case Decl::StaticAssert:
3572 case Decl::Block:
3573 return C;
3574
3575 // Declaration kinds that don't make any sense here, but are
3576 // nonetheless harmless.
3577 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 break;
3579
3580 // Declaration kinds for which the definition is not resolvable.
3581 case Decl::UnresolvedUsingTypename:
3582 case Decl::UnresolvedUsingValue:
3583 break;
3584
3585 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003586 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003587 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003588
3589 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003590 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003591
3592 case Decl::Enum:
3593 case Decl::Record:
3594 case Decl::CXXRecord:
3595 case Decl::ClassTemplateSpecialization:
3596 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003597 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003598 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003599 return clang_getNullCursor();
3600
3601 case Decl::Function:
3602 case Decl::CXXMethod:
3603 case Decl::CXXConstructor:
3604 case Decl::CXXDestructor:
3605 case Decl::CXXConversion: {
3606 const FunctionDecl *Def = 0;
3607 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003608 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003609 return clang_getNullCursor();
3610 }
3611
3612 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003613 // Ask the variable if it has a definition.
3614 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003615 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003616 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003617 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003618
Douglas Gregorb6998662010-01-19 19:34:47 +00003619 case Decl::FunctionTemplate: {
3620 const FunctionDecl *Def = 0;
3621 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003622 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003623 return clang_getNullCursor();
3624 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003625
Douglas Gregorb6998662010-01-19 19:34:47 +00003626 case Decl::ClassTemplate: {
3627 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003628 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003629 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003630 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003631 return clang_getNullCursor();
3632 }
3633
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003634 case Decl::Using:
3635 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003636 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003637
3638 case Decl::UsingShadow:
3639 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003640 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003641 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003642
3643 case Decl::ObjCMethod: {
3644 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3645 if (Method->isThisDeclarationADefinition())
3646 return C;
3647
3648 // Dig out the method definition in the associated
3649 // @implementation, if we have it.
3650 // FIXME: The ASTs should make finding the definition easier.
3651 if (ObjCInterfaceDecl *Class
3652 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3653 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3654 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3655 Method->isInstanceMethod()))
3656 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003657 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003658
3659 return clang_getNullCursor();
3660 }
3661
3662 case Decl::ObjCCategory:
3663 if (ObjCCategoryImplDecl *Impl
3664 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003665 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003666 return clang_getNullCursor();
3667
3668 case Decl::ObjCProtocol:
3669 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3670 return C;
3671 return clang_getNullCursor();
3672
3673 case Decl::ObjCInterface:
3674 // There are two notions of a "definition" for an Objective-C
3675 // class: the interface and its implementation. When we resolved a
3676 // reference to an Objective-C class, produce the @interface as
3677 // the definition; when we were provided with the interface,
3678 // produce the @implementation as the definition.
3679 if (WasReference) {
3680 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3681 return C;
3682 } else if (ObjCImplementationDecl *Impl
3683 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003684 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003685 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003686
Douglas Gregorb6998662010-01-19 19:34:47 +00003687 case Decl::ObjCProperty:
3688 // FIXME: We don't really know where to find the
3689 // ObjCPropertyImplDecls that implement this property.
3690 return clang_getNullCursor();
3691
3692 case Decl::ObjCCompatibleAlias:
3693 if (ObjCInterfaceDecl *Class
3694 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3695 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003696 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003697
Douglas Gregorb6998662010-01-19 19:34:47 +00003698 return clang_getNullCursor();
3699
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003700 case Decl::ObjCForwardProtocol:
3701 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003702 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003703
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003704 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003705 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003706 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003707
3708 case Decl::Friend:
3709 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003710 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003711 return clang_getNullCursor();
3712
3713 case Decl::FriendTemplate:
3714 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003715 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003716 return clang_getNullCursor();
3717 }
3718
3719 return clang_getNullCursor();
3720}
3721
3722unsigned clang_isCursorDefinition(CXCursor C) {
3723 if (!clang_isDeclaration(C.kind))
3724 return 0;
3725
3726 return clang_getCursorDefinition(C) == C;
3727}
3728
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003729CXCursor clang_getCanonicalCursor(CXCursor C) {
3730 if (!clang_isDeclaration(C.kind))
3731 return C;
3732
3733 if (Decl *D = getCursorDecl(C))
3734 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3735
3736 return C;
3737}
3738
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003739unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003740 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003741 return 0;
3742
3743 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3744 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3745 return E->getNumDecls();
3746
3747 if (OverloadedTemplateStorage *S
3748 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3749 return S->size();
3750
3751 Decl *D = Storage.get<Decl*>();
3752 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003753 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003754 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3755 return Classes->size();
3756 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3757 return Protocols->protocol_size();
3758
3759 return 0;
3760}
3761
3762CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003763 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003764 return clang_getNullCursor();
3765
3766 if (index >= clang_getNumOverloadedDecls(cursor))
3767 return clang_getNullCursor();
3768
Ted Kremeneka60ed472010-11-16 08:15:36 +00003769 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003770 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3771 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003772 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003773
3774 if (OverloadedTemplateStorage *S
3775 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003776 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003777
3778 Decl *D = Storage.get<Decl*>();
3779 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3780 // FIXME: This is, unfortunately, linear time.
3781 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3782 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003783 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003784 }
3785
3786 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003787 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003788
3789 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003790 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003791
3792 return clang_getNullCursor();
3793}
3794
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003795void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003796 const char **startBuf,
3797 const char **endBuf,
3798 unsigned *startLine,
3799 unsigned *startColumn,
3800 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003801 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003802 assert(getCursorDecl(C) && "CXCursor has null decl");
3803 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003804 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3805 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Steve Naroff4ade6d62009-09-23 17:52:52 +00003807 SourceManager &SM = FD->getASTContext().getSourceManager();
3808 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3809 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3810 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3811 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3812 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3813 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3814}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003815
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003816void clang_enableStackTraces(void) {
3817 llvm::sys::PrintStackTraceOnErrorSignal();
3818}
3819
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003820void clang_executeOnThread(void (*fn)(void*), void *user_data,
3821 unsigned stack_size) {
3822 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3823}
3824
Ted Kremenekfb480492010-01-13 21:46:36 +00003825} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003826
Ted Kremenekfb480492010-01-13 21:46:36 +00003827//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003828// Token-based Operations.
3829//===----------------------------------------------------------------------===//
3830
3831/* CXToken layout:
3832 * int_data[0]: a CXTokenKind
3833 * int_data[1]: starting token location
3834 * int_data[2]: token length
3835 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837 * otherwise unused.
3838 */
3839extern "C" {
3840
3841CXTokenKind clang_getTokenKind(CXToken CXTok) {
3842 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3843}
3844
3845CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3846 switch (clang_getTokenKind(CXTok)) {
3847 case CXToken_Identifier:
3848 case CXToken_Keyword:
3849 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003850 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3851 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003852
3853 case CXToken_Literal: {
3854 // We have stashed the starting pointer in the ptr_data field. Use it.
3855 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003856 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003857 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 case CXToken_Punctuation:
3860 case CXToken_Comment:
3861 break;
3862 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
3864 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003865 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003866 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003867 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003868 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3871 std::pair<FileID, unsigned> LocInfo
3872 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003873 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003874 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003875 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3876 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003877 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003879 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003880}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003881
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003882CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003883 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003884 if (!CXXUnit)
3885 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003886
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003887 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3888 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3889}
3890
3891CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003892 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003893 if (!CXXUnit)
3894 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003895
3896 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003897 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3898}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003899
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003900void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3901 CXToken **Tokens, unsigned *NumTokens) {
3902 if (Tokens)
3903 *Tokens = 0;
3904 if (NumTokens)
3905 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003906
Ted Kremeneka60ed472010-11-16 08:15:36 +00003907 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003908 if (!CXXUnit || !Tokens || !NumTokens)
3909 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003910
Douglas Gregorbdf60622010-03-05 21:16:25 +00003911 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3912
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003913 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003914 if (R.isInvalid())
3915 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003916
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003917 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3918 std::pair<FileID, unsigned> BeginLocInfo
3919 = SourceMgr.getDecomposedLoc(R.getBegin());
3920 std::pair<FileID, unsigned> EndLocInfo
3921 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003922
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003923 // Cannot tokenize across files.
3924 if (BeginLocInfo.first != EndLocInfo.first)
3925 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003926
3927 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003928 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003929 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003930 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003931 if (Invalid)
3932 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003933
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003934 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3935 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003936 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003937 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003938
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003939 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003940 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003941 llvm::SmallVector<CXToken, 32> CXTokens;
3942 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003943 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003944 do {
3945 // Lex the next token
3946 Lex.LexFromRawLexer(Tok);
3947 if (Tok.is(tok::eof))
3948 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003949
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003950 // Initialize the CXToken.
3951 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003952
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003953 // - Common fields
3954 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3955 CXTok.int_data[2] = Tok.getLength();
3956 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003957
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003958 // - Kind-specific fields
3959 if (Tok.isLiteral()) {
3960 CXTok.int_data[0] = CXToken_Literal;
3961 CXTok.ptr_data = (void *)Tok.getLiteralData();
3962 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003963 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003964 std::pair<FileID, unsigned> LocInfo
3965 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003966 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003967 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003968 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3969 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003970 return;
3971
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003972 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003973 IdentifierInfo *II
3974 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003975
David Chisnall096428b2010-10-13 21:44:48 +00003976 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003977 CXTok.int_data[0] = CXToken_Keyword;
3978 }
3979 else {
3980 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3981 CXToken_Identifier
3982 : CXToken_Keyword;
3983 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003984 CXTok.ptr_data = II;
3985 } else if (Tok.is(tok::comment)) {
3986 CXTok.int_data[0] = CXToken_Comment;
3987 CXTok.ptr_data = 0;
3988 } else {
3989 CXTok.int_data[0] = CXToken_Punctuation;
3990 CXTok.ptr_data = 0;
3991 }
3992 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003993 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003994 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003995
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003996 if (CXTokens.empty())
3997 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003998
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003999 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4000 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4001 *NumTokens = CXTokens.size();
4002}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004003
Ted Kremenek6db61092010-05-05 00:55:15 +00004004void clang_disposeTokens(CXTranslationUnit TU,
4005 CXToken *Tokens, unsigned NumTokens) {
4006 free(Tokens);
4007}
4008
4009} // end: extern "C"
4010
4011//===----------------------------------------------------------------------===//
4012// Token annotation APIs.
4013//===----------------------------------------------------------------------===//
4014
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004015typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004016static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4017 CXCursor parent,
4018 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004019namespace {
4020class AnnotateTokensWorker {
4021 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004022 CXToken *Tokens;
4023 CXCursor *Cursors;
4024 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004025 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004026 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004027 CursorVisitor AnnotateVis;
4028 SourceManager &SrcMgr;
4029
4030 bool MoreTokens() const { return TokIdx < NumTokens; }
4031 unsigned NextToken() const { return TokIdx; }
4032 void AdvanceToken() { ++TokIdx; }
4033 SourceLocation GetTokenLoc(unsigned tokI) {
4034 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4035 }
4036
Ted Kremenek6db61092010-05-05 00:55:15 +00004037public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004038 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004039 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004040 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004041 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004042 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004043 AnnotateVis(tu,
4044 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004045 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004046 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004047
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004048 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004049 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004050 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004051 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004052 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004053 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004054};
4055}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004056
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004057void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4058 // Walk the AST within the region of interest, annotating tokens
4059 // along the way.
4060 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004061
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004062 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4063 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004064 if (Pos != Annotated.end() &&
4065 (clang_isInvalid(Cursors[I].kind) ||
4066 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004067 Cursors[I] = Pos->second;
4068 }
4069
4070 // Finish up annotating any tokens left.
4071 if (!MoreTokens())
4072 return;
4073
4074 const CXCursor &C = clang_getNullCursor();
4075 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4076 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4077 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004078 }
4079}
4080
Ted Kremenek6db61092010-05-05 00:55:15 +00004081enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004082AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004083 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004084 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004085 if (cursorRange.isInvalid())
4086 return CXChildVisit_Recurse;
4087
Douglas Gregor4419b672010-10-21 06:10:04 +00004088 if (clang_isPreprocessing(cursor.kind)) {
4089 // For macro instantiations, just note where the beginning of the macro
4090 // instantiation occurs.
4091 if (cursor.kind == CXCursor_MacroInstantiation) {
4092 Annotated[Loc.int_data] = cursor;
4093 return CXChildVisit_Recurse;
4094 }
4095
Douglas Gregor4419b672010-10-21 06:10:04 +00004096 // Items in the preprocessing record are kept separate from items in
4097 // declarations, so we keep a separate token index.
4098 unsigned SavedTokIdx = TokIdx;
4099 TokIdx = PreprocessingTokIdx;
4100
4101 // Skip tokens up until we catch up to the beginning of the preprocessing
4102 // entry.
4103 while (MoreTokens()) {
4104 const unsigned I = NextToken();
4105 SourceLocation TokLoc = GetTokenLoc(I);
4106 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4107 case RangeBefore:
4108 AdvanceToken();
4109 continue;
4110 case RangeAfter:
4111 case RangeOverlap:
4112 break;
4113 }
4114 break;
4115 }
4116
4117 // Look at all of the tokens within this range.
4118 while (MoreTokens()) {
4119 const unsigned I = NextToken();
4120 SourceLocation TokLoc = GetTokenLoc(I);
4121 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4122 case RangeBefore:
4123 assert(0 && "Infeasible");
4124 case RangeAfter:
4125 break;
4126 case RangeOverlap:
4127 Cursors[I] = cursor;
4128 AdvanceToken();
4129 continue;
4130 }
4131 break;
4132 }
4133
4134 // Save the preprocessing token index; restore the non-preprocessing
4135 // token index.
4136 PreprocessingTokIdx = TokIdx;
4137 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004138 return CXChildVisit_Recurse;
4139 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004140
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004141 if (cursorRange.isInvalid())
4142 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004143
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004144 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4145
Ted Kremeneka333c662010-05-12 05:29:33 +00004146 // Adjust the annotated range based specific declarations.
4147 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4148 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004149 Decl *D = cxcursor::getCursorDecl(cursor);
4150 // Don't visit synthesized ObjC methods, since they have no syntatic
4151 // representation in the source.
4152 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4153 if (MD->isSynthesized())
4154 return CXChildVisit_Continue;
4155 }
4156 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004157 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4158 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004159 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004160 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004161 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004162 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004163 }
4164 }
4165 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004166
Ted Kremenek3f404602010-08-14 01:14:06 +00004167 // If the location of the cursor occurs within a macro instantiation, record
4168 // the spelling location of the cursor in our annotation map. We can then
4169 // paper over the token labelings during a post-processing step to try and
4170 // get cursor mappings for tokens that are the *arguments* of a macro
4171 // instantiation.
4172 if (L.isMacroID()) {
4173 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4174 // Only invalidate the old annotation if it isn't part of a preprocessing
4175 // directive. Here we assume that the default construction of CXCursor
4176 // results in CXCursor.kind being an initialized value (i.e., 0). If
4177 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004178
Ted Kremenek3f404602010-08-14 01:14:06 +00004179 CXCursor &oldC = Annotated[rawEncoding];
4180 if (!clang_isPreprocessing(oldC.kind))
4181 oldC = cursor;
4182 }
4183
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004184 const enum CXCursorKind K = clang_getCursorKind(parent);
4185 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004186 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4187 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004188
4189 while (MoreTokens()) {
4190 const unsigned I = NextToken();
4191 SourceLocation TokLoc = GetTokenLoc(I);
4192 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4193 case RangeBefore:
4194 Cursors[I] = updateC;
4195 AdvanceToken();
4196 continue;
4197 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004198 case RangeOverlap:
4199 break;
4200 }
4201 break;
4202 }
4203
4204 // Visit children to get their cursor information.
4205 const unsigned BeforeChildren = NextToken();
4206 VisitChildren(cursor);
4207 const unsigned AfterChildren = NextToken();
4208
4209 // Adjust 'Last' to the last token within the extent of the cursor.
4210 while (MoreTokens()) {
4211 const unsigned I = NextToken();
4212 SourceLocation TokLoc = GetTokenLoc(I);
4213 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4214 case RangeBefore:
4215 assert(0 && "Infeasible");
4216 case RangeAfter:
4217 break;
4218 case RangeOverlap:
4219 Cursors[I] = updateC;
4220 AdvanceToken();
4221 continue;
4222 }
4223 break;
4224 }
4225 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004226
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227 // Scan the tokens that are at the beginning of the cursor, but are not
4228 // capture by the child cursors.
4229
4230 // For AST elements within macros, rely on a post-annotate pass to
4231 // to correctly annotate the tokens with cursors. Otherwise we can
4232 // get confusing results of having tokens that map to cursors that really
4233 // are expanded by an instantiation.
4234 if (L.isMacroID())
4235 cursor = clang_getNullCursor();
4236
4237 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4238 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4239 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004240
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004241 Cursors[I] = cursor;
4242 }
4243 // Scan the tokens that are at the end of the cursor, but are not captured
4244 // but the child cursors.
4245 for (unsigned I = AfterChildren; I != Last; ++I)
4246 Cursors[I] = cursor;
4247
4248 TokIdx = Last;
4249 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004250}
4251
Ted Kremenek6db61092010-05-05 00:55:15 +00004252static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4253 CXCursor parent,
4254 CXClientData client_data) {
4255 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4256}
4257
Ted Kremenekab979612010-11-11 08:05:23 +00004258// This gets run a separate thread to avoid stack blowout.
4259static void runAnnotateTokensWorker(void *UserData) {
4260 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4261}
4262
Ted Kremenek6db61092010-05-05 00:55:15 +00004263extern "C" {
4264
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004265void clang_annotateTokens(CXTranslationUnit TU,
4266 CXToken *Tokens, unsigned NumTokens,
4267 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004268
4269 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004270 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004271
Douglas Gregor4419b672010-10-21 06:10:04 +00004272 // Any token we don't specifically annotate will have a NULL cursor.
4273 CXCursor C = clang_getNullCursor();
4274 for (unsigned I = 0; I != NumTokens; ++I)
4275 Cursors[I] = C;
4276
Ted Kremeneka60ed472010-11-16 08:15:36 +00004277 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004278 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004279 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004280
Douglas Gregorbdf60622010-03-05 21:16:25 +00004281 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004282
Douglas Gregor0396f462010-03-19 05:22:59 +00004283 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004284 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4286 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004287 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4288 clang_getTokenLocation(TU,
4289 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004290
Douglas Gregor0396f462010-03-19 05:22:59 +00004291 // A mapping from the source locations found when re-lexing or traversing the
4292 // region of interest to the corresponding cursors.
4293 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004294
4295 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004296 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004297 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4298 std::pair<FileID, unsigned> BeginLocInfo
4299 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4300 std::pair<FileID, unsigned> EndLocInfo
4301 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004302
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004303 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004304 bool Invalid = false;
4305 if (BeginLocInfo.first == EndLocInfo.first &&
4306 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4307 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004308 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4309 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004310 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004311 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004312 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004313
4314 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004315 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004316 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004317 Token Tok;
4318 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004319
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004320 reprocess:
4321 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4322 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004323 // don't see it while preprocessing these tokens later, but keep track
4324 // of all of the token locations inside this preprocessing directive so
4325 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004326 //
4327 // FIXME: Some simple tests here could identify macro definitions and
4328 // #undefs, to provide specific cursor kinds for those.
4329 std::vector<SourceLocation> Locations;
4330 do {
4331 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004332 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004333 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004334
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004335 using namespace cxcursor;
4336 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004337 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4338 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004339 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004340 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4341 Annotated[Locations[I].getRawEncoding()] = Cursor;
4342 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004343
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004344 if (Tok.isAtStartOfLine())
4345 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004346
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004347 continue;
4348 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004349
Douglas Gregor48072312010-03-18 15:23:44 +00004350 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004351 break;
4352 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004353 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004354
Douglas Gregor0396f462010-03-19 05:22:59 +00004355 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004356 // a specific cursor.
4357 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004358 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004359
4360 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004361 // FIXME: We use a ridiculous stack size here because the data-recursion
4362 // algorithm uses a large stack frame than the non-data recursive version,
4363 // and AnnotationTokensWorker currently transforms the data-recursion
4364 // algorithm back into a traditional recursion by explicitly calling
4365 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004366 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004367 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4368 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004369 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4370 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004371}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004372} // end: extern "C"
4373
4374//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004375// Operations for querying linkage of a cursor.
4376//===----------------------------------------------------------------------===//
4377
4378extern "C" {
4379CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004380 if (!clang_isDeclaration(cursor.kind))
4381 return CXLinkage_Invalid;
4382
Ted Kremenek16b42592010-03-03 06:36:57 +00004383 Decl *D = cxcursor::getCursorDecl(cursor);
4384 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4385 switch (ND->getLinkage()) {
4386 case NoLinkage: return CXLinkage_NoLinkage;
4387 case InternalLinkage: return CXLinkage_Internal;
4388 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4389 case ExternalLinkage: return CXLinkage_External;
4390 };
4391
4392 return CXLinkage_Invalid;
4393}
4394} // end: extern "C"
4395
4396//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004397// Operations for querying language of a cursor.
4398//===----------------------------------------------------------------------===//
4399
4400static CXLanguageKind getDeclLanguage(const Decl *D) {
4401 switch (D->getKind()) {
4402 default:
4403 break;
4404 case Decl::ImplicitParam:
4405 case Decl::ObjCAtDefsField:
4406 case Decl::ObjCCategory:
4407 case Decl::ObjCCategoryImpl:
4408 case Decl::ObjCClass:
4409 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004410 case Decl::ObjCForwardProtocol:
4411 case Decl::ObjCImplementation:
4412 case Decl::ObjCInterface:
4413 case Decl::ObjCIvar:
4414 case Decl::ObjCMethod:
4415 case Decl::ObjCProperty:
4416 case Decl::ObjCPropertyImpl:
4417 case Decl::ObjCProtocol:
4418 return CXLanguage_ObjC;
4419 case Decl::CXXConstructor:
4420 case Decl::CXXConversion:
4421 case Decl::CXXDestructor:
4422 case Decl::CXXMethod:
4423 case Decl::CXXRecord:
4424 case Decl::ClassTemplate:
4425 case Decl::ClassTemplatePartialSpecialization:
4426 case Decl::ClassTemplateSpecialization:
4427 case Decl::Friend:
4428 case Decl::FriendTemplate:
4429 case Decl::FunctionTemplate:
4430 case Decl::LinkageSpec:
4431 case Decl::Namespace:
4432 case Decl::NamespaceAlias:
4433 case Decl::NonTypeTemplateParm:
4434 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004435 case Decl::TemplateTemplateParm:
4436 case Decl::TemplateTypeParm:
4437 case Decl::UnresolvedUsingTypename:
4438 case Decl::UnresolvedUsingValue:
4439 case Decl::Using:
4440 case Decl::UsingDirective:
4441 case Decl::UsingShadow:
4442 return CXLanguage_CPlusPlus;
4443 }
4444
4445 return CXLanguage_C;
4446}
4447
4448extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004449
4450enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4451 if (clang_isDeclaration(cursor.kind))
4452 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4453 if (D->hasAttr<UnavailableAttr>() ||
4454 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4455 return CXAvailability_Available;
4456
4457 if (D->hasAttr<DeprecatedAttr>())
4458 return CXAvailability_Deprecated;
4459 }
4460
4461 return CXAvailability_Available;
4462}
4463
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004464CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4465 if (clang_isDeclaration(cursor.kind))
4466 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4467
4468 return CXLanguage_Invalid;
4469}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004470
4471CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4472 if (clang_isDeclaration(cursor.kind)) {
4473 if (Decl *D = getCursorDecl(cursor)) {
4474 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004475 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004476 }
4477 }
4478
4479 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4480 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004481 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004482 }
4483
4484 return clang_getNullCursor();
4485}
4486
4487CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4488 if (clang_isDeclaration(cursor.kind)) {
4489 if (Decl *D = getCursorDecl(cursor)) {
4490 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004491 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004492 }
4493 }
4494
4495 // FIXME: Note that we can't easily compute the lexical context of a
4496 // statement or expression, so we return nothing.
4497 return clang_getNullCursor();
4498}
4499
Douglas Gregor9f592342010-10-01 20:25:15 +00004500static void CollectOverriddenMethods(DeclContext *Ctx,
4501 ObjCMethodDecl *Method,
4502 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4503 if (!Ctx)
4504 return;
4505
4506 // If we have a class or category implementation, jump straight to the
4507 // interface.
4508 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4509 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4510
4511 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4512 if (!Container)
4513 return;
4514
4515 // Check whether we have a matching method at this level.
4516 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4517 Method->isInstanceMethod()))
4518 if (Method != Overridden) {
4519 // We found an override at this level; there is no need to look
4520 // into other protocols or categories.
4521 Methods.push_back(Overridden);
4522 return;
4523 }
4524
4525 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4526 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4527 PEnd = Protocol->protocol_end();
4528 P != PEnd; ++P)
4529 CollectOverriddenMethods(*P, Method, Methods);
4530 }
4531
4532 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4533 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4534 PEnd = Category->protocol_end();
4535 P != PEnd; ++P)
4536 CollectOverriddenMethods(*P, Method, Methods);
4537 }
4538
4539 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4540 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4541 PEnd = Interface->protocol_end();
4542 P != PEnd; ++P)
4543 CollectOverriddenMethods(*P, Method, Methods);
4544
4545 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4546 Category; Category = Category->getNextClassCategory())
4547 CollectOverriddenMethods(Category, Method, Methods);
4548
4549 // We only look into the superclass if we haven't found anything yet.
4550 if (Methods.empty())
4551 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4552 return CollectOverriddenMethods(Super, Method, Methods);
4553 }
4554}
4555
4556void clang_getOverriddenCursors(CXCursor cursor,
4557 CXCursor **overridden,
4558 unsigned *num_overridden) {
4559 if (overridden)
4560 *overridden = 0;
4561 if (num_overridden)
4562 *num_overridden = 0;
4563 if (!overridden || !num_overridden)
4564 return;
4565
4566 if (!clang_isDeclaration(cursor.kind))
4567 return;
4568
4569 Decl *D = getCursorDecl(cursor);
4570 if (!D)
4571 return;
4572
4573 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004574 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004575 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4576 *num_overridden = CXXMethod->size_overridden_methods();
4577 if (!*num_overridden)
4578 return;
4579
4580 *overridden = new CXCursor [*num_overridden];
4581 unsigned I = 0;
4582 for (CXXMethodDecl::method_iterator
4583 M = CXXMethod->begin_overridden_methods(),
4584 MEnd = CXXMethod->end_overridden_methods();
4585 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004586 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004587 return;
4588 }
4589
4590 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4591 if (!Method)
4592 return;
4593
4594 // Handle Objective-C methods.
4595 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4596 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4597
4598 if (Methods.empty())
4599 return;
4600
4601 *num_overridden = Methods.size();
4602 *overridden = new CXCursor [Methods.size()];
4603 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004604 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004605}
4606
4607void clang_disposeOverriddenCursors(CXCursor *overridden) {
4608 delete [] overridden;
4609}
4610
Douglas Gregorecdcb882010-10-20 22:00:55 +00004611CXFile clang_getIncludedFile(CXCursor cursor) {
4612 if (cursor.kind != CXCursor_InclusionDirective)
4613 return 0;
4614
4615 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4616 return (void *)ID->getFile();
4617}
4618
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004619} // end: extern "C"
4620
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004621
4622//===----------------------------------------------------------------------===//
4623// C++ AST instrospection.
4624//===----------------------------------------------------------------------===//
4625
4626extern "C" {
4627unsigned clang_CXXMethod_isStatic(CXCursor C) {
4628 if (!clang_isDeclaration(C.kind))
4629 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004630
4631 CXXMethodDecl *Method = 0;
4632 Decl *D = cxcursor::getCursorDecl(C);
4633 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4634 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4635 else
4636 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4637 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004638}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004639
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004640} // end: extern "C"
4641
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004642//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004643// Attribute introspection.
4644//===----------------------------------------------------------------------===//
4645
4646extern "C" {
4647CXType clang_getIBOutletCollectionType(CXCursor C) {
4648 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004649 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004650
4651 IBOutletCollectionAttr *A =
4652 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4653
Ted Kremeneka60ed472010-11-16 08:15:36 +00004654 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004655}
4656} // end: extern "C"
4657
4658//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004659// Misc. utility functions.
4660//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004661
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004662/// Default to using an 8 MB stack size on "safety" threads.
4663static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004664
4665namespace clang {
4666
4667bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004668 void (*Fn)(void*), void *UserData,
4669 unsigned Size) {
4670 if (!Size)
4671 Size = GetSafetyThreadStackSize();
4672 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004673 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4674 return CRC.RunSafely(Fn, UserData);
4675}
4676
4677unsigned GetSafetyThreadStackSize() {
4678 return SafetyStackThreadSize;
4679}
4680
4681void SetSafetyThreadStackSize(unsigned Value) {
4682 SafetyStackThreadSize = Value;
4683}
4684
4685}
4686
Ted Kremenek04bb7162010-01-22 22:44:15 +00004687extern "C" {
4688
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004689CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004690 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004691}
4692
4693} // end: extern "C"