blob: b6b5922feb88a1ff8a388b0c7cac89ee6f37d327 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
37#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000038#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000039#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000040#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000042#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000043#include "llvm/Support/Mutex.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000047#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000048
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Ted Kremeneka60ed472010-11-16 08:15:36 +000053static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
54 if (!TU)
55 return 0;
56 CXTranslationUnit D = new CXTranslationUnitImpl();
57 D->TUData = TU;
58 D->StringPool = createCXStringPool();
59 return D;
60}
61
Douglas Gregor33e9abd2010-01-22 19:49:59 +000062/// \brief The result of comparing two source ranges.
63enum RangeComparisonResult {
64 /// \brief Either the ranges overlap or one of the ranges is invalid.
65 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000066
Douglas Gregor33e9abd2010-01-22 19:49:59 +000067 /// \brief The first range ends before the second range starts.
68 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000069
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070 /// \brief The first range starts after the second range ends.
71 RangeAfter
72};
73
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076static RangeComparisonResult RangeCompare(SourceManager &SM,
77 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 SourceRange R2) {
79 assert(R1.isValid() && "First range is invalid?");
80 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000081 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000082 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000085 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 return RangeAfter;
87 return RangeOverlap;
88}
89
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000090/// \brief Determine if a source location falls within, before, or after a
91/// a given source range.
92static RangeComparisonResult LocationCompare(SourceManager &SM,
93 SourceLocation L, SourceRange R) {
94 assert(R.isValid() && "First range is invalid?");
95 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000096 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
99 return RangeBefore;
100 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
101 return RangeAfter;
102 return RangeOverlap;
103}
104
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105/// \brief Translate a Clang source range into a CIndex source range.
106///
107/// Clang internally represents ranges where the end location points to the
108/// start of the token at the end. However, for external clients it is more
109/// useful to have a CXSourceRange be a proper half-open interval. This routine
110/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000111CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000113 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000115 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000117 if (EndLoc.isValid() && EndLoc.isMacroID())
118 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000119 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000120 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000121 EndLoc = EndLoc.getFileLocWithOffset(Length);
122 }
123
124 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
125 R.getBegin().getRawEncoding(),
126 EndLoc.getRawEncoding() };
127 return Result;
128}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000129
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
133
Steve Naroff89922f82009-08-31 00:59:03 +0000134namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135
136class VisitorJob {
137public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000138 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000139 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000140 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000141 ExplicitTemplateArgsVisitKind,
142 NestedNameSpecifierVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000143 DeclarationNameInfoVisitKind,
144 MemberRefVisitKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000145protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000146 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147 CXCursor parent;
148 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
150 : parent(C), K(k) {
151 data[0] = d1;
152 data[1] = d2;
153 data[2] = d3;
154 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000155public:
156 Kind getKind() const { return K; }
157 const CXCursor &getParent() const { return parent; }
158 static bool classof(VisitorJob *VJ) { return true; }
159};
160
161typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
162
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000164class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000165 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000168 CXTranslationUnit TU;
169 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The declaration that serves at the parent of any statement or
175 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000176 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000178 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000179 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000184 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
185 // to the visitor. Declarations with a PCH level greater than this value will
186 // be suppressed.
187 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188
189 /// \brief When valid, a source range to which the cursor should restrict
190 /// its search.
191 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000193 // FIXME: Eventually remove. This part of a hack to support proper
194 // iteration over all Decls contained lexically within an ObjC container.
195 DeclContext::decl_iterator *DI_current;
196 DeclContext::decl_iterator DE_current;
197
Ted Kremenekd1ded662010-11-15 23:31:32 +0000198 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
199 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
200 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000204
205 /// \brief Determine whether this particular source range comes before, comes
206 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000208 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
210
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000211 class SetParentRAII {
212 CXCursor &Parent;
213 Decl *&StmtParent;
214 CXCursor OldParent;
215
216 public:
217 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
218 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
219 {
220 Parent = NewParent;
221 if (clang_isDeclaration(Parent.kind))
222 StmtParent = getCursorDecl(Parent);
223 }
224
225 ~SetParentRAII() {
226 Parent = OldParent;
227 if (clang_isDeclaration(Parent.kind))
228 StmtParent = getCursorDecl(Parent);
229 }
230 };
231
Steve Naroff89922f82009-08-31 00:59:03 +0000232public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000233 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
234 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000237 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
238 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000239 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
240 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 {
242 Parent.kind = CXCursor_NoDeclFound;
243 Parent.data[0] = 0;
244 Parent.data[1] = 0;
245 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000246 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000247 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000248
Ted Kremenekd1ded662010-11-15 23:31:32 +0000249 ~CursorVisitor() {
250 // Free the pre-allocated worklists for data-recursion.
251 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
252 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
253 delete *I;
254 }
255 }
256
Ted Kremeneka60ed472010-11-16 08:15:36 +0000257 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
258 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000259
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000260 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000261
262 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
263 getPreprocessedEntities();
264
Douglas Gregorb1373d02010-01-20 20:59:29 +0000265 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000266
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000268 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000269 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000270 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000271 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000273 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
274 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000276 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000277 bool VisitClassTemplatePartialSpecializationDecl(
278 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000279 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000280 bool VisitEnumConstantDecl(EnumConstantDecl *D);
281 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
282 bool VisitFunctionDecl(FunctionDecl *ND);
283 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000284 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000285 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000287 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000288 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
290 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
291 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
292 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000293 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
295 bool VisitObjCImplDecl(ObjCImplDecl *D);
296 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
297 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
299 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
300 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000301 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000302 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000303 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000304 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000305 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000306 bool VisitUsingDecl(UsingDecl *D);
307 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
308 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000309
Douglas Gregor01829d32010-08-31 14:41:23 +0000310 // Name visitor
311 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000312 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000313
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000314 // Template visitors
315 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000316 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000317 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
318
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000319 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000320 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000322 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
324 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000325 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000326 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000327 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000329 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitPointerTypeLoc(PointerTypeLoc TL);
331 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
332 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
333 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
334 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000335 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000337 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000338 // FIXME: Implement visitors here when the unimplemented TypeLocs get
339 // implemented
340 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000341 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000342 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000343
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000344 // Data-recursive visitor functions.
345 bool IsInRegionOfInterest(CXCursor C);
346 bool RunVisitorWorkList(VisitorWorkList &WL);
347 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000348 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000349};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000350
Ted Kremenekab188932010-01-05 19:32:54 +0000351} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000352
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000353static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000354static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
355
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000356
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000358 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359}
360
Douglas Gregorb1373d02010-01-20 20:59:29 +0000361/// \brief Visit the given cursor and, if requested by the visitor,
362/// its children.
363///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000364/// \param Cursor the cursor to visit.
365///
366/// \param CheckRegionOfInterest if true, then the caller already checked that
367/// this cursor is within the region of interest.
368///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369/// \returns true if the visitation should be aborted, false if it
370/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 if (clang_isInvalid(Cursor.kind))
373 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000374
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 if (clang_isDeclaration(Cursor.kind)) {
376 Decl *D = getCursorDecl(Cursor);
377 assert(D && "Invalid declaration cursor");
378 if (D->getPCHLevel() > MaxPCHLevel)
379 return false;
380
381 if (D->isImplicit())
382 return false;
383 }
384
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385 // If we have a range of interest, and this cursor doesn't intersect with it,
386 // we're done.
387 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000388 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000389 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390 return false;
391 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000392
Douglas Gregorb1373d02010-01-20 20:59:29 +0000393 switch (Visitor(Cursor, Parent, ClientData)) {
394 case CXChildVisit_Break:
395 return true;
396
397 case CXChildVisit_Continue:
398 return false;
399
400 case CXChildVisit_Recurse:
401 return VisitChildren(Cursor);
402 }
403
Douglas Gregorfd643772010-01-25 16:45:46 +0000404 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405}
406
Douglas Gregor788f5a12010-03-20 00:41:21 +0000407std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
408CursorVisitor::getPreprocessedEntities() {
409 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000410 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000411
412 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000413 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000414
Douglas Gregor89d99802010-11-30 06:16:57 +0000415 PreprocessingRecord::iterator StartEntity, EndEntity;
416 if (OnlyLocalDecls) {
417 StartEntity = AU->pp_entity_begin();
418 EndEntity = AU->pp_entity_end();
419 } else {
420 StartEntity = PPRec.begin();
421 EndEntity = PPRec.end();
422 }
423
Douglas Gregor788f5a12010-03-20 00:41:21 +0000424 // There is no region of interest; we have to walk everything.
425 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000426 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000427
428 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000429 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000430 std::pair<FileID, unsigned> Begin
431 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
432 std::pair<FileID, unsigned> End
433 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
434
435 // The region of interest spans files; we have to walk everything.
436 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000437 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000438
439 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000440 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000441 if (ByFileMap.empty()) {
442 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000443 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000444 std::pair<FileID, unsigned> P
445 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000446
Douglas Gregor788f5a12010-03-20 00:41:21 +0000447 ByFileMap[P.first].push_back(*E);
448 }
449 }
450
451 return std::make_pair(ByFileMap[Begin.first].begin(),
452 ByFileMap[Begin.first].end());
453}
454
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000456///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457/// \returns true if the visitation should be aborted, false if it
458/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000459bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000460 if (clang_isReference(Cursor.kind)) {
461 // By definition, references have no children.
462 return false;
463 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464
465 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000467 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 if (clang_isDeclaration(Cursor.kind)) {
470 Decl *D = getCursorDecl(Cursor);
471 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000472 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000474
Douglas Gregora59e3902010-01-21 23:27:09 +0000475 if (clang_isStatement(Cursor.kind))
476 return Visit(getCursorStmt(Cursor));
477 if (clang_isExpression(Cursor.kind))
478 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000481 CXTranslationUnit tu = getCursorTU(Cursor);
482 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000483 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
484 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000485 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
486 TLEnd = CXXUnit->top_level_end();
487 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000488 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000489 return true;
490 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 } else if (VisitDeclContext(
492 CXXUnit->getASTContext().getTranslationUnitDecl()))
493 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000494
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000496 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 // FIXME: Once we have the ability to deserialize a preprocessing record,
498 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000499 PreprocessingRecord::iterator E, EEnd;
500 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000502 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000504
Douglas Gregor0396f462010-03-19 05:22:59 +0000505 continue;
506 }
507
508 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000509 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 return true;
511
512 continue;
513 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000514
515 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000516 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000517 return true;
518
519 continue;
520 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 }
522 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000523 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000525
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 return false;
528}
529
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000531 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
532 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533
Ted Kremenek664cffd2010-07-22 11:30:19 +0000534 if (Stmt *Body = B->getBody())
535 return Visit(MakeCXCursor(Body, StmtParent, TU));
536
537 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000538}
539
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000540llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
541 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000542 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543 if (Range.isInvalid())
544 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000545
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000546 switch (CompareRegionOfInterest(Range)) {
547 case RangeBefore:
548 // This declaration comes before the region of interest; skip it.
549 return llvm::Optional<bool>();
550
551 case RangeAfter:
552 // This declaration comes after the region of interest; we're done.
553 return false;
554
555 case RangeOverlap:
556 // This declaration overlaps the region of interest; visit it.
557 break;
558 }
559 }
560 return true;
561}
562
563bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
564 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
565
566 // FIXME: Eventually remove. This part of a hack to support proper
567 // iteration over all Decls contained lexically within an ObjC container.
568 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
569 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
570
571 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000572 Decl *D = *I;
573 if (D->getLexicalDeclContext() != DC)
574 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000575 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000576 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
577 if (!V.hasValue())
578 continue;
579 if (!V.getValue())
580 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000581 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582 return true;
583 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000585}
586
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000587bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
588 llvm_unreachable("Translation units are visited directly by Visit()");
589 return false;
590}
591
592bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
593 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
594 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000596 return false;
597}
598
599bool CursorVisitor::VisitTagDecl(TagDecl *D) {
600 return VisitDeclContext(D);
601}
602
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000603bool CursorVisitor::VisitClassTemplateSpecializationDecl(
604 ClassTemplateSpecializationDecl *D) {
605 bool ShouldVisitBody = false;
606 switch (D->getSpecializationKind()) {
607 case TSK_Undeclared:
608 case TSK_ImplicitInstantiation:
609 // Nothing to visit
610 return false;
611
612 case TSK_ExplicitInstantiationDeclaration:
613 case TSK_ExplicitInstantiationDefinition:
614 break;
615
616 case TSK_ExplicitSpecialization:
617 ShouldVisitBody = true;
618 break;
619 }
620
621 // Visit the template arguments used in the specialization.
622 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
623 TypeLoc TL = SpecType->getTypeLoc();
624 if (TemplateSpecializationTypeLoc *TSTLoc
625 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
626 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
627 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
628 return true;
629 }
630 }
631
632 if (ShouldVisitBody && VisitCXXRecordDecl(D))
633 return true;
634
635 return false;
636}
637
Douglas Gregor74dbe642010-08-31 19:31:58 +0000638bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
639 ClassTemplatePartialSpecializationDecl *D) {
640 // FIXME: Visit the "outer" template parameter lists on the TagDecl
641 // before visiting these template parameters.
642 if (VisitTemplateParameters(D->getTemplateParameters()))
643 return true;
644
645 // Visit the partial specialization arguments.
646 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
647 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
648 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
649 return true;
650
651 return VisitCXXRecordDecl(D);
652}
653
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000654bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000655 // Visit the default argument.
656 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
657 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
658 if (Visit(DefArg->getTypeLoc()))
659 return true;
660
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000661 return false;
662}
663
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000664bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
665 if (Expr *Init = D->getInitExpr())
666 return Visit(MakeCXCursor(Init, StmtParent, TU));
667 return false;
668}
669
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000670bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
671 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
672 if (Visit(TSInfo->getTypeLoc()))
673 return true;
674
675 return false;
676}
677
Douglas Gregora67e03f2010-09-09 21:42:20 +0000678/// \brief Compare two base or member initializers based on their source order.
679static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
680 CXXBaseOrMemberInitializer const * const *X
681 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
682 CXXBaseOrMemberInitializer const * const *Y
683 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
684
685 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
686 return -1;
687 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
688 return 1;
689 else
690 return 0;
691}
692
Douglas Gregorb1373d02010-01-20 20:59:29 +0000693bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000694 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
695 // Visit the function declaration's syntactic components in the order
696 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000697 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000698 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
699
700 // If we have a function declared directly (without the use of a typedef),
701 // visit just the return type. Otherwise, just visit the function's type
702 // now.
703 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
704 (!FTL && Visit(TL)))
705 return true;
706
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000707 // Visit the nested-name-specifier, if present.
708 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
709 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
710 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000711
712 // Visit the declaration name.
713 if (VisitDeclarationNameInfo(ND->getNameInfo()))
714 return true;
715
716 // FIXME: Visit explicitly-specified template arguments!
717
718 // Visit the function parameters, if we have a function type.
719 if (FTL && VisitFunctionTypeLoc(*FTL, true))
720 return true;
721
722 // FIXME: Attributes?
723 }
724
Douglas Gregora67e03f2010-09-09 21:42:20 +0000725 if (ND->isThisDeclarationADefinition()) {
726 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
727 // Find the initializers that were written in the source.
728 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
729 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
730 IEnd = Constructor->init_end();
731 I != IEnd; ++I) {
732 if (!(*I)->isWritten())
733 continue;
734
735 WrittenInits.push_back(*I);
736 }
737
738 // Sort the initializers in source order
739 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
740 &CompareCXXBaseOrMemberInitializers);
741
742 // Visit the initializers in source order
743 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
744 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000745 if (Init->isAnyMemberInitializer()) {
746 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000747 Init->getMemberLocation(), TU)))
748 return true;
749 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
750 if (Visit(BaseInfo->getTypeLoc()))
751 return true;
752 }
753
754 // Visit the initializer value.
755 if (Expr *Initializer = Init->getInit())
756 if (Visit(MakeCXCursor(Initializer, ND, TU)))
757 return true;
758 }
759 }
760
761 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
762 return true;
763 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000764
Douglas Gregorb1373d02010-01-20 20:59:29 +0000765 return false;
766}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000767
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000768bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
769 if (VisitDeclaratorDecl(D))
770 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772 if (Expr *BitWidth = D->getBitWidth())
773 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000774
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000775 return false;
776}
777
778bool CursorVisitor::VisitVarDecl(VarDecl *D) {
779 if (VisitDeclaratorDecl(D))
780 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000781
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000782 if (Expr *Init = D->getInit())
783 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785 return false;
786}
787
Douglas Gregor84b51d72010-09-01 20:16:53 +0000788bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
789 if (VisitDeclaratorDecl(D))
790 return true;
791
792 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
793 if (Expr *DefArg = D->getDefaultArgument())
794 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
795
796 return false;
797}
798
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000799bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
800 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
801 // before visiting these template parameters.
802 if (VisitTemplateParameters(D->getTemplateParameters()))
803 return true;
804
805 return VisitFunctionDecl(D->getTemplatedDecl());
806}
807
Douglas Gregor39d6f072010-08-31 19:02:00 +0000808bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
809 // FIXME: Visit the "outer" template parameter lists on the TagDecl
810 // before visiting these template parameters.
811 if (VisitTemplateParameters(D->getTemplateParameters()))
812 return true;
813
814 return VisitCXXRecordDecl(D->getTemplatedDecl());
815}
816
Douglas Gregor84b51d72010-09-01 20:16:53 +0000817bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
818 if (VisitTemplateParameters(D->getTemplateParameters()))
819 return true;
820
821 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
822 VisitTemplateArgumentLoc(D->getDefaultArgument()))
823 return true;
824
825 return false;
826}
827
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000828bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000829 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
830 if (Visit(TSInfo->getTypeLoc()))
831 return true;
832
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000834 PEnd = ND->param_end();
835 P != PEnd; ++P) {
836 if (Visit(MakeCXCursor(*P, TU)))
837 return true;
838 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 if (ND->isThisDeclarationADefinition() &&
841 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
842 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000843
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000844 return false;
845}
846
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000847namespace {
848 struct ContainerDeclsSort {
849 SourceManager &SM;
850 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
851 bool operator()(Decl *A, Decl *B) {
852 SourceLocation L_A = A->getLocStart();
853 SourceLocation L_B = B->getLocStart();
854 assert(L_A.isValid() && L_B.isValid());
855 return SM.isBeforeInTranslationUnit(L_A, L_B);
856 }
857 };
858}
859
Douglas Gregora59e3902010-01-21 23:27:09 +0000860bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000861 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
862 // an @implementation can lexically contain Decls that are not properly
863 // nested in the AST. When we identify such cases, we need to retrofit
864 // this nesting here.
865 if (!DI_current)
866 return VisitDeclContext(D);
867
868 // Scan the Decls that immediately come after the container
869 // in the current DeclContext. If any fall within the
870 // container's lexical region, stash them into a vector
871 // for later processing.
872 llvm::SmallVector<Decl *, 24> DeclsInContainer;
873 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000874 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000875 if (EndLoc.isValid()) {
876 DeclContext::decl_iterator next = *DI_current;
877 while (++next != DE_current) {
878 Decl *D_next = *next;
879 if (!D_next)
880 break;
881 SourceLocation L = D_next->getLocStart();
882 if (!L.isValid())
883 break;
884 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
885 *DI_current = next;
886 DeclsInContainer.push_back(D_next);
887 continue;
888 }
889 break;
890 }
891 }
892
893 // The common case.
894 if (DeclsInContainer.empty())
895 return VisitDeclContext(D);
896
897 // Get all the Decls in the DeclContext, and sort them with the
898 // additional ones we've collected. Then visit them.
899 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
900 I!=E; ++I) {
901 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000902 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
903 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000904 continue;
905 DeclsInContainer.push_back(subDecl);
906 }
907
908 // Now sort the Decls so that they appear in lexical order.
909 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
910 ContainerDeclsSort(SM));
911
912 // Now visit the decls.
913 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
914 E = DeclsInContainer.end(); I != E; ++I) {
915 CXCursor Cursor = MakeCXCursor(*I, TU);
916 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
917 if (!V.hasValue())
918 continue;
919 if (!V.getValue())
920 return false;
921 if (Visit(Cursor, true))
922 return true;
923 }
924 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000925}
926
Douglas Gregorb1373d02010-01-20 20:59:29 +0000927bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000928 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
929 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000930 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000931
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000932 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
933 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
934 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000935 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000936 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000937
Douglas Gregora59e3902010-01-21 23:27:09 +0000938 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000939}
940
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000941bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
942 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
943 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
944 E = PID->protocol_end(); I != E; ++I, ++PL)
945 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
946 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000947
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000948 return VisitObjCContainerDecl(PID);
949}
950
Ted Kremenek23173d72010-05-18 21:09:07 +0000951bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000952 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000953 return true;
954
Ted Kremenek23173d72010-05-18 21:09:07 +0000955 // FIXME: This implements a workaround with @property declarations also being
956 // installed in the DeclContext for the @interface. Eventually this code
957 // should be removed.
958 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
959 if (!CDecl || !CDecl->IsClassExtension())
960 return false;
961
962 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
963 if (!ID)
964 return false;
965
966 IdentifierInfo *PropertyId = PD->getIdentifier();
967 ObjCPropertyDecl *prevDecl =
968 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
969
970 if (!prevDecl)
971 return false;
972
973 // Visit synthesized methods since they will be skipped when visiting
974 // the @interface.
975 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000976 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000977 if (Visit(MakeCXCursor(MD, TU)))
978 return true;
979
980 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000981 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000982 if (Visit(MakeCXCursor(MD, TU)))
983 return true;
984
985 return false;
986}
987
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000989 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000990 if (D->getSuperClass() &&
991 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000993 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000994 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000996 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
997 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
998 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000999 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001000 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001001
Douglas Gregora59e3902010-01-21 23:27:09 +00001002 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001003}
1004
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001005bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1006 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001007}
1008
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001009bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001010 // 'ID' could be null when dealing with invalid code.
1011 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1012 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001015 return VisitObjCImplDecl(D);
1016}
1017
1018bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1019#if 0
1020 // Issue callbacks for super class.
1021 // FIXME: No source location information!
1022 if (D->getSuperClass() &&
1023 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001025 TU)))
1026 return true;
1027#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029 return VisitObjCImplDecl(D);
1030}
1031
1032bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1033 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1034 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1035 E = D->protocol_end();
1036 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001037 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001038 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039
1040 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001041}
1042
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1044 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1045 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1046 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001048 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001049}
1050
Douglas Gregora4ffd852010-11-17 01:03:52 +00001051bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1052 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1053 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1054
1055 return false;
1056}
1057
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001058bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1059 return VisitDeclContext(D);
1060}
1061
Douglas Gregor69319002010-08-31 23:48:11 +00001062bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001063 // Visit nested-name-specifier.
1064 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1065 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1066 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001067
1068 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1069 D->getTargetNameLoc(), TU));
1070}
1071
Douglas Gregor7e242562010-09-01 19:52:22 +00001072bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001073 // Visit nested-name-specifier.
1074 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1075 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1076 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001077
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001078 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1079 return true;
1080
Douglas Gregor7e242562010-09-01 19:52:22 +00001081 return VisitDeclarationNameInfo(D->getNameInfo());
1082}
1083
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001084bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001085 // Visit nested-name-specifier.
1086 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1087 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1088 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001089
1090 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1091 D->getIdentLocation(), TU));
1092}
1093
Douglas Gregor7e242562010-09-01 19:52:22 +00001094bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001095 // Visit nested-name-specifier.
1096 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1097 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1098 return true;
1099
Douglas Gregor7e242562010-09-01 19:52:22 +00001100 return VisitDeclarationNameInfo(D->getNameInfo());
1101}
1102
1103bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1104 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105 // Visit nested-name-specifier.
1106 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1107 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1108 return true;
1109
Douglas Gregor7e242562010-09-01 19:52:22 +00001110 return false;
1111}
1112
Douglas Gregor01829d32010-08-31 14:41:23 +00001113bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1114 switch (Name.getName().getNameKind()) {
1115 case clang::DeclarationName::Identifier:
1116 case clang::DeclarationName::CXXLiteralOperatorName:
1117 case clang::DeclarationName::CXXOperatorName:
1118 case clang::DeclarationName::CXXUsingDirective:
1119 return false;
1120
1121 case clang::DeclarationName::CXXConstructorName:
1122 case clang::DeclarationName::CXXDestructorName:
1123 case clang::DeclarationName::CXXConversionFunctionName:
1124 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1125 return Visit(TSInfo->getTypeLoc());
1126 return false;
1127
1128 case clang::DeclarationName::ObjCZeroArgSelector:
1129 case clang::DeclarationName::ObjCOneArgSelector:
1130 case clang::DeclarationName::ObjCMultiArgSelector:
1131 // FIXME: Per-identifier location info?
1132 return false;
1133 }
1134
1135 return false;
1136}
1137
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001138bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1139 SourceRange Range) {
1140 // FIXME: This whole routine is a hack to work around the lack of proper
1141 // source information in nested-name-specifiers (PR5791). Since we do have
1142 // a beginning source location, we can visit the first component of the
1143 // nested-name-specifier, if it's a single-token component.
1144 if (!NNS)
1145 return false;
1146
1147 // Get the first component in the nested-name-specifier.
1148 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1149 NNS = Prefix;
1150
1151 switch (NNS->getKind()) {
1152 case NestedNameSpecifier::Namespace:
1153 // FIXME: The token at this source location might actually have been a
1154 // namespace alias, but we don't model that. Lame!
1155 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1156 TU));
1157
1158 case NestedNameSpecifier::TypeSpec: {
1159 // If the type has a form where we know that the beginning of the source
1160 // range matches up with a reference cursor. Visit the appropriate reference
1161 // cursor.
1162 Type *T = NNS->getAsType();
1163 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1164 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1165 if (const TagType *Tag = dyn_cast<TagType>(T))
1166 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1167 if (const TemplateSpecializationType *TST
1168 = dyn_cast<TemplateSpecializationType>(T))
1169 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1170 break;
1171 }
1172
1173 case NestedNameSpecifier::TypeSpecWithTemplate:
1174 case NestedNameSpecifier::Global:
1175 case NestedNameSpecifier::Identifier:
1176 break;
1177 }
1178
1179 return false;
1180}
1181
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001182bool CursorVisitor::VisitTemplateParameters(
1183 const TemplateParameterList *Params) {
1184 if (!Params)
1185 return false;
1186
1187 for (TemplateParameterList::const_iterator P = Params->begin(),
1188 PEnd = Params->end();
1189 P != PEnd; ++P) {
1190 if (Visit(MakeCXCursor(*P, TU)))
1191 return true;
1192 }
1193
1194 return false;
1195}
1196
Douglas Gregor0b36e612010-08-31 20:37:03 +00001197bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1198 switch (Name.getKind()) {
1199 case TemplateName::Template:
1200 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1201
1202 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001203 // Visit the overloaded template set.
1204 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1205 return true;
1206
Douglas Gregor0b36e612010-08-31 20:37:03 +00001207 return false;
1208
1209 case TemplateName::DependentTemplate:
1210 // FIXME: Visit nested-name-specifier.
1211 return false;
1212
1213 case TemplateName::QualifiedTemplate:
1214 // FIXME: Visit nested-name-specifier.
1215 return Visit(MakeCursorTemplateRef(
1216 Name.getAsQualifiedTemplateName()->getDecl(),
1217 Loc, TU));
1218 }
1219
1220 return false;
1221}
1222
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001223bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1224 switch (TAL.getArgument().getKind()) {
1225 case TemplateArgument::Null:
1226 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001227 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001228 return false;
1229
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001230 case TemplateArgument::Type:
1231 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1232 return Visit(TSInfo->getTypeLoc());
1233 return false;
1234
1235 case TemplateArgument::Declaration:
1236 if (Expr *E = TAL.getSourceDeclExpression())
1237 return Visit(MakeCXCursor(E, StmtParent, TU));
1238 return false;
1239
1240 case TemplateArgument::Expression:
1241 if (Expr *E = TAL.getSourceExpression())
1242 return Visit(MakeCXCursor(E, StmtParent, TU));
1243 return false;
1244
1245 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001246 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1247 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001248 }
1249
1250 return false;
1251}
1252
Ted Kremeneka0536d82010-05-07 01:04:29 +00001253bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1254 return VisitDeclContext(D);
1255}
1256
Douglas Gregor01829d32010-08-31 14:41:23 +00001257bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1258 return Visit(TL.getUnqualifiedLoc());
1259}
1260
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001261bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001262 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001263
1264 // Some builtin types (such as Objective-C's "id", "sel", and
1265 // "Class") have associated declarations. Create cursors for those.
1266 QualType VisitType;
1267 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001268 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001269 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001270 case BuiltinType::Char_U:
1271 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001272 case BuiltinType::Char16:
1273 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001274 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001275 case BuiltinType::UInt:
1276 case BuiltinType::ULong:
1277 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001278 case BuiltinType::UInt128:
1279 case BuiltinType::Char_S:
1280 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001281 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001282 case BuiltinType::Short:
1283 case BuiltinType::Int:
1284 case BuiltinType::Long:
1285 case BuiltinType::LongLong:
1286 case BuiltinType::Int128:
1287 case BuiltinType::Float:
1288 case BuiltinType::Double:
1289 case BuiltinType::LongDouble:
1290 case BuiltinType::NullPtr:
1291 case BuiltinType::Overload:
1292 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001293 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001294
1295 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001296 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001297
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001298 case BuiltinType::ObjCId:
1299 VisitType = Context.getObjCIdType();
1300 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001301
1302 case BuiltinType::ObjCClass:
1303 VisitType = Context.getObjCClassType();
1304 break;
1305
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001306 case BuiltinType::ObjCSel:
1307 VisitType = Context.getObjCSelType();
1308 break;
1309 }
1310
1311 if (!VisitType.isNull()) {
1312 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001313 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001314 TU));
1315 }
1316
1317 return false;
1318}
1319
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001320bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1321 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1322}
1323
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001324bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1325 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1326}
1327
1328bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1329 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1330}
1331
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001332bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001333 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001334 // no context information with which we can match up the depth/index in the
1335 // type to the appropriate
1336 return false;
1337}
1338
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001339bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1340 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1341 return true;
1342
John McCallc12c5bb2010-05-15 11:32:37 +00001343 return false;
1344}
1345
1346bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1347 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1348 return true;
1349
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001350 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1351 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1352 TU)))
1353 return true;
1354 }
1355
1356 return false;
1357}
1358
1359bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001360 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001361}
1362
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001363bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1364 return Visit(TL.getInnerLoc());
1365}
1366
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1368 return Visit(TL.getPointeeLoc());
1369}
1370
1371bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1372 return Visit(TL.getPointeeLoc());
1373}
1374
1375bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1376 return Visit(TL.getPointeeLoc());
1377}
1378
1379bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001380 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381}
1382
1383bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385}
1386
Douglas Gregor01829d32010-08-31 14:41:23 +00001387bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1388 bool SkipResultType) {
1389 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390 return true;
1391
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001393 if (Decl *D = TL.getArg(I))
1394 if (Visit(MakeCXCursor(D, TU)))
1395 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001396
1397 return false;
1398}
1399
1400bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1401 if (Visit(TL.getElementLoc()))
1402 return true;
1403
1404 if (Expr *Size = TL.getSizeExpr())
1405 return Visit(MakeCXCursor(Size, StmtParent, TU));
1406
1407 return false;
1408}
1409
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001410bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1411 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001412 // Visit the template name.
1413 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1414 TL.getTemplateNameLoc()))
1415 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001416
1417 // Visit the template arguments.
1418 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1419 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1420 return true;
1421
1422 return false;
1423}
1424
Douglas Gregor2332c112010-01-21 20:48:56 +00001425bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1426 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1427}
1428
1429bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1430 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1431 return Visit(TSInfo->getTypeLoc());
1432
1433 return false;
1434}
1435
Douglas Gregor7536dd52010-12-20 02:24:11 +00001436bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1437 return Visit(TL.getPatternLoc());
1438}
1439
Ted Kremenek3064ef92010-08-27 21:34:58 +00001440bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1441 if (D->isDefinition()) {
1442 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1443 E = D->bases_end(); I != E; ++I) {
1444 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1445 return true;
1446 }
1447 }
1448
1449 return VisitTagDecl(D);
1450}
1451
Ted Kremenek09dfa372010-02-18 05:46:33 +00001452bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001453 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1454 i != e; ++i)
1455 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001456 return true;
1457
1458 return false;
1459}
1460
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001461//===----------------------------------------------------------------------===//
1462// Data-recursive visitor methods.
1463//===----------------------------------------------------------------------===//
1464
Ted Kremenek28a71942010-11-13 00:36:47 +00001465namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001466#define DEF_JOB(NAME, DATA, KIND)\
1467class NAME : public VisitorJob {\
1468public:\
1469 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1470 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001471 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001472};
1473
1474DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1475DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001476DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001477DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001478DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1479 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001480#undef DEF_JOB
1481
1482class DeclVisit : public VisitorJob {
1483public:
1484 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1485 VisitorJob(parent, VisitorJob::DeclVisitKind,
1486 d, isFirst ? (void*) 1 : (void*) 0) {}
1487 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001488 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001489 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001490 Decl *get() const { return static_cast<Decl*>(data[0]); }
1491 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001492};
Ted Kremenek035dc412010-11-13 00:36:50 +00001493class TypeLocVisit : public VisitorJob {
1494public:
1495 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1496 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1497 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1498
1499 static bool classof(const VisitorJob *VJ) {
1500 return VJ->getKind() == TypeLocVisitKind;
1501 }
1502
Ted Kremenek82f3c502010-11-15 22:23:26 +00001503 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001504 QualType T = QualType::getFromOpaquePtr(data[0]);
1505 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001506 }
1507};
1508
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001509class LabelRefVisit : public VisitorJob {
1510public:
1511 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1512 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1513 (void*) labelLoc.getRawEncoding()) {}
1514
1515 static bool classof(const VisitorJob *VJ) {
1516 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1517 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001518 LabelStmt *get() const { return static_cast<LabelStmt*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001519 SourceLocation getLoc() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001520 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); }
1521};
1522class NestedNameSpecifierVisit : public VisitorJob {
1523public:
1524 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1525 CXCursor parent)
1526 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
1527 NS, (void*) R.getBegin().getRawEncoding(),
1528 (void*) R.getEnd().getRawEncoding()) {}
1529 static bool classof(const VisitorJob *VJ) {
1530 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1531 }
1532 NestedNameSpecifier *get() const {
1533 return static_cast<NestedNameSpecifier*>(data[0]);
1534 }
1535 SourceRange getSourceRange() const {
1536 SourceLocation A =
1537 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1538 SourceLocation B =
1539 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1540 return SourceRange(A, B);
1541 }
1542};
1543class DeclarationNameInfoVisit : public VisitorJob {
1544public:
1545 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1546 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1547 static bool classof(const VisitorJob *VJ) {
1548 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1549 }
1550 DeclarationNameInfo get() const {
1551 Stmt *S = static_cast<Stmt*>(data[0]);
1552 switch (S->getStmtClass()) {
1553 default:
1554 llvm_unreachable("Unhandled Stmt");
1555 case Stmt::CXXDependentScopeMemberExprClass:
1556 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1557 case Stmt::DependentScopeDeclRefExprClass:
1558 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1559 }
1560 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001561};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001562class MemberRefVisit : public VisitorJob {
1563public:
1564 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1565 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1566 (void*) L.getRawEncoding()) {}
1567 static bool classof(const VisitorJob *VJ) {
1568 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1569 }
1570 FieldDecl *get() const {
1571 return static_cast<FieldDecl*>(data[0]);
1572 }
1573 SourceLocation getLoc() const {
1574 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1575 }
1576};
Ted Kremenek28a71942010-11-13 00:36:47 +00001577class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1578 VisitorWorkList &WL;
1579 CXCursor Parent;
1580public:
1581 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1582 : WL(wl), Parent(parent) {}
1583
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001584 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001585 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001586 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001587 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001588 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001589 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001590 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001591 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001592 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001593 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001594 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001595 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001596 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001597 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001598 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001599 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001600 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001601 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001602 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1603 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001604 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001605 void VisitIfStmt(IfStmt *If);
1606 void VisitInitListExpr(InitListExpr *IE);
1607 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001608 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001609 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001610 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1611 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001612 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001613 void VisitStmt(Stmt *S);
1614 void VisitSwitchStmt(SwitchStmt *S);
1615 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001616 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001617 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001618 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001619 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001620
1621private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001622 void AddDeclarationNameInfo(Stmt *S);
1623 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001624 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001625 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001626 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001627 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001628 void AddTypeLoc(TypeSourceInfo *TI);
1629 void EnqueueChildren(Stmt *S);
1630};
1631} // end anonyous namespace
1632
Ted Kremenekf64d8032010-11-18 00:02:32 +00001633void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1634 // 'S' should always be non-null, since it comes from the
1635 // statement we are visiting.
1636 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1637}
1638void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1639 SourceRange R) {
1640 if (N)
1641 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1642}
Ted Kremenek28a71942010-11-13 00:36:47 +00001643void EnqueueVisitor::AddStmt(Stmt *S) {
1644 if (S)
1645 WL.push_back(StmtVisit(S, Parent));
1646}
Ted Kremenek035dc412010-11-13 00:36:50 +00001647void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001648 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001649 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001650}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001651void EnqueueVisitor::
1652 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1653 if (A)
1654 WL.push_back(ExplicitTemplateArgsVisit(
1655 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1656}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001657void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1658 if (D)
1659 WL.push_back(MemberRefVisit(D, L, Parent));
1660}
Ted Kremenek28a71942010-11-13 00:36:47 +00001661void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1662 if (TI)
1663 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1664 }
1665void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001666 unsigned size = WL.size();
1667 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1668 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001669 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001670 }
1671 if (size == WL.size())
1672 return;
1673 // Now reverse the entries we just added. This will match the DFS
1674 // ordering performed by the worklist.
1675 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1676 std::reverse(I, E);
1677}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001678void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1679 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1680}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001681void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1682 AddDecl(B->getBlockDecl());
1683}
Ted Kremenek28a71942010-11-13 00:36:47 +00001684void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1685 EnqueueChildren(E);
1686 AddTypeLoc(E->getTypeSourceInfo());
1687}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001688void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1689 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1690 E = S->body_rend(); I != E; ++I) {
1691 AddStmt(*I);
1692 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001693}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001694void EnqueueVisitor::
1695VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1696 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1697 AddDeclarationNameInfo(E);
1698 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1699 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1700 if (!E->isImplicitAccess())
1701 AddStmt(E->getBase());
1702}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001703void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1704 // Enqueue the initializer or constructor arguments.
1705 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1706 AddStmt(E->getConstructorArg(I-1));
1707 // Enqueue the array size, if any.
1708 AddStmt(E->getArraySize());
1709 // Enqueue the allocated type.
1710 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1711 // Enqueue the placement arguments.
1712 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1713 AddStmt(E->getPlacementArg(I-1));
1714}
Ted Kremenek28a71942010-11-13 00:36:47 +00001715void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001716 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1717 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001718 AddStmt(CE->getCallee());
1719 AddStmt(CE->getArg(0));
1720}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001721void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1722 // Visit the name of the type being destroyed.
1723 AddTypeLoc(E->getDestroyedTypeInfo());
1724 // Visit the scope type that looks disturbingly like the nested-name-specifier
1725 // but isn't.
1726 AddTypeLoc(E->getScopeTypeInfo());
1727 // Visit the nested-name-specifier.
1728 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1729 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1730 // Visit base expression.
1731 AddStmt(E->getBase());
1732}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001733void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1734 AddTypeLoc(E->getTypeSourceInfo());
1735}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001736void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1737 EnqueueChildren(E);
1738 AddTypeLoc(E->getTypeSourceInfo());
1739}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001740void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1741 EnqueueChildren(E);
1742 if (E->isTypeOperand())
1743 AddTypeLoc(E->getTypeOperandSourceInfo());
1744}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001745
1746void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1747 *E) {
1748 EnqueueChildren(E);
1749 AddTypeLoc(E->getTypeSourceInfo());
1750}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001751void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1752 EnqueueChildren(E);
1753 if (E->isTypeOperand())
1754 AddTypeLoc(E->getTypeOperandSourceInfo());
1755}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001756void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001757 if (DR->hasExplicitTemplateArgs()) {
1758 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1759 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001760 WL.push_back(DeclRefExprParts(DR, Parent));
1761}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001762void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1763 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1764 AddDeclarationNameInfo(E);
1765 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1766 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1767}
Ted Kremenek035dc412010-11-13 00:36:50 +00001768void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1769 unsigned size = WL.size();
1770 bool isFirst = true;
1771 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1772 D != DEnd; ++D) {
1773 AddDecl(*D, isFirst);
1774 isFirst = false;
1775 }
1776 if (size == WL.size())
1777 return;
1778 // Now reverse the entries we just added. This will match the DFS
1779 // ordering performed by the worklist.
1780 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1781 std::reverse(I, E);
1782}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001783void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1784 AddStmt(E->getInit());
1785 typedef DesignatedInitExpr::Designator Designator;
1786 for (DesignatedInitExpr::reverse_designators_iterator
1787 D = E->designators_rbegin(), DEnd = E->designators_rend();
1788 D != DEnd; ++D) {
1789 if (D->isFieldDesignator()) {
1790 if (FieldDecl *Field = D->getField())
1791 AddMemberRef(Field, D->getFieldLoc());
1792 continue;
1793 }
1794 if (D->isArrayDesignator()) {
1795 AddStmt(E->getArrayIndex(*D));
1796 continue;
1797 }
1798 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1799 AddStmt(E->getArrayRangeEnd(*D));
1800 AddStmt(E->getArrayRangeStart(*D));
1801 }
1802}
Ted Kremenek28a71942010-11-13 00:36:47 +00001803void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1804 EnqueueChildren(E);
1805 AddTypeLoc(E->getTypeInfoAsWritten());
1806}
1807void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1808 AddStmt(FS->getBody());
1809 AddStmt(FS->getInc());
1810 AddStmt(FS->getCond());
1811 AddDecl(FS->getConditionVariable());
1812 AddStmt(FS->getInit());
1813}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001814void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1815 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1816}
Ted Kremenek28a71942010-11-13 00:36:47 +00001817void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1818 AddStmt(If->getElse());
1819 AddStmt(If->getThen());
1820 AddStmt(If->getCond());
1821 AddDecl(If->getConditionVariable());
1822}
1823void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1824 // We care about the syntactic form of the initializer list, only.
1825 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1826 IE = Syntactic;
1827 EnqueueChildren(IE);
1828}
1829void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001830 WL.push_back(MemberExprParts(M, Parent));
1831
1832 // If the base of the member access expression is an implicit 'this', don't
1833 // visit it.
1834 // FIXME: If we ever want to show these implicit accesses, this will be
1835 // unfortunate. However, clang_getCursor() relies on this behavior.
1836 if (CXXThisExpr *This
1837 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1838 if (This->isImplicit())
1839 return;
1840
Ted Kremenek28a71942010-11-13 00:36:47 +00001841 AddStmt(M->getBase());
1842}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001843void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1844 AddTypeLoc(E->getEncodedTypeSourceInfo());
1845}
Ted Kremenek28a71942010-11-13 00:36:47 +00001846void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1847 EnqueueChildren(M);
1848 AddTypeLoc(M->getClassReceiverTypeInfo());
1849}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001850void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1851 // Visit the components of the offsetof expression.
1852 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1853 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1854 const OffsetOfNode &Node = E->getComponent(I-1);
1855 switch (Node.getKind()) {
1856 case OffsetOfNode::Array:
1857 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1858 break;
1859 case OffsetOfNode::Field:
1860 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1861 break;
1862 case OffsetOfNode::Identifier:
1863 case OffsetOfNode::Base:
1864 continue;
1865 }
1866 }
1867 // Visit the type into which we're computing the offset.
1868 AddTypeLoc(E->getTypeSourceInfo());
1869}
Ted Kremenek28a71942010-11-13 00:36:47 +00001870void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001871 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001872 WL.push_back(OverloadExprParts(E, Parent));
1873}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001874void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1875 EnqueueChildren(E);
1876 if (E->isArgumentType())
1877 AddTypeLoc(E->getArgumentTypeInfo());
1878}
Ted Kremenek28a71942010-11-13 00:36:47 +00001879void EnqueueVisitor::VisitStmt(Stmt *S) {
1880 EnqueueChildren(S);
1881}
1882void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1883 AddStmt(S->getBody());
1884 AddStmt(S->getCond());
1885 AddDecl(S->getConditionVariable());
1886}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001887
Ted Kremenek28a71942010-11-13 00:36:47 +00001888void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1889 AddStmt(W->getBody());
1890 AddStmt(W->getCond());
1891 AddDecl(W->getConditionVariable());
1892}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001893void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1894 AddTypeLoc(E->getQueriedTypeSourceInfo());
1895}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001896
1897void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00001898 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00001899 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00001900}
1901
Ted Kremenek28a71942010-11-13 00:36:47 +00001902void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1903 VisitOverloadExpr(U);
1904 if (!U->isImplicitAccess())
1905 AddStmt(U->getBase());
1906}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001907void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1908 AddStmt(E->getSubExpr());
1909 AddTypeLoc(E->getWrittenTypeInfo());
1910}
Ted Kremenek60458782010-11-12 21:34:16 +00001911
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001912void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001913 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001914}
1915
1916bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1917 if (RegionOfInterest.isValid()) {
1918 SourceRange Range = getRawCursorExtent(C);
1919 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1920 return false;
1921 }
1922 return true;
1923}
1924
1925bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1926 while (!WL.empty()) {
1927 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001928 VisitorJob LI = WL.back();
1929 WL.pop_back();
1930
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001931 // Set the Parent field, then back to its old value once we're done.
1932 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1933
1934 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001935 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001936 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001937 if (!D)
1938 continue;
1939
1940 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001941 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001942 return true;
1943
1944 continue;
1945 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001946 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1947 const ExplicitTemplateArgumentList *ArgList =
1948 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1949 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1950 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1951 Arg != ArgEnd; ++Arg) {
1952 if (VisitTemplateArgumentLoc(*Arg))
1953 return true;
1954 }
1955 continue;
1956 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001957 case VisitorJob::TypeLocVisitKind: {
1958 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001959 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001960 return true;
1961 continue;
1962 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001963 case VisitorJob::LabelRefVisitKind: {
1964 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1965 if (Visit(MakeCursorLabelRef(LS,
1966 cast<LabelRefVisit>(&LI)->getLoc(),
1967 TU)))
1968 return true;
1969 continue;
1970 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001971 case VisitorJob::NestedNameSpecifierVisitKind: {
1972 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
1973 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
1974 return true;
1975 continue;
1976 }
1977 case VisitorJob::DeclarationNameInfoVisitKind: {
1978 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
1979 ->get()))
1980 return true;
1981 continue;
1982 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00001983 case VisitorJob::MemberRefVisitKind: {
1984 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
1985 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
1986 return true;
1987 continue;
1988 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001989 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001990 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001991 if (!S)
1992 continue;
1993
Ted Kremenekf1107452010-11-12 18:26:56 +00001994 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001995 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001996 if (!IsInRegionOfInterest(Cursor))
1997 continue;
1998 switch (Visitor(Cursor, Parent, ClientData)) {
1999 case CXChildVisit_Break: return true;
2000 case CXChildVisit_Continue: break;
2001 case CXChildVisit_Recurse:
2002 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002003 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002004 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002005 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002006 }
2007 case VisitorJob::MemberExprPartsKind: {
2008 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002009 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002010
2011 // Visit the nested-name-specifier
2012 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2013 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2014 return true;
2015
2016 // Visit the declaration name.
2017 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2018 return true;
2019
2020 // Visit the explicitly-specified template arguments, if any.
2021 if (M->hasExplicitTemplateArgs()) {
2022 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2023 *ArgEnd = Arg + M->getNumTemplateArgs();
2024 Arg != ArgEnd; ++Arg) {
2025 if (VisitTemplateArgumentLoc(*Arg))
2026 return true;
2027 }
2028 }
2029 continue;
2030 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002031 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002032 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002033 // Visit nested-name-specifier, if present.
2034 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2035 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2036 return true;
2037 // Visit declaration name.
2038 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2039 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002040 continue;
2041 }
Ted Kremenek60458782010-11-12 21:34:16 +00002042 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002043 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002044 // Visit the nested-name-specifier.
2045 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2046 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2047 return true;
2048 // Visit the declaration name.
2049 if (VisitDeclarationNameInfo(O->getNameInfo()))
2050 return true;
2051 // Visit the overloaded declaration reference.
2052 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2053 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002054 continue;
2055 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002056 }
2057 }
2058 return false;
2059}
2060
Ted Kremenekcdba6592010-11-18 00:42:18 +00002061bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002062 VisitorWorkList *WL = 0;
2063 if (!WorkListFreeList.empty()) {
2064 WL = WorkListFreeList.back();
2065 WL->clear();
2066 WorkListFreeList.pop_back();
2067 }
2068 else {
2069 WL = new VisitorWorkList();
2070 WorkListCache.push_back(WL);
2071 }
2072 EnqueueWorkList(*WL, S);
2073 bool result = RunVisitorWorkList(*WL);
2074 WorkListFreeList.push_back(WL);
2075 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002076}
2077
2078//===----------------------------------------------------------------------===//
2079// Misc. API hooks.
2080//===----------------------------------------------------------------------===//
2081
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002082static llvm::sys::Mutex EnableMultithreadingMutex;
2083static bool EnabledMultithreading;
2084
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002085extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002086CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2087 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002088 // Disable pretty stack trace functionality, which will otherwise be a very
2089 // poor citizen of the world and set up all sorts of signal handlers.
2090 llvm::DisablePrettyStackTrace = true;
2091
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002092 // We use crash recovery to make some of our APIs more reliable, implicitly
2093 // enable it.
2094 llvm::CrashRecoveryContext::Enable();
2095
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002096 // Enable support for multithreading in LLVM.
2097 {
2098 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2099 if (!EnabledMultithreading) {
2100 llvm::llvm_start_multithreaded();
2101 EnabledMultithreading = true;
2102 }
2103 }
2104
Douglas Gregora030b7c2010-01-22 20:35:53 +00002105 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002106 if (excludeDeclarationsFromPCH)
2107 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002108 if (displayDiagnostics)
2109 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002110 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002111}
2112
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002113void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002114 if (CIdx)
2115 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002116}
2117
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002118CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002119 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002120 if (!CIdx)
2121 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002122
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002123 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002124 FileSystemOptions FileSystemOpts;
2125 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002126
Douglas Gregor28019772010-04-05 23:52:57 +00002127 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002128 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002129 CXXIdx->getOnlyLocalDecls(),
2130 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002131 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002132}
2133
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002134unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002135 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002136 CXTranslationUnit_CacheCompletionResults |
2137 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002138}
2139
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002140CXTranslationUnit
2141clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2142 const char *source_filename,
2143 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002144 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002145 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002146 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002147 return clang_parseTranslationUnit(CIdx, source_filename,
2148 command_line_args, num_command_line_args,
2149 unsaved_files, num_unsaved_files,
2150 CXTranslationUnit_DetailedPreprocessingRecord);
2151}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002152
2153struct ParseTranslationUnitInfo {
2154 CXIndex CIdx;
2155 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002156 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002157 int num_command_line_args;
2158 struct CXUnsavedFile *unsaved_files;
2159 unsigned num_unsaved_files;
2160 unsigned options;
2161 CXTranslationUnit result;
2162};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002163static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002164 ParseTranslationUnitInfo *PTUI =
2165 static_cast<ParseTranslationUnitInfo*>(UserData);
2166 CXIndex CIdx = PTUI->CIdx;
2167 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002168 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002169 int num_command_line_args = PTUI->num_command_line_args;
2170 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2171 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2172 unsigned options = PTUI->options;
2173 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002174
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002175 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002176 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002177
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002178 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2179
Douglas Gregor44c181a2010-07-23 00:33:23 +00002180 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002181 bool CompleteTranslationUnit
2182 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002183 bool CacheCodeCompetionResults
2184 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002185 bool CXXPrecompilePreamble
2186 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2187 bool CXXChainedPCH
2188 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002189
Douglas Gregor5352ac02010-01-28 00:27:43 +00002190 // Configure the diagnostics.
2191 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002192 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2193 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002194
Douglas Gregor4db64a42010-01-23 00:14:00 +00002195 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2196 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002197 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002198 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002199 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002200 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2201 Buffer));
2202 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002203
Douglas Gregorb10daed2010-10-11 16:52:23 +00002204 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002205
Ted Kremenek139ba862009-10-22 00:03:57 +00002206 // The 'source_filename' argument is optional. If the caller does not
2207 // specify it then it is assumed that the source file is specified
2208 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002209 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002210 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002211
2212 // Since the Clang C library is primarily used by batch tools dealing with
2213 // (often very broken) source code, where spell-checking can have a
2214 // significant negative impact on performance (particularly when
2215 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 // Only do this if we haven't found a spell-checking-related argument.
2217 bool FoundSpellCheckingArgument = false;
2218 for (int I = 0; I != num_command_line_args; ++I) {
2219 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2220 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2221 FoundSpellCheckingArgument = true;
2222 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002223 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002224 }
2225 if (!FoundSpellCheckingArgument)
2226 Args.push_back("-fno-spell-checking");
2227
2228 Args.insert(Args.end(), command_line_args,
2229 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002230
Douglas Gregor44c181a2010-07-23 00:33:23 +00002231 // Do we need the detailed preprocessing record?
2232 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002233 Args.push_back("-Xclang");
2234 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002235 }
2236
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002237 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002238 llvm::OwningPtr<ASTUnit> Unit(
2239 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2240 Diags,
2241 CXXIdx->getClangResourcesPath(),
2242 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002243 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002244 RemappedFiles.data(),
2245 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002246 PrecompilePreamble,
2247 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002248 CacheCodeCompetionResults,
2249 CXXPrecompilePreamble,
2250 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002251
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002252 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002253 // Make sure to check that 'Unit' is non-NULL.
2254 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2255 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2256 DEnd = Unit->stored_diag_end();
2257 D != DEnd; ++D) {
2258 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2259 CXString Msg = clang_formatDiagnostic(&Diag,
2260 clang_defaultDiagnosticDisplayOptions());
2261 fprintf(stderr, "%s\n", clang_getCString(Msg));
2262 clang_disposeString(Msg);
2263 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002264#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002265 // On Windows, force a flush, since there may be multiple copies of
2266 // stderr and stdout in the file system, all with different buffers
2267 // but writing to the same device.
2268 fflush(stderr);
2269#endif
2270 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002271 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002272
Ted Kremeneka60ed472010-11-16 08:15:36 +00002273 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002274}
2275CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2276 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002277 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002278 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002279 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002280 unsigned num_unsaved_files,
2281 unsigned options) {
2282 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002283 num_command_line_args, unsaved_files,
2284 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002285 llvm::CrashRecoveryContext CRC;
2286
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002287 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002288 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2289 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2290 fprintf(stderr, " 'command_line_args' : [");
2291 for (int i = 0; i != num_command_line_args; ++i) {
2292 if (i)
2293 fprintf(stderr, ", ");
2294 fprintf(stderr, "'%s'", command_line_args[i]);
2295 }
2296 fprintf(stderr, "],\n");
2297 fprintf(stderr, " 'unsaved_files' : [");
2298 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2299 if (i)
2300 fprintf(stderr, ", ");
2301 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2302 unsaved_files[i].Length);
2303 }
2304 fprintf(stderr, "],\n");
2305 fprintf(stderr, " 'options' : %d,\n", options);
2306 fprintf(stderr, "}\n");
2307
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002308 return 0;
2309 }
2310
2311 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002312}
2313
Douglas Gregor19998442010-08-13 15:35:05 +00002314unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2315 return CXSaveTranslationUnit_None;
2316}
2317
2318int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2319 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002320 if (!TU)
2321 return 1;
2322
Ted Kremeneka60ed472010-11-16 08:15:36 +00002323 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002324}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002325
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002326void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002327 if (CTUnit) {
2328 // If the translation unit has been marked as unsafe to free, just discard
2329 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002330 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002331 return;
2332
Ted Kremeneka60ed472010-11-16 08:15:36 +00002333 delete static_cast<ASTUnit *>(CTUnit->TUData);
2334 disposeCXStringPool(CTUnit->StringPool);
2335 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002336 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002337}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002338
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002339unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2340 return CXReparse_None;
2341}
2342
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002343struct ReparseTranslationUnitInfo {
2344 CXTranslationUnit TU;
2345 unsigned num_unsaved_files;
2346 struct CXUnsavedFile *unsaved_files;
2347 unsigned options;
2348 int result;
2349};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002350
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002351static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002352 ReparseTranslationUnitInfo *RTUI =
2353 static_cast<ReparseTranslationUnitInfo*>(UserData);
2354 CXTranslationUnit TU = RTUI->TU;
2355 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2356 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2357 unsigned options = RTUI->options;
2358 (void) options;
2359 RTUI->result = 1;
2360
Douglas Gregorabc563f2010-07-19 21:46:24 +00002361 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002362 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002363
Ted Kremeneka60ed472010-11-16 08:15:36 +00002364 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002365 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002366
2367 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2368 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2369 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2370 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002371 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002372 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2373 Buffer));
2374 }
2375
Douglas Gregor593b0c12010-09-23 18:47:53 +00002376 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2377 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002378}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002379
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002380int clang_reparseTranslationUnit(CXTranslationUnit TU,
2381 unsigned num_unsaved_files,
2382 struct CXUnsavedFile *unsaved_files,
2383 unsigned options) {
2384 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2385 options, 0 };
2386 llvm::CrashRecoveryContext CRC;
2387
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002388 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002389 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002390 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002391 return 1;
2392 }
2393
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002394
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002395 return RTUI.result;
2396}
2397
Douglas Gregordf95a132010-08-09 20:45:32 +00002398
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002399CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002400 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002401 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002402
Ted Kremeneka60ed472010-11-16 08:15:36 +00002403 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002404 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002405}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002406
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002407CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002408 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002409 return Result;
2410}
2411
Ted Kremenekfb480492010-01-13 21:46:36 +00002412} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002413
Ted Kremenekfb480492010-01-13 21:46:36 +00002414//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002415// CXSourceLocation and CXSourceRange Operations.
2416//===----------------------------------------------------------------------===//
2417
Douglas Gregorb9790342010-01-22 21:44:22 +00002418extern "C" {
2419CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002420 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002421 return Result;
2422}
2423
2424unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002425 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2426 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2427 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002428}
2429
2430CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2431 CXFile file,
2432 unsigned line,
2433 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002434 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002435 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002436
Ted Kremeneka60ed472010-11-16 08:15:36 +00002437 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002438 SourceLocation SLoc
2439 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002440 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002441 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002442 if (SLoc.isInvalid()) return clang_getNullLocation();
2443
2444 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2445}
2446
2447CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2448 CXFile file,
2449 unsigned offset) {
2450 if (!tu || !file)
2451 return clang_getNullLocation();
2452
Ted Kremeneka60ed472010-11-16 08:15:36 +00002453 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002454 SourceLocation Start
2455 = CXXUnit->getSourceManager().getLocation(
2456 static_cast<const FileEntry *>(file),
2457 1, 1);
2458 if (Start.isInvalid()) return clang_getNullLocation();
2459
2460 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2461
2462 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002463
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002464 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002465}
2466
Douglas Gregor5352ac02010-01-28 00:27:43 +00002467CXSourceRange clang_getNullRange() {
2468 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2469 return Result;
2470}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002471
Douglas Gregor5352ac02010-01-28 00:27:43 +00002472CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2473 if (begin.ptr_data[0] != end.ptr_data[0] ||
2474 begin.ptr_data[1] != end.ptr_data[1])
2475 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002476
2477 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002478 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002479 return Result;
2480}
2481
Douglas Gregor46766dc2010-01-26 19:19:08 +00002482void clang_getInstantiationLocation(CXSourceLocation location,
2483 CXFile *file,
2484 unsigned *line,
2485 unsigned *column,
2486 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002487 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2488
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002489 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002490 if (file)
2491 *file = 0;
2492 if (line)
2493 *line = 0;
2494 if (column)
2495 *column = 0;
2496 if (offset)
2497 *offset = 0;
2498 return;
2499 }
2500
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002501 const SourceManager &SM =
2502 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002503 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002504
2505 if (file)
2506 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2507 if (line)
2508 *line = SM.getInstantiationLineNumber(InstLoc);
2509 if (column)
2510 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002511 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002512 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002513}
2514
Douglas Gregora9b06d42010-11-09 06:24:54 +00002515void clang_getSpellingLocation(CXSourceLocation location,
2516 CXFile *file,
2517 unsigned *line,
2518 unsigned *column,
2519 unsigned *offset) {
2520 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2521
2522 if (!location.ptr_data[0] || Loc.isInvalid()) {
2523 if (file)
2524 *file = 0;
2525 if (line)
2526 *line = 0;
2527 if (column)
2528 *column = 0;
2529 if (offset)
2530 *offset = 0;
2531 return;
2532 }
2533
2534 const SourceManager &SM =
2535 *static_cast<const SourceManager*>(location.ptr_data[0]);
2536 SourceLocation SpellLoc = Loc;
2537 if (SpellLoc.isMacroID()) {
2538 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2539 if (SimpleSpellingLoc.isFileID() &&
2540 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2541 SpellLoc = SimpleSpellingLoc;
2542 else
2543 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2544 }
2545
2546 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2547 FileID FID = LocInfo.first;
2548 unsigned FileOffset = LocInfo.second;
2549
2550 if (file)
2551 *file = (void *)SM.getFileEntryForID(FID);
2552 if (line)
2553 *line = SM.getLineNumber(FID, FileOffset);
2554 if (column)
2555 *column = SM.getColumnNumber(FID, FileOffset);
2556 if (offset)
2557 *offset = FileOffset;
2558}
2559
Douglas Gregor1db19de2010-01-19 21:36:55 +00002560CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002561 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002562 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002563 return Result;
2564}
2565
2566CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002567 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002568 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002569 return Result;
2570}
2571
Douglas Gregorb9790342010-01-22 21:44:22 +00002572} // end: extern "C"
2573
Douglas Gregor1db19de2010-01-19 21:36:55 +00002574//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002575// CXFile Operations.
2576//===----------------------------------------------------------------------===//
2577
2578extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002579CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002580 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002581 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582
Steve Naroff88145032009-10-27 14:35:18 +00002583 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002584 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002585}
2586
2587time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002588 if (!SFile)
2589 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590
Steve Naroff88145032009-10-27 14:35:18 +00002591 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2592 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002593}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002594
Douglas Gregorb9790342010-01-22 21:44:22 +00002595CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2596 if (!tu)
2597 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Ted Kremeneka60ed472010-11-16 08:15:36 +00002599 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002600
Douglas Gregorb9790342010-01-22 21:44:22 +00002601 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002602 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002603}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002604
Ted Kremenekfb480492010-01-13 21:46:36 +00002605} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002606
Ted Kremenekfb480492010-01-13 21:46:36 +00002607//===----------------------------------------------------------------------===//
2608// CXCursor Operations.
2609//===----------------------------------------------------------------------===//
2610
Ted Kremenekfb480492010-01-13 21:46:36 +00002611static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002612 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2613 return getDeclFromExpr(CE->getSubExpr());
2614
Ted Kremenekfb480492010-01-13 21:46:36 +00002615 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2616 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002617 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2618 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002619 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2620 return ME->getMemberDecl();
2621 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2622 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002623 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002624 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002625
Ted Kremenekfb480492010-01-13 21:46:36 +00002626 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2627 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002628 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2629 if (!CE->isElidable())
2630 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002631 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2632 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002633
Douglas Gregordb1314e2010-10-01 21:11:22 +00002634 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2635 return PE->getProtocol();
2636
Ted Kremenekfb480492010-01-13 21:46:36 +00002637 return 0;
2638}
2639
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002640static SourceLocation getLocationFromExpr(Expr *E) {
2641 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2642 return /*FIXME:*/Msg->getLeftLoc();
2643 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2644 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002645 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2646 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002647 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2648 return Member->getMemberLoc();
2649 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2650 return Ivar->getLocation();
2651 return E->getLocStart();
2652}
2653
Ted Kremenekfb480492010-01-13 21:46:36 +00002654extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002655
2656unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002657 CXCursorVisitor visitor,
2658 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002659 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2660 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002661 return CursorVis.VisitChildren(parent);
2662}
2663
David Chisnall3387c652010-11-03 14:12:26 +00002664#ifndef __has_feature
2665#define __has_feature(x) 0
2666#endif
2667#if __has_feature(blocks)
2668typedef enum CXChildVisitResult
2669 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2670
2671static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2672 CXClientData client_data) {
2673 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2674 return block(cursor, parent);
2675}
2676#else
2677// If we are compiled with a compiler that doesn't have native blocks support,
2678// define and call the block manually, so the
2679typedef struct _CXChildVisitResult
2680{
2681 void *isa;
2682 int flags;
2683 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002684 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2685 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002686} *CXCursorVisitorBlock;
2687
2688static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2689 CXClientData client_data) {
2690 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2691 return block->invoke(block, cursor, parent);
2692}
2693#endif
2694
2695
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002696unsigned clang_visitChildrenWithBlock(CXCursor parent,
2697 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002698 return clang_visitChildren(parent, visitWithBlock, block);
2699}
2700
Douglas Gregor78205d42010-01-20 21:45:58 +00002701static CXString getDeclSpelling(Decl *D) {
2702 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002703 if (!ND) {
2704 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2705 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2706 return createCXString(Property->getIdentifier()->getName());
2707
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002708 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002709 }
2710
Douglas Gregor78205d42010-01-20 21:45:58 +00002711 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002712 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002713
Douglas Gregor78205d42010-01-20 21:45:58 +00002714 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2715 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2716 // and returns different names. NamedDecl returns the class name and
2717 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002718 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002719
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002720 if (isa<UsingDirectiveDecl>(D))
2721 return createCXString("");
2722
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002723 llvm::SmallString<1024> S;
2724 llvm::raw_svector_ostream os(S);
2725 ND->printName(os);
2726
2727 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002728}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002729
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002730CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002731 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002732 return clang_getTranslationUnitSpelling(
2733 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002734
Steve Narofff334b4e2009-09-02 18:26:48 +00002735 if (clang_isReference(C.kind)) {
2736 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002737 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002738 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002739 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002740 }
2741 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002742 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002743 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002744 }
2745 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002746 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002747 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002748 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002749 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002750 case CXCursor_CXXBaseSpecifier: {
2751 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2752 return createCXString(B->getType().getAsString());
2753 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002754 case CXCursor_TypeRef: {
2755 TypeDecl *Type = getCursorTypeRef(C).first;
2756 assert(Type && "Missing type decl");
2757
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002758 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2759 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002760 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002761 case CXCursor_TemplateRef: {
2762 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002763 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002764
2765 return createCXString(Template->getNameAsString());
2766 }
Douglas Gregor69319002010-08-31 23:48:11 +00002767
2768 case CXCursor_NamespaceRef: {
2769 NamedDecl *NS = getCursorNamespaceRef(C).first;
2770 assert(NS && "Missing namespace decl");
2771
2772 return createCXString(NS->getNameAsString());
2773 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002774
Douglas Gregora67e03f2010-09-09 21:42:20 +00002775 case CXCursor_MemberRef: {
2776 FieldDecl *Field = getCursorMemberRef(C).first;
2777 assert(Field && "Missing member decl");
2778
2779 return createCXString(Field->getNameAsString());
2780 }
2781
Douglas Gregor36897b02010-09-10 00:22:18 +00002782 case CXCursor_LabelRef: {
2783 LabelStmt *Label = getCursorLabelRef(C).first;
2784 assert(Label && "Missing label");
2785
2786 return createCXString(Label->getID()->getName());
2787 }
2788
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002789 case CXCursor_OverloadedDeclRef: {
2790 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2791 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2792 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2793 return createCXString(ND->getNameAsString());
2794 return createCXString("");
2795 }
2796 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2797 return createCXString(E->getName().getAsString());
2798 OverloadedTemplateStorage *Ovl
2799 = Storage.get<OverloadedTemplateStorage*>();
2800 if (Ovl->size() == 0)
2801 return createCXString("");
2802 return createCXString((*Ovl->begin())->getNameAsString());
2803 }
2804
Daniel Dunbaracca7252009-11-30 20:42:49 +00002805 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002806 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002807 }
2808 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002809
2810 if (clang_isExpression(C.kind)) {
2811 Decl *D = getDeclFromExpr(getCursorExpr(C));
2812 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002813 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002814 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002815 }
2816
Douglas Gregor36897b02010-09-10 00:22:18 +00002817 if (clang_isStatement(C.kind)) {
2818 Stmt *S = getCursorStmt(C);
2819 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2820 return createCXString(Label->getID()->getName());
2821
2822 return createCXString("");
2823 }
2824
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002825 if (C.kind == CXCursor_MacroInstantiation)
2826 return createCXString(getCursorMacroInstantiation(C)->getName()
2827 ->getNameStart());
2828
Douglas Gregor572feb22010-03-18 18:04:21 +00002829 if (C.kind == CXCursor_MacroDefinition)
2830 return createCXString(getCursorMacroDefinition(C)->getName()
2831 ->getNameStart());
2832
Douglas Gregorecdcb882010-10-20 22:00:55 +00002833 if (C.kind == CXCursor_InclusionDirective)
2834 return createCXString(getCursorInclusionDirective(C)->getFileName());
2835
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002836 if (clang_isDeclaration(C.kind))
2837 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002838
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002839 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002840}
2841
Douglas Gregor358559d2010-10-02 22:49:11 +00002842CXString clang_getCursorDisplayName(CXCursor C) {
2843 if (!clang_isDeclaration(C.kind))
2844 return clang_getCursorSpelling(C);
2845
2846 Decl *D = getCursorDecl(C);
2847 if (!D)
2848 return createCXString("");
2849
2850 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2851 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2852 D = FunTmpl->getTemplatedDecl();
2853
2854 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2855 llvm::SmallString<64> Str;
2856 llvm::raw_svector_ostream OS(Str);
2857 OS << Function->getNameAsString();
2858 if (Function->getPrimaryTemplate())
2859 OS << "<>";
2860 OS << "(";
2861 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2862 if (I)
2863 OS << ", ";
2864 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2865 }
2866
2867 if (Function->isVariadic()) {
2868 if (Function->getNumParams())
2869 OS << ", ";
2870 OS << "...";
2871 }
2872 OS << ")";
2873 return createCXString(OS.str());
2874 }
2875
2876 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2877 llvm::SmallString<64> Str;
2878 llvm::raw_svector_ostream OS(Str);
2879 OS << ClassTemplate->getNameAsString();
2880 OS << "<";
2881 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2882 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2883 if (I)
2884 OS << ", ";
2885
2886 NamedDecl *Param = Params->getParam(I);
2887 if (Param->getIdentifier()) {
2888 OS << Param->getIdentifier()->getName();
2889 continue;
2890 }
2891
2892 // There is no parameter name, which makes this tricky. Try to come up
2893 // with something useful that isn't too long.
2894 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2895 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2896 else if (NonTypeTemplateParmDecl *NTTP
2897 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2898 OS << NTTP->getType().getAsString(Policy);
2899 else
2900 OS << "template<...> class";
2901 }
2902
2903 OS << ">";
2904 return createCXString(OS.str());
2905 }
2906
2907 if (ClassTemplateSpecializationDecl *ClassSpec
2908 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2909 // If the type was explicitly written, use that.
2910 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2911 return createCXString(TSInfo->getType().getAsString(Policy));
2912
2913 llvm::SmallString<64> Str;
2914 llvm::raw_svector_ostream OS(Str);
2915 OS << ClassSpec->getNameAsString();
2916 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002917 ClassSpec->getTemplateArgs().data(),
2918 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002919 Policy);
2920 return createCXString(OS.str());
2921 }
2922
2923 return clang_getCursorSpelling(C);
2924}
2925
Ted Kremeneke68fff62010-02-17 00:41:32 +00002926CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002927 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002928 case CXCursor_FunctionDecl:
2929 return createCXString("FunctionDecl");
2930 case CXCursor_TypedefDecl:
2931 return createCXString("TypedefDecl");
2932 case CXCursor_EnumDecl:
2933 return createCXString("EnumDecl");
2934 case CXCursor_EnumConstantDecl:
2935 return createCXString("EnumConstantDecl");
2936 case CXCursor_StructDecl:
2937 return createCXString("StructDecl");
2938 case CXCursor_UnionDecl:
2939 return createCXString("UnionDecl");
2940 case CXCursor_ClassDecl:
2941 return createCXString("ClassDecl");
2942 case CXCursor_FieldDecl:
2943 return createCXString("FieldDecl");
2944 case CXCursor_VarDecl:
2945 return createCXString("VarDecl");
2946 case CXCursor_ParmDecl:
2947 return createCXString("ParmDecl");
2948 case CXCursor_ObjCInterfaceDecl:
2949 return createCXString("ObjCInterfaceDecl");
2950 case CXCursor_ObjCCategoryDecl:
2951 return createCXString("ObjCCategoryDecl");
2952 case CXCursor_ObjCProtocolDecl:
2953 return createCXString("ObjCProtocolDecl");
2954 case CXCursor_ObjCPropertyDecl:
2955 return createCXString("ObjCPropertyDecl");
2956 case CXCursor_ObjCIvarDecl:
2957 return createCXString("ObjCIvarDecl");
2958 case CXCursor_ObjCInstanceMethodDecl:
2959 return createCXString("ObjCInstanceMethodDecl");
2960 case CXCursor_ObjCClassMethodDecl:
2961 return createCXString("ObjCClassMethodDecl");
2962 case CXCursor_ObjCImplementationDecl:
2963 return createCXString("ObjCImplementationDecl");
2964 case CXCursor_ObjCCategoryImplDecl:
2965 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002966 case CXCursor_CXXMethod:
2967 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002968 case CXCursor_UnexposedDecl:
2969 return createCXString("UnexposedDecl");
2970 case CXCursor_ObjCSuperClassRef:
2971 return createCXString("ObjCSuperClassRef");
2972 case CXCursor_ObjCProtocolRef:
2973 return createCXString("ObjCProtocolRef");
2974 case CXCursor_ObjCClassRef:
2975 return createCXString("ObjCClassRef");
2976 case CXCursor_TypeRef:
2977 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002978 case CXCursor_TemplateRef:
2979 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002980 case CXCursor_NamespaceRef:
2981 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002982 case CXCursor_MemberRef:
2983 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002984 case CXCursor_LabelRef:
2985 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002986 case CXCursor_OverloadedDeclRef:
2987 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002988 case CXCursor_UnexposedExpr:
2989 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002990 case CXCursor_BlockExpr:
2991 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002992 case CXCursor_DeclRefExpr:
2993 return createCXString("DeclRefExpr");
2994 case CXCursor_MemberRefExpr:
2995 return createCXString("MemberRefExpr");
2996 case CXCursor_CallExpr:
2997 return createCXString("CallExpr");
2998 case CXCursor_ObjCMessageExpr:
2999 return createCXString("ObjCMessageExpr");
3000 case CXCursor_UnexposedStmt:
3001 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003002 case CXCursor_LabelStmt:
3003 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003004 case CXCursor_InvalidFile:
3005 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003006 case CXCursor_InvalidCode:
3007 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003008 case CXCursor_NoDeclFound:
3009 return createCXString("NoDeclFound");
3010 case CXCursor_NotImplemented:
3011 return createCXString("NotImplemented");
3012 case CXCursor_TranslationUnit:
3013 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003014 case CXCursor_UnexposedAttr:
3015 return createCXString("UnexposedAttr");
3016 case CXCursor_IBActionAttr:
3017 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003018 case CXCursor_IBOutletAttr:
3019 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003020 case CXCursor_IBOutletCollectionAttr:
3021 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003022 case CXCursor_PreprocessingDirective:
3023 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003024 case CXCursor_MacroDefinition:
3025 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003026 case CXCursor_MacroInstantiation:
3027 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003028 case CXCursor_InclusionDirective:
3029 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003030 case CXCursor_Namespace:
3031 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003032 case CXCursor_LinkageSpec:
3033 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003034 case CXCursor_CXXBaseSpecifier:
3035 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003036 case CXCursor_Constructor:
3037 return createCXString("CXXConstructor");
3038 case CXCursor_Destructor:
3039 return createCXString("CXXDestructor");
3040 case CXCursor_ConversionFunction:
3041 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003042 case CXCursor_TemplateTypeParameter:
3043 return createCXString("TemplateTypeParameter");
3044 case CXCursor_NonTypeTemplateParameter:
3045 return createCXString("NonTypeTemplateParameter");
3046 case CXCursor_TemplateTemplateParameter:
3047 return createCXString("TemplateTemplateParameter");
3048 case CXCursor_FunctionTemplate:
3049 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003050 case CXCursor_ClassTemplate:
3051 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003052 case CXCursor_ClassTemplatePartialSpecialization:
3053 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003054 case CXCursor_NamespaceAlias:
3055 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003056 case CXCursor_UsingDirective:
3057 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003058 case CXCursor_UsingDeclaration:
3059 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003060 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003061
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003062 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003063 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003064}
Steve Naroff89922f82009-08-31 00:59:03 +00003065
Ted Kremeneke68fff62010-02-17 00:41:32 +00003066enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3067 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003068 CXClientData client_data) {
3069 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003070
3071 // If our current best cursor is the construction of a temporary object,
3072 // don't replace that cursor with a type reference, because we want
3073 // clang_getCursor() to point at the constructor.
3074 if (clang_isExpression(BestCursor->kind) &&
3075 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3076 cursor.kind == CXCursor_TypeRef)
3077 return CXChildVisit_Recurse;
3078
Douglas Gregor85fe1562010-12-10 07:23:11 +00003079 // Don't override a preprocessing cursor with another preprocessing
3080 // cursor; we want the outermost preprocessing cursor.
3081 if (clang_isPreprocessing(cursor.kind) &&
3082 clang_isPreprocessing(BestCursor->kind))
3083 return CXChildVisit_Recurse;
3084
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003085 *BestCursor = cursor;
3086 return CXChildVisit_Recurse;
3087}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003088
Douglas Gregorb9790342010-01-22 21:44:22 +00003089CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3090 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003091 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003092
Ted Kremeneka60ed472010-11-16 08:15:36 +00003093 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003094 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3095
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003096 // Translate the given source location to make it point at the beginning of
3097 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003098 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003099
3100 // Guard against an invalid SourceLocation, or we may assert in one
3101 // of the following calls.
3102 if (SLoc.isInvalid())
3103 return clang_getNullCursor();
3104
Douglas Gregor40749ee2010-11-03 00:35:38 +00003105 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003106 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3107 CXXUnit->getASTContext().getLangOptions());
3108
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003109 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3110 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003111 // FIXME: Would be great to have a "hint" cursor, then walk from that
3112 // hint cursor upward until we find a cursor whose source range encloses
3113 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003114 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3115 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003116 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003117 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003118 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003119
3120 if (Logging) {
3121 CXFile SearchFile;
3122 unsigned SearchLine, SearchColumn;
3123 CXFile ResultFile;
3124 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003125 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3126 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003127 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3128
3129 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3130 0);
3131 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3132 &ResultColumn, 0);
3133 SearchFileName = clang_getFileName(SearchFile);
3134 ResultFileName = clang_getFileName(ResultFile);
3135 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003136 USR = clang_getCursorUSR(Result);
3137 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003138 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3139 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003140 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3141 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003142 clang_disposeString(SearchFileName);
3143 clang_disposeString(ResultFileName);
3144 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003145 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003146
3147 CXCursor Definition = clang_getCursorDefinition(Result);
3148 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3149 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3150 CXString DefinitionKindSpelling
3151 = clang_getCursorKindSpelling(Definition.kind);
3152 CXFile DefinitionFile;
3153 unsigned DefinitionLine, DefinitionColumn;
3154 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3155 &DefinitionLine, &DefinitionColumn, 0);
3156 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3157 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3158 clang_getCString(DefinitionKindSpelling),
3159 clang_getCString(DefinitionFileName),
3160 DefinitionLine, DefinitionColumn);
3161 clang_disposeString(DefinitionFileName);
3162 clang_disposeString(DefinitionKindSpelling);
3163 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003164 }
3165
Ted Kremeneke68fff62010-02-17 00:41:32 +00003166 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003167}
3168
Ted Kremenek73885552009-11-17 19:28:59 +00003169CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003170 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003171}
3172
3173unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003174 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003175}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003176
Douglas Gregor9ce55842010-11-20 00:09:34 +00003177unsigned clang_hashCursor(CXCursor C) {
3178 unsigned Index = 0;
3179 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3180 Index = 1;
3181
3182 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3183 std::make_pair(C.kind, C.data[Index]));
3184}
3185
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003186unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003187 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3188}
3189
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003190unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003191 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3192}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003193
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003194unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003195 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3196}
3197
Douglas Gregor97b98722010-01-19 23:20:36 +00003198unsigned clang_isExpression(enum CXCursorKind K) {
3199 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3200}
3201
3202unsigned clang_isStatement(enum CXCursorKind K) {
3203 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3204}
3205
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003206unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3207 return K == CXCursor_TranslationUnit;
3208}
3209
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003210unsigned clang_isPreprocessing(enum CXCursorKind K) {
3211 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3212}
3213
Ted Kremenekad6eff62010-03-08 21:17:29 +00003214unsigned clang_isUnexposed(enum CXCursorKind K) {
3215 switch (K) {
3216 case CXCursor_UnexposedDecl:
3217 case CXCursor_UnexposedExpr:
3218 case CXCursor_UnexposedStmt:
3219 case CXCursor_UnexposedAttr:
3220 return true;
3221 default:
3222 return false;
3223 }
3224}
3225
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003226CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003227 return C.kind;
3228}
3229
Douglas Gregor98258af2010-01-18 22:46:11 +00003230CXSourceLocation clang_getCursorLocation(CXCursor C) {
3231 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003232 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003233 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003234 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3235 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003236 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003237 }
3238
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003239 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003240 std::pair<ObjCProtocolDecl *, SourceLocation> P
3241 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003242 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003243 }
3244
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003245 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003246 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3247 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003248 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003249 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003250
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003251 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003252 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003253 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003254 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003255
3256 case CXCursor_TemplateRef: {
3257 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3258 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3259 }
3260
Douglas Gregor69319002010-08-31 23:48:11 +00003261 case CXCursor_NamespaceRef: {
3262 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3263 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3264 }
3265
Douglas Gregora67e03f2010-09-09 21:42:20 +00003266 case CXCursor_MemberRef: {
3267 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3268 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3269 }
3270
Ted Kremenek3064ef92010-08-27 21:34:58 +00003271 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003272 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3273 if (!BaseSpec)
3274 return clang_getNullLocation();
3275
3276 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3277 return cxloc::translateSourceLocation(getCursorContext(C),
3278 TSInfo->getTypeLoc().getBeginLoc());
3279
3280 return cxloc::translateSourceLocation(getCursorContext(C),
3281 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003282 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003283
Douglas Gregor36897b02010-09-10 00:22:18 +00003284 case CXCursor_LabelRef: {
3285 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3286 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3287 }
3288
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003289 case CXCursor_OverloadedDeclRef:
3290 return cxloc::translateSourceLocation(getCursorContext(C),
3291 getCursorOverloadedDeclRef(C).second);
3292
Douglas Gregorf46034a2010-01-18 23:41:10 +00003293 default:
3294 // FIXME: Need a way to enumerate all non-reference cases.
3295 llvm_unreachable("Missed a reference kind");
3296 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003297 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003298
3299 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003300 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003301 getLocationFromExpr(getCursorExpr(C)));
3302
Douglas Gregor36897b02010-09-10 00:22:18 +00003303 if (clang_isStatement(C.kind))
3304 return cxloc::translateSourceLocation(getCursorContext(C),
3305 getCursorStmt(C)->getLocStart());
3306
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003307 if (C.kind == CXCursor_PreprocessingDirective) {
3308 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3309 return cxloc::translateSourceLocation(getCursorContext(C), L);
3310 }
Douglas Gregor48072312010-03-18 15:23:44 +00003311
3312 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003313 SourceLocation L
3314 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003315 return cxloc::translateSourceLocation(getCursorContext(C), L);
3316 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003317
3318 if (C.kind == CXCursor_MacroDefinition) {
3319 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3320 return cxloc::translateSourceLocation(getCursorContext(C), L);
3321 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003322
3323 if (C.kind == CXCursor_InclusionDirective) {
3324 SourceLocation L
3325 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3326 return cxloc::translateSourceLocation(getCursorContext(C), L);
3327 }
3328
Ted Kremenek9a700d22010-05-12 06:16:13 +00003329 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003330 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003331
Douglas Gregorf46034a2010-01-18 23:41:10 +00003332 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003333 SourceLocation Loc = D->getLocation();
3334 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3335 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003336 // FIXME: Multiple variables declared in a single declaration
3337 // currently lack the information needed to correctly determine their
3338 // ranges when accounting for the type-specifier. We use context
3339 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3340 // and if so, whether it is the first decl.
3341 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3342 if (!cxcursor::isFirstInDeclGroup(C))
3343 Loc = VD->getLocation();
3344 }
3345
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003346 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003347}
Douglas Gregora7bde202010-01-19 00:34:46 +00003348
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003349} // end extern "C"
3350
3351static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003352 if (clang_isReference(C.kind)) {
3353 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003354 case CXCursor_ObjCSuperClassRef:
3355 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003357 case CXCursor_ObjCProtocolRef:
3358 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003359
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003360 case CXCursor_ObjCClassRef:
3361 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003362
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003363 case CXCursor_TypeRef:
3364 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003365
3366 case CXCursor_TemplateRef:
3367 return getCursorTemplateRef(C).second;
3368
Douglas Gregor69319002010-08-31 23:48:11 +00003369 case CXCursor_NamespaceRef:
3370 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003371
3372 case CXCursor_MemberRef:
3373 return getCursorMemberRef(C).second;
3374
Ted Kremenek3064ef92010-08-27 21:34:58 +00003375 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003376 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003377
Douglas Gregor36897b02010-09-10 00:22:18 +00003378 case CXCursor_LabelRef:
3379 return getCursorLabelRef(C).second;
3380
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003381 case CXCursor_OverloadedDeclRef:
3382 return getCursorOverloadedDeclRef(C).second;
3383
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003384 default:
3385 // FIXME: Need a way to enumerate all non-reference cases.
3386 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003387 }
3388 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003389
3390 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003391 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003392
3393 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003394 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003395
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003396 if (C.kind == CXCursor_PreprocessingDirective)
3397 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003398
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003399 if (C.kind == CXCursor_MacroInstantiation)
3400 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003401
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003402 if (C.kind == CXCursor_MacroDefinition)
3403 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003404
3405 if (C.kind == CXCursor_InclusionDirective)
3406 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3407
Ted Kremenek007a7c92010-11-01 23:26:51 +00003408 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3409 Decl *D = cxcursor::getCursorDecl(C);
3410 SourceRange R = D->getSourceRange();
3411 // FIXME: Multiple variables declared in a single declaration
3412 // currently lack the information needed to correctly determine their
3413 // ranges when accounting for the type-specifier. We use context
3414 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3415 // and if so, whether it is the first decl.
3416 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3417 if (!cxcursor::isFirstInDeclGroup(C))
3418 R.setBegin(VD->getLocation());
3419 }
3420 return R;
3421 }
Douglas Gregor66537982010-11-17 17:14:07 +00003422 return SourceRange();
3423}
3424
3425/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3426/// the decl-specifier-seq for declarations.
3427static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3428 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3429 Decl *D = cxcursor::getCursorDecl(C);
3430 SourceRange R = D->getSourceRange();
3431
3432 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3433 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3434 TypeLoc TL = TI->getTypeLoc();
3435 SourceLocation TLoc = TL.getSourceRange().getBegin();
3436 if (TLoc.isValid() && R.getBegin().isValid() &&
3437 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3438 R.setBegin(TLoc);
3439 }
3440
3441 // FIXME: Multiple variables declared in a single declaration
3442 // currently lack the information needed to correctly determine their
3443 // ranges when accounting for the type-specifier. We use context
3444 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3445 // and if so, whether it is the first decl.
3446 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3447 if (!cxcursor::isFirstInDeclGroup(C))
3448 R.setBegin(VD->getLocation());
3449 }
3450 }
3451
3452 return R;
3453 }
3454
3455 return getRawCursorExtent(C);
3456}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003457
3458extern "C" {
3459
3460CXSourceRange clang_getCursorExtent(CXCursor C) {
3461 SourceRange R = getRawCursorExtent(C);
3462 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003463 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003464
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003465 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003466}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003467
3468CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003469 if (clang_isInvalid(C.kind))
3470 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003471
Ted Kremeneka60ed472010-11-16 08:15:36 +00003472 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003473 if (clang_isDeclaration(C.kind)) {
3474 Decl *D = getCursorDecl(C);
3475 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003476 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003477 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003478 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003479 if (ObjCForwardProtocolDecl *Protocols
3480 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003481 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003482 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3483 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3484 return MakeCXCursor(Property, tu);
3485
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003486 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003487 }
3488
Douglas Gregor97b98722010-01-19 23:20:36 +00003489 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003490 Expr *E = getCursorExpr(C);
3491 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003492 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003493 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003494
3495 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003496 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003497
Douglas Gregor97b98722010-01-19 23:20:36 +00003498 return clang_getNullCursor();
3499 }
3500
Douglas Gregor36897b02010-09-10 00:22:18 +00003501 if (clang_isStatement(C.kind)) {
3502 Stmt *S = getCursorStmt(C);
3503 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003504 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003505
3506 return clang_getNullCursor();
3507 }
3508
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003509 if (C.kind == CXCursor_MacroInstantiation) {
3510 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003511 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003512 }
3513
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003514 if (!clang_isReference(C.kind))
3515 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003516
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003517 switch (C.kind) {
3518 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003519 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003520
3521 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003522 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003523
3524 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003525 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003526
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003527 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003528 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003529
3530 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003531 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003532
Douglas Gregor69319002010-08-31 23:48:11 +00003533 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003534 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003535
Douglas Gregora67e03f2010-09-09 21:42:20 +00003536 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003537 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003538
Ted Kremenek3064ef92010-08-27 21:34:58 +00003539 case CXCursor_CXXBaseSpecifier: {
3540 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3541 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003542 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003543 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003544
Douglas Gregor36897b02010-09-10 00:22:18 +00003545 case CXCursor_LabelRef:
3546 // FIXME: We end up faking the "parent" declaration here because we
3547 // don't want to make CXCursor larger.
3548 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003549 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3550 .getTranslationUnitDecl(),
3551 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003552
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003553 case CXCursor_OverloadedDeclRef:
3554 return C;
3555
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003556 default:
3557 // We would prefer to enumerate all non-reference cursor kinds here.
3558 llvm_unreachable("Unhandled reference cursor kind");
3559 break;
3560 }
3561 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003562
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003563 return clang_getNullCursor();
3564}
3565
Douglas Gregorb6998662010-01-19 19:34:47 +00003566CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003567 if (clang_isInvalid(C.kind))
3568 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003569
Ted Kremeneka60ed472010-11-16 08:15:36 +00003570 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003571
Douglas Gregorb6998662010-01-19 19:34:47 +00003572 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003573 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003574 C = clang_getCursorReferenced(C);
3575 WasReference = true;
3576 }
3577
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003578 if (C.kind == CXCursor_MacroInstantiation)
3579 return clang_getCursorReferenced(C);
3580
Douglas Gregorb6998662010-01-19 19:34:47 +00003581 if (!clang_isDeclaration(C.kind))
3582 return clang_getNullCursor();
3583
3584 Decl *D = getCursorDecl(C);
3585 if (!D)
3586 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003587
Douglas Gregorb6998662010-01-19 19:34:47 +00003588 switch (D->getKind()) {
3589 // Declaration kinds that don't really separate the notions of
3590 // declaration and definition.
3591 case Decl::Namespace:
3592 case Decl::Typedef:
3593 case Decl::TemplateTypeParm:
3594 case Decl::EnumConstant:
3595 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003596 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003597 case Decl::ObjCIvar:
3598 case Decl::ObjCAtDefsField:
3599 case Decl::ImplicitParam:
3600 case Decl::ParmVar:
3601 case Decl::NonTypeTemplateParm:
3602 case Decl::TemplateTemplateParm:
3603 case Decl::ObjCCategoryImpl:
3604 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003605 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003606 case Decl::LinkageSpec:
3607 case Decl::ObjCPropertyImpl:
3608 case Decl::FileScopeAsm:
3609 case Decl::StaticAssert:
3610 case Decl::Block:
3611 return C;
3612
3613 // Declaration kinds that don't make any sense here, but are
3614 // nonetheless harmless.
3615 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003616 break;
3617
3618 // Declaration kinds for which the definition is not resolvable.
3619 case Decl::UnresolvedUsingTypename:
3620 case Decl::UnresolvedUsingValue:
3621 break;
3622
3623 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003624 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003625 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003626
3627 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003628 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003629
3630 case Decl::Enum:
3631 case Decl::Record:
3632 case Decl::CXXRecord:
3633 case Decl::ClassTemplateSpecialization:
3634 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003635 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003636 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003637 return clang_getNullCursor();
3638
3639 case Decl::Function:
3640 case Decl::CXXMethod:
3641 case Decl::CXXConstructor:
3642 case Decl::CXXDestructor:
3643 case Decl::CXXConversion: {
3644 const FunctionDecl *Def = 0;
3645 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003646 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003647 return clang_getNullCursor();
3648 }
3649
3650 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003651 // Ask the variable if it has a definition.
3652 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003653 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003654 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003655 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003656
Douglas Gregorb6998662010-01-19 19:34:47 +00003657 case Decl::FunctionTemplate: {
3658 const FunctionDecl *Def = 0;
3659 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003660 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003661 return clang_getNullCursor();
3662 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003663
Douglas Gregorb6998662010-01-19 19:34:47 +00003664 case Decl::ClassTemplate: {
3665 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003666 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003667 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003668 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003669 return clang_getNullCursor();
3670 }
3671
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003672 case Decl::Using:
3673 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003674 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003675
3676 case Decl::UsingShadow:
3677 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003678 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003679 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003680
3681 case Decl::ObjCMethod: {
3682 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3683 if (Method->isThisDeclarationADefinition())
3684 return C;
3685
3686 // Dig out the method definition in the associated
3687 // @implementation, if we have it.
3688 // FIXME: The ASTs should make finding the definition easier.
3689 if (ObjCInterfaceDecl *Class
3690 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3691 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3692 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3693 Method->isInstanceMethod()))
3694 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003695 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003696
3697 return clang_getNullCursor();
3698 }
3699
3700 case Decl::ObjCCategory:
3701 if (ObjCCategoryImplDecl *Impl
3702 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003703 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003704 return clang_getNullCursor();
3705
3706 case Decl::ObjCProtocol:
3707 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3708 return C;
3709 return clang_getNullCursor();
3710
3711 case Decl::ObjCInterface:
3712 // There are two notions of a "definition" for an Objective-C
3713 // class: the interface and its implementation. When we resolved a
3714 // reference to an Objective-C class, produce the @interface as
3715 // the definition; when we were provided with the interface,
3716 // produce the @implementation as the definition.
3717 if (WasReference) {
3718 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3719 return C;
3720 } else if (ObjCImplementationDecl *Impl
3721 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003722 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003723 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003724
Douglas Gregorb6998662010-01-19 19:34:47 +00003725 case Decl::ObjCProperty:
3726 // FIXME: We don't really know where to find the
3727 // ObjCPropertyImplDecls that implement this property.
3728 return clang_getNullCursor();
3729
3730 case Decl::ObjCCompatibleAlias:
3731 if (ObjCInterfaceDecl *Class
3732 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3733 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003734 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003735
Douglas Gregorb6998662010-01-19 19:34:47 +00003736 return clang_getNullCursor();
3737
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003738 case Decl::ObjCForwardProtocol:
3739 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003740 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003741
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003742 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003743 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003744 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003745
3746 case Decl::Friend:
3747 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003748 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003749 return clang_getNullCursor();
3750
3751 case Decl::FriendTemplate:
3752 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003753 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003754 return clang_getNullCursor();
3755 }
3756
3757 return clang_getNullCursor();
3758}
3759
3760unsigned clang_isCursorDefinition(CXCursor C) {
3761 if (!clang_isDeclaration(C.kind))
3762 return 0;
3763
3764 return clang_getCursorDefinition(C) == C;
3765}
3766
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003767CXCursor clang_getCanonicalCursor(CXCursor C) {
3768 if (!clang_isDeclaration(C.kind))
3769 return C;
3770
3771 if (Decl *D = getCursorDecl(C))
3772 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3773
3774 return C;
3775}
3776
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003777unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003778 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003779 return 0;
3780
3781 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3782 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3783 return E->getNumDecls();
3784
3785 if (OverloadedTemplateStorage *S
3786 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3787 return S->size();
3788
3789 Decl *D = Storage.get<Decl*>();
3790 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003791 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003792 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3793 return Classes->size();
3794 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3795 return Protocols->protocol_size();
3796
3797 return 0;
3798}
3799
3800CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003801 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003802 return clang_getNullCursor();
3803
3804 if (index >= clang_getNumOverloadedDecls(cursor))
3805 return clang_getNullCursor();
3806
Ted Kremeneka60ed472010-11-16 08:15:36 +00003807 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003808 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3809 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003810 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003811
3812 if (OverloadedTemplateStorage *S
3813 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003814 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003815
3816 Decl *D = Storage.get<Decl*>();
3817 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3818 // FIXME: This is, unfortunately, linear time.
3819 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3820 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003821 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003822 }
3823
3824 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003825 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003826
3827 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003828 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003829
3830 return clang_getNullCursor();
3831}
3832
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003833void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003834 const char **startBuf,
3835 const char **endBuf,
3836 unsigned *startLine,
3837 unsigned *startColumn,
3838 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003839 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003840 assert(getCursorDecl(C) && "CXCursor has null decl");
3841 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003842 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3843 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003844
Steve Naroff4ade6d62009-09-23 17:52:52 +00003845 SourceManager &SM = FD->getASTContext().getSourceManager();
3846 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3847 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3848 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3849 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3850 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3851 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3852}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003853
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003854void clang_enableStackTraces(void) {
3855 llvm::sys::PrintStackTraceOnErrorSignal();
3856}
3857
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003858void clang_executeOnThread(void (*fn)(void*), void *user_data,
3859 unsigned stack_size) {
3860 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3861}
3862
Ted Kremenekfb480492010-01-13 21:46:36 +00003863} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003864
Ted Kremenekfb480492010-01-13 21:46:36 +00003865//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003866// Token-based Operations.
3867//===----------------------------------------------------------------------===//
3868
3869/* CXToken layout:
3870 * int_data[0]: a CXTokenKind
3871 * int_data[1]: starting token location
3872 * int_data[2]: token length
3873 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003874 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003875 * otherwise unused.
3876 */
3877extern "C" {
3878
3879CXTokenKind clang_getTokenKind(CXToken CXTok) {
3880 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3881}
3882
3883CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3884 switch (clang_getTokenKind(CXTok)) {
3885 case CXToken_Identifier:
3886 case CXToken_Keyword:
3887 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003888 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3889 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890
3891 case CXToken_Literal: {
3892 // We have stashed the starting pointer in the ptr_data field. Use it.
3893 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003894 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003896
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003897 case CXToken_Punctuation:
3898 case CXToken_Comment:
3899 break;
3900 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003901
3902 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003903 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003904 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003905 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003906 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003907
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003908 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3909 std::pair<FileID, unsigned> LocInfo
3910 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003911 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003912 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003913 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3914 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003915 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003916
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003917 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003918}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003919
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003920CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003921 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003922 if (!CXXUnit)
3923 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003924
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003925 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3926 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3927}
3928
3929CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003930 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003931 if (!CXXUnit)
3932 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003933
3934 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003935 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3936}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003937
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003938void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3939 CXToken **Tokens, unsigned *NumTokens) {
3940 if (Tokens)
3941 *Tokens = 0;
3942 if (NumTokens)
3943 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003944
Ted Kremeneka60ed472010-11-16 08:15:36 +00003945 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003946 if (!CXXUnit || !Tokens || !NumTokens)
3947 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003948
Douglas Gregorbdf60622010-03-05 21:16:25 +00003949 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3950
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003951 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003952 if (R.isInvalid())
3953 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003954
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003955 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3956 std::pair<FileID, unsigned> BeginLocInfo
3957 = SourceMgr.getDecomposedLoc(R.getBegin());
3958 std::pair<FileID, unsigned> EndLocInfo
3959 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003960
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003961 // Cannot tokenize across files.
3962 if (BeginLocInfo.first != EndLocInfo.first)
3963 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003964
3965 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003966 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003967 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003968 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003969 if (Invalid)
3970 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003971
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003972 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3973 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003974 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003975 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003976
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003977 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003978 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003979 llvm::SmallVector<CXToken, 32> CXTokens;
3980 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003981 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003982 do {
3983 // Lex the next token
3984 Lex.LexFromRawLexer(Tok);
3985 if (Tok.is(tok::eof))
3986 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003987
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003988 // Initialize the CXToken.
3989 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003990
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003991 // - Common fields
3992 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3993 CXTok.int_data[2] = Tok.getLength();
3994 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003995
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003996 // - Kind-specific fields
3997 if (Tok.isLiteral()) {
3998 CXTok.int_data[0] = CXToken_Literal;
3999 CXTok.ptr_data = (void *)Tok.getLiteralData();
4000 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004001 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004002 std::pair<FileID, unsigned> LocInfo
4003 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00004004 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004005 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00004006 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4007 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004008 return;
4009
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004010 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004011 IdentifierInfo *II
4012 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004013
David Chisnall096428b2010-10-13 21:44:48 +00004014 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004015 CXTok.int_data[0] = CXToken_Keyword;
4016 }
4017 else {
4018 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
4019 CXToken_Identifier
4020 : CXToken_Keyword;
4021 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004022 CXTok.ptr_data = II;
4023 } else if (Tok.is(tok::comment)) {
4024 CXTok.int_data[0] = CXToken_Comment;
4025 CXTok.ptr_data = 0;
4026 } else {
4027 CXTok.int_data[0] = CXToken_Punctuation;
4028 CXTok.ptr_data = 0;
4029 }
4030 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004031 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004032 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004033
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004034 if (CXTokens.empty())
4035 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004036
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004037 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4038 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4039 *NumTokens = CXTokens.size();
4040}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004041
Ted Kremenek6db61092010-05-05 00:55:15 +00004042void clang_disposeTokens(CXTranslationUnit TU,
4043 CXToken *Tokens, unsigned NumTokens) {
4044 free(Tokens);
4045}
4046
4047} // end: extern "C"
4048
4049//===----------------------------------------------------------------------===//
4050// Token annotation APIs.
4051//===----------------------------------------------------------------------===//
4052
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004053typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004054static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4055 CXCursor parent,
4056 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004057namespace {
4058class AnnotateTokensWorker {
4059 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004060 CXToken *Tokens;
4061 CXCursor *Cursors;
4062 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004063 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004064 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004065 CursorVisitor AnnotateVis;
4066 SourceManager &SrcMgr;
4067
4068 bool MoreTokens() const { return TokIdx < NumTokens; }
4069 unsigned NextToken() const { return TokIdx; }
4070 void AdvanceToken() { ++TokIdx; }
4071 SourceLocation GetTokenLoc(unsigned tokI) {
4072 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4073 }
4074
Ted Kremenek6db61092010-05-05 00:55:15 +00004075public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004076 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004077 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004078 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004079 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004080 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004081 AnnotateVis(tu,
4082 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004083 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004084 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004085
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004086 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004087 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004088 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004089 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004090 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004091 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004092};
4093}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004094
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004095void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4096 // Walk the AST within the region of interest, annotating tokens
4097 // along the way.
4098 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004099
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004100 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4101 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004102 if (Pos != Annotated.end() &&
4103 (clang_isInvalid(Cursors[I].kind) ||
4104 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004105 Cursors[I] = Pos->second;
4106 }
4107
4108 // Finish up annotating any tokens left.
4109 if (!MoreTokens())
4110 return;
4111
4112 const CXCursor &C = clang_getNullCursor();
4113 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4114 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4115 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004116 }
4117}
4118
Ted Kremenek6db61092010-05-05 00:55:15 +00004119enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004120AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004121 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004122 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004123 if (cursorRange.isInvalid())
4124 return CXChildVisit_Recurse;
4125
Douglas Gregor4419b672010-10-21 06:10:04 +00004126 if (clang_isPreprocessing(cursor.kind)) {
4127 // For macro instantiations, just note where the beginning of the macro
4128 // instantiation occurs.
4129 if (cursor.kind == CXCursor_MacroInstantiation) {
4130 Annotated[Loc.int_data] = cursor;
4131 return CXChildVisit_Recurse;
4132 }
4133
Douglas Gregor4419b672010-10-21 06:10:04 +00004134 // Items in the preprocessing record are kept separate from items in
4135 // declarations, so we keep a separate token index.
4136 unsigned SavedTokIdx = TokIdx;
4137 TokIdx = PreprocessingTokIdx;
4138
4139 // Skip tokens up until we catch up to the beginning of the preprocessing
4140 // entry.
4141 while (MoreTokens()) {
4142 const unsigned I = NextToken();
4143 SourceLocation TokLoc = GetTokenLoc(I);
4144 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4145 case RangeBefore:
4146 AdvanceToken();
4147 continue;
4148 case RangeAfter:
4149 case RangeOverlap:
4150 break;
4151 }
4152 break;
4153 }
4154
4155 // Look at all of the tokens within this range.
4156 while (MoreTokens()) {
4157 const unsigned I = NextToken();
4158 SourceLocation TokLoc = GetTokenLoc(I);
4159 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4160 case RangeBefore:
4161 assert(0 && "Infeasible");
4162 case RangeAfter:
4163 break;
4164 case RangeOverlap:
4165 Cursors[I] = cursor;
4166 AdvanceToken();
4167 continue;
4168 }
4169 break;
4170 }
4171
4172 // Save the preprocessing token index; restore the non-preprocessing
4173 // token index.
4174 PreprocessingTokIdx = TokIdx;
4175 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004176 return CXChildVisit_Recurse;
4177 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004178
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004179 if (cursorRange.isInvalid())
4180 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004181
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004182 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4183
Ted Kremeneka333c662010-05-12 05:29:33 +00004184 // Adjust the annotated range based specific declarations.
4185 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4186 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004187 Decl *D = cxcursor::getCursorDecl(cursor);
4188 // Don't visit synthesized ObjC methods, since they have no syntatic
4189 // representation in the source.
4190 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4191 if (MD->isSynthesized())
4192 return CXChildVisit_Continue;
4193 }
4194 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004195 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4196 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004197 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004198 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004199 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004200 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004201 }
4202 }
4203 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004204
Ted Kremenek3f404602010-08-14 01:14:06 +00004205 // If the location of the cursor occurs within a macro instantiation, record
4206 // the spelling location of the cursor in our annotation map. We can then
4207 // paper over the token labelings during a post-processing step to try and
4208 // get cursor mappings for tokens that are the *arguments* of a macro
4209 // instantiation.
4210 if (L.isMacroID()) {
4211 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4212 // Only invalidate the old annotation if it isn't part of a preprocessing
4213 // directive. Here we assume that the default construction of CXCursor
4214 // results in CXCursor.kind being an initialized value (i.e., 0). If
4215 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004216
Ted Kremenek3f404602010-08-14 01:14:06 +00004217 CXCursor &oldC = Annotated[rawEncoding];
4218 if (!clang_isPreprocessing(oldC.kind))
4219 oldC = cursor;
4220 }
4221
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004222 const enum CXCursorKind K = clang_getCursorKind(parent);
4223 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004224 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4225 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004226
4227 while (MoreTokens()) {
4228 const unsigned I = NextToken();
4229 SourceLocation TokLoc = GetTokenLoc(I);
4230 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4231 case RangeBefore:
4232 Cursors[I] = updateC;
4233 AdvanceToken();
4234 continue;
4235 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004236 case RangeOverlap:
4237 break;
4238 }
4239 break;
4240 }
4241
4242 // Visit children to get their cursor information.
4243 const unsigned BeforeChildren = NextToken();
4244 VisitChildren(cursor);
4245 const unsigned AfterChildren = NextToken();
4246
4247 // Adjust 'Last' to the last token within the extent of the cursor.
4248 while (MoreTokens()) {
4249 const unsigned I = NextToken();
4250 SourceLocation TokLoc = GetTokenLoc(I);
4251 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4252 case RangeBefore:
4253 assert(0 && "Infeasible");
4254 case RangeAfter:
4255 break;
4256 case RangeOverlap:
4257 Cursors[I] = updateC;
4258 AdvanceToken();
4259 continue;
4260 }
4261 break;
4262 }
4263 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004264
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004265 // Scan the tokens that are at the beginning of the cursor, but are not
4266 // capture by the child cursors.
4267
4268 // For AST elements within macros, rely on a post-annotate pass to
4269 // to correctly annotate the tokens with cursors. Otherwise we can
4270 // get confusing results of having tokens that map to cursors that really
4271 // are expanded by an instantiation.
4272 if (L.isMacroID())
4273 cursor = clang_getNullCursor();
4274
4275 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4276 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4277 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004278
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279 Cursors[I] = cursor;
4280 }
4281 // Scan the tokens that are at the end of the cursor, but are not captured
4282 // but the child cursors.
4283 for (unsigned I = AfterChildren; I != Last; ++I)
4284 Cursors[I] = cursor;
4285
4286 TokIdx = Last;
4287 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004288}
4289
Ted Kremenek6db61092010-05-05 00:55:15 +00004290static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4291 CXCursor parent,
4292 CXClientData client_data) {
4293 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4294}
4295
Ted Kremenekab979612010-11-11 08:05:23 +00004296// This gets run a separate thread to avoid stack blowout.
4297static void runAnnotateTokensWorker(void *UserData) {
4298 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4299}
4300
Ted Kremenek6db61092010-05-05 00:55:15 +00004301extern "C" {
4302
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004303void clang_annotateTokens(CXTranslationUnit TU,
4304 CXToken *Tokens, unsigned NumTokens,
4305 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004306
4307 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004308 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004309
Douglas Gregor4419b672010-10-21 06:10:04 +00004310 // Any token we don't specifically annotate will have a NULL cursor.
4311 CXCursor C = clang_getNullCursor();
4312 for (unsigned I = 0; I != NumTokens; ++I)
4313 Cursors[I] = C;
4314
Ted Kremeneka60ed472010-11-16 08:15:36 +00004315 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004316 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004317 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004318
Douglas Gregorbdf60622010-03-05 21:16:25 +00004319 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004320
Douglas Gregor0396f462010-03-19 05:22:59 +00004321 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004322 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004323 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4324 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004325 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4326 clang_getTokenLocation(TU,
4327 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004328
Douglas Gregor0396f462010-03-19 05:22:59 +00004329 // A mapping from the source locations found when re-lexing or traversing the
4330 // region of interest to the corresponding cursors.
4331 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004332
4333 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004334 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004335 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4336 std::pair<FileID, unsigned> BeginLocInfo
4337 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4338 std::pair<FileID, unsigned> EndLocInfo
4339 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004340
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004341 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004342 bool Invalid = false;
4343 if (BeginLocInfo.first == EndLocInfo.first &&
4344 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4345 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004346 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4347 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004348 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004349 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004350 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004351
4352 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004353 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004354 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004355 Token Tok;
4356 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004357
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004358 reprocess:
4359 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4360 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004361 // don't see it while preprocessing these tokens later, but keep track
4362 // of all of the token locations inside this preprocessing directive so
4363 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004364 //
4365 // FIXME: Some simple tests here could identify macro definitions and
4366 // #undefs, to provide specific cursor kinds for those.
4367 std::vector<SourceLocation> Locations;
4368 do {
4369 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004370 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004371 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004372
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004373 using namespace cxcursor;
4374 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004375 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4376 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004377 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004378 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4379 Annotated[Locations[I].getRawEncoding()] = Cursor;
4380 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004381
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004382 if (Tok.isAtStartOfLine())
4383 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004384
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004385 continue;
4386 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004387
Douglas Gregor48072312010-03-18 15:23:44 +00004388 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004389 break;
4390 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004391 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004392
Douglas Gregor0396f462010-03-19 05:22:59 +00004393 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004394 // a specific cursor.
4395 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004396 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004397
4398 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004399 // FIXME: We use a ridiculous stack size here because the data-recursion
4400 // algorithm uses a large stack frame than the non-data recursive version,
4401 // and AnnotationTokensWorker currently transforms the data-recursion
4402 // algorithm back into a traditional recursion by explicitly calling
4403 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004404 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004405 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4406 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004407 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4408 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004409}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004410} // end: extern "C"
4411
4412//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004413// Operations for querying linkage of a cursor.
4414//===----------------------------------------------------------------------===//
4415
4416extern "C" {
4417CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004418 if (!clang_isDeclaration(cursor.kind))
4419 return CXLinkage_Invalid;
4420
Ted Kremenek16b42592010-03-03 06:36:57 +00004421 Decl *D = cxcursor::getCursorDecl(cursor);
4422 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4423 switch (ND->getLinkage()) {
4424 case NoLinkage: return CXLinkage_NoLinkage;
4425 case InternalLinkage: return CXLinkage_Internal;
4426 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4427 case ExternalLinkage: return CXLinkage_External;
4428 };
4429
4430 return CXLinkage_Invalid;
4431}
4432} // end: extern "C"
4433
4434//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004435// Operations for querying language of a cursor.
4436//===----------------------------------------------------------------------===//
4437
4438static CXLanguageKind getDeclLanguage(const Decl *D) {
4439 switch (D->getKind()) {
4440 default:
4441 break;
4442 case Decl::ImplicitParam:
4443 case Decl::ObjCAtDefsField:
4444 case Decl::ObjCCategory:
4445 case Decl::ObjCCategoryImpl:
4446 case Decl::ObjCClass:
4447 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004448 case Decl::ObjCForwardProtocol:
4449 case Decl::ObjCImplementation:
4450 case Decl::ObjCInterface:
4451 case Decl::ObjCIvar:
4452 case Decl::ObjCMethod:
4453 case Decl::ObjCProperty:
4454 case Decl::ObjCPropertyImpl:
4455 case Decl::ObjCProtocol:
4456 return CXLanguage_ObjC;
4457 case Decl::CXXConstructor:
4458 case Decl::CXXConversion:
4459 case Decl::CXXDestructor:
4460 case Decl::CXXMethod:
4461 case Decl::CXXRecord:
4462 case Decl::ClassTemplate:
4463 case Decl::ClassTemplatePartialSpecialization:
4464 case Decl::ClassTemplateSpecialization:
4465 case Decl::Friend:
4466 case Decl::FriendTemplate:
4467 case Decl::FunctionTemplate:
4468 case Decl::LinkageSpec:
4469 case Decl::Namespace:
4470 case Decl::NamespaceAlias:
4471 case Decl::NonTypeTemplateParm:
4472 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004473 case Decl::TemplateTemplateParm:
4474 case Decl::TemplateTypeParm:
4475 case Decl::UnresolvedUsingTypename:
4476 case Decl::UnresolvedUsingValue:
4477 case Decl::Using:
4478 case Decl::UsingDirective:
4479 case Decl::UsingShadow:
4480 return CXLanguage_CPlusPlus;
4481 }
4482
4483 return CXLanguage_C;
4484}
4485
4486extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004487
4488enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4489 if (clang_isDeclaration(cursor.kind))
4490 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4491 if (D->hasAttr<UnavailableAttr>() ||
4492 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4493 return CXAvailability_Available;
4494
4495 if (D->hasAttr<DeprecatedAttr>())
4496 return CXAvailability_Deprecated;
4497 }
4498
4499 return CXAvailability_Available;
4500}
4501
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004502CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4503 if (clang_isDeclaration(cursor.kind))
4504 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4505
4506 return CXLanguage_Invalid;
4507}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004508
4509CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4510 if (clang_isDeclaration(cursor.kind)) {
4511 if (Decl *D = getCursorDecl(cursor)) {
4512 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004513 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004514 }
4515 }
4516
4517 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4518 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004519 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004520 }
4521
4522 return clang_getNullCursor();
4523}
4524
4525CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4526 if (clang_isDeclaration(cursor.kind)) {
4527 if (Decl *D = getCursorDecl(cursor)) {
4528 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004529 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004530 }
4531 }
4532
4533 // FIXME: Note that we can't easily compute the lexical context of a
4534 // statement or expression, so we return nothing.
4535 return clang_getNullCursor();
4536}
4537
Douglas Gregor9f592342010-10-01 20:25:15 +00004538static void CollectOverriddenMethods(DeclContext *Ctx,
4539 ObjCMethodDecl *Method,
4540 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4541 if (!Ctx)
4542 return;
4543
4544 // If we have a class or category implementation, jump straight to the
4545 // interface.
4546 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4547 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4548
4549 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4550 if (!Container)
4551 return;
4552
4553 // Check whether we have a matching method at this level.
4554 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4555 Method->isInstanceMethod()))
4556 if (Method != Overridden) {
4557 // We found an override at this level; there is no need to look
4558 // into other protocols or categories.
4559 Methods.push_back(Overridden);
4560 return;
4561 }
4562
4563 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4564 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4565 PEnd = Protocol->protocol_end();
4566 P != PEnd; ++P)
4567 CollectOverriddenMethods(*P, Method, Methods);
4568 }
4569
4570 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4571 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4572 PEnd = Category->protocol_end();
4573 P != PEnd; ++P)
4574 CollectOverriddenMethods(*P, Method, Methods);
4575 }
4576
4577 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4578 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4579 PEnd = Interface->protocol_end();
4580 P != PEnd; ++P)
4581 CollectOverriddenMethods(*P, Method, Methods);
4582
4583 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4584 Category; Category = Category->getNextClassCategory())
4585 CollectOverriddenMethods(Category, Method, Methods);
4586
4587 // We only look into the superclass if we haven't found anything yet.
4588 if (Methods.empty())
4589 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4590 return CollectOverriddenMethods(Super, Method, Methods);
4591 }
4592}
4593
4594void clang_getOverriddenCursors(CXCursor cursor,
4595 CXCursor **overridden,
4596 unsigned *num_overridden) {
4597 if (overridden)
4598 *overridden = 0;
4599 if (num_overridden)
4600 *num_overridden = 0;
4601 if (!overridden || !num_overridden)
4602 return;
4603
4604 if (!clang_isDeclaration(cursor.kind))
4605 return;
4606
4607 Decl *D = getCursorDecl(cursor);
4608 if (!D)
4609 return;
4610
4611 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004612 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004613 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4614 *num_overridden = CXXMethod->size_overridden_methods();
4615 if (!*num_overridden)
4616 return;
4617
4618 *overridden = new CXCursor [*num_overridden];
4619 unsigned I = 0;
4620 for (CXXMethodDecl::method_iterator
4621 M = CXXMethod->begin_overridden_methods(),
4622 MEnd = CXXMethod->end_overridden_methods();
4623 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004624 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004625 return;
4626 }
4627
4628 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4629 if (!Method)
4630 return;
4631
4632 // Handle Objective-C methods.
4633 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4634 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4635
4636 if (Methods.empty())
4637 return;
4638
4639 *num_overridden = Methods.size();
4640 *overridden = new CXCursor [Methods.size()];
4641 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004642 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004643}
4644
4645void clang_disposeOverriddenCursors(CXCursor *overridden) {
4646 delete [] overridden;
4647}
4648
Douglas Gregorecdcb882010-10-20 22:00:55 +00004649CXFile clang_getIncludedFile(CXCursor cursor) {
4650 if (cursor.kind != CXCursor_InclusionDirective)
4651 return 0;
4652
4653 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4654 return (void *)ID->getFile();
4655}
4656
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004657} // end: extern "C"
4658
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004659
4660//===----------------------------------------------------------------------===//
4661// C++ AST instrospection.
4662//===----------------------------------------------------------------------===//
4663
4664extern "C" {
4665unsigned clang_CXXMethod_isStatic(CXCursor C) {
4666 if (!clang_isDeclaration(C.kind))
4667 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004668
4669 CXXMethodDecl *Method = 0;
4670 Decl *D = cxcursor::getCursorDecl(C);
4671 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4672 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4673 else
4674 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4675 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004676}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004677
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004678} // end: extern "C"
4679
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004680//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004681// Attribute introspection.
4682//===----------------------------------------------------------------------===//
4683
4684extern "C" {
4685CXType clang_getIBOutletCollectionType(CXCursor C) {
4686 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004687 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004688
4689 IBOutletCollectionAttr *A =
4690 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4691
Ted Kremeneka60ed472010-11-16 08:15:36 +00004692 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004693}
4694} // end: extern "C"
4695
4696//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004697// Misc. utility functions.
4698//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004699
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004700/// Default to using an 8 MB stack size on "safety" threads.
4701static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004702
4703namespace clang {
4704
4705bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004706 void (*Fn)(void*), void *UserData,
4707 unsigned Size) {
4708 if (!Size)
4709 Size = GetSafetyThreadStackSize();
4710 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004711 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4712 return CRC.RunSafely(Fn, UserData);
4713}
4714
4715unsigned GetSafetyThreadStackSize() {
4716 return SafetyStackThreadSize;
4717}
4718
4719void SetSafetyThreadStackSize(unsigned Value) {
4720 SafetyStackThreadSize = Value;
4721}
4722
4723}
4724
Ted Kremenek04bb7162010-01-22 22:44:15 +00004725extern "C" {
4726
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004727CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004728 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004729}
4730
4731} // end: extern "C"