blob: d9aec475587f3c0ff005b25d66faa29b8dcd7136 [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);
329 bool VisitPointerTypeLoc(PointerTypeLoc TL);
330 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
331 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
332 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
333 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000334 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000335 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000336 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000337 // FIXME: Implement visitors here when the unimplemented TypeLocs get
338 // implemented
339 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
340 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000341
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000342 // Data-recursive visitor functions.
343 bool IsInRegionOfInterest(CXCursor C);
344 bool RunVisitorWorkList(VisitorWorkList &WL);
345 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000346 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000347};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000348
Ted Kremenekab188932010-01-05 19:32:54 +0000349} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000350
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000351static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000352static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
353
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000354
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000355RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000356 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357}
358
Douglas Gregorb1373d02010-01-20 20:59:29 +0000359/// \brief Visit the given cursor and, if requested by the visitor,
360/// its children.
361///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362/// \param Cursor the cursor to visit.
363///
364/// \param CheckRegionOfInterest if true, then the caller already checked that
365/// this cursor is within the region of interest.
366///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000367/// \returns true if the visitation should be aborted, false if it
368/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000369bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370 if (clang_isInvalid(Cursor.kind))
371 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000372
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373 if (clang_isDeclaration(Cursor.kind)) {
374 Decl *D = getCursorDecl(Cursor);
375 assert(D && "Invalid declaration cursor");
376 if (D->getPCHLevel() > MaxPCHLevel)
377 return false;
378
379 if (D->isImplicit())
380 return false;
381 }
382
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000383 // If we have a range of interest, and this cursor doesn't intersect with it,
384 // we're done.
385 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000386 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000387 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388 return false;
389 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000390
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391 switch (Visitor(Cursor, Parent, ClientData)) {
392 case CXChildVisit_Break:
393 return true;
394
395 case CXChildVisit_Continue:
396 return false;
397
398 case CXChildVisit_Recurse:
399 return VisitChildren(Cursor);
400 }
401
Douglas Gregorfd643772010-01-25 16:45:46 +0000402 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403}
404
Douglas Gregor788f5a12010-03-20 00:41:21 +0000405std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
406CursorVisitor::getPreprocessedEntities() {
407 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000408 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000409
410 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000411 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000412
Douglas Gregor89d99802010-11-30 06:16:57 +0000413 PreprocessingRecord::iterator StartEntity, EndEntity;
414 if (OnlyLocalDecls) {
415 StartEntity = AU->pp_entity_begin();
416 EndEntity = AU->pp_entity_end();
417 } else {
418 StartEntity = PPRec.begin();
419 EndEntity = PPRec.end();
420 }
421
Douglas Gregor788f5a12010-03-20 00:41:21 +0000422 // There is no region of interest; we have to walk everything.
423 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000424 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000425
426 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000427 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000428 std::pair<FileID, unsigned> Begin
429 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
430 std::pair<FileID, unsigned> End
431 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
432
433 // The region of interest spans files; we have to walk everything.
434 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000435 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000436
437 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000438 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000439 if (ByFileMap.empty()) {
440 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000441 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000442 std::pair<FileID, unsigned> P
443 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000444
Douglas Gregor788f5a12010-03-20 00:41:21 +0000445 ByFileMap[P.first].push_back(*E);
446 }
447 }
448
449 return std::make_pair(ByFileMap[Begin.first].begin(),
450 ByFileMap[Begin.first].end());
451}
452
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000454///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455/// \returns true if the visitation should be aborted, false if it
456/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000458 if (clang_isReference(Cursor.kind)) {
459 // By definition, references have no children.
460 return false;
461 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000462
463 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000464 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000465 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467 if (clang_isDeclaration(Cursor.kind)) {
468 Decl *D = getCursorDecl(Cursor);
469 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000470 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472
Douglas Gregora59e3902010-01-21 23:27:09 +0000473 if (clang_isStatement(Cursor.kind))
474 return Visit(getCursorStmt(Cursor));
475 if (clang_isExpression(Cursor.kind))
476 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000477
Douglas Gregorb1373d02010-01-20 20:59:29 +0000478 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000479 CXTranslationUnit tu = getCursorTU(Cursor);
480 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000481 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
482 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000483 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
484 TLEnd = CXXUnit->top_level_end();
485 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000486 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000487 return true;
488 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000489 } else if (VisitDeclContext(
490 CXXUnit->getASTContext().getTranslationUnitDecl()))
491 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000492
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000494 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 // FIXME: Once we have the ability to deserialize a preprocessing record,
496 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000497 PreprocessingRecord::iterator E, EEnd;
498 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000499 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000500 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000502
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 continue;
504 }
505
506 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000507 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 return true;
509
510 continue;
511 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000512
513 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000514 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000515 return true;
516
517 continue;
518 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000519 }
520 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000521 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000523
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 return false;
526}
527
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000529 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
530 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000531
Ted Kremenek664cffd2010-07-22 11:30:19 +0000532 if (Stmt *Body = B->getBody())
533 return Visit(MakeCXCursor(Body, StmtParent, TU));
534
535 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000536}
537
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000538llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
539 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000540 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000541 if (Range.isInvalid())
542 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000543
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000544 switch (CompareRegionOfInterest(Range)) {
545 case RangeBefore:
546 // This declaration comes before the region of interest; skip it.
547 return llvm::Optional<bool>();
548
549 case RangeAfter:
550 // This declaration comes after the region of interest; we're done.
551 return false;
552
553 case RangeOverlap:
554 // This declaration overlaps the region of interest; visit it.
555 break;
556 }
557 }
558 return true;
559}
560
561bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
562 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
563
564 // FIXME: Eventually remove. This part of a hack to support proper
565 // iteration over all Decls contained lexically within an ObjC container.
566 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
567 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
568
569 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000570 Decl *D = *I;
571 if (D->getLexicalDeclContext() != DC)
572 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000573 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000574 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
575 if (!V.hasValue())
576 continue;
577 if (!V.getValue())
578 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000579 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000580 return true;
581 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000583}
584
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000585bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
586 llvm_unreachable("Translation units are visited directly by Visit()");
587 return false;
588}
589
590bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
591 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
592 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000594 return false;
595}
596
597bool CursorVisitor::VisitTagDecl(TagDecl *D) {
598 return VisitDeclContext(D);
599}
600
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000601bool CursorVisitor::VisitClassTemplateSpecializationDecl(
602 ClassTemplateSpecializationDecl *D) {
603 bool ShouldVisitBody = false;
604 switch (D->getSpecializationKind()) {
605 case TSK_Undeclared:
606 case TSK_ImplicitInstantiation:
607 // Nothing to visit
608 return false;
609
610 case TSK_ExplicitInstantiationDeclaration:
611 case TSK_ExplicitInstantiationDefinition:
612 break;
613
614 case TSK_ExplicitSpecialization:
615 ShouldVisitBody = true;
616 break;
617 }
618
619 // Visit the template arguments used in the specialization.
620 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
621 TypeLoc TL = SpecType->getTypeLoc();
622 if (TemplateSpecializationTypeLoc *TSTLoc
623 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
624 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
625 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
626 return true;
627 }
628 }
629
630 if (ShouldVisitBody && VisitCXXRecordDecl(D))
631 return true;
632
633 return false;
634}
635
Douglas Gregor74dbe642010-08-31 19:31:58 +0000636bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
637 ClassTemplatePartialSpecializationDecl *D) {
638 // FIXME: Visit the "outer" template parameter lists on the TagDecl
639 // before visiting these template parameters.
640 if (VisitTemplateParameters(D->getTemplateParameters()))
641 return true;
642
643 // Visit the partial specialization arguments.
644 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
645 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
646 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
647 return true;
648
649 return VisitCXXRecordDecl(D);
650}
651
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000652bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000653 // Visit the default argument.
654 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
655 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
656 if (Visit(DefArg->getTypeLoc()))
657 return true;
658
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000659 return false;
660}
661
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000662bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
663 if (Expr *Init = D->getInitExpr())
664 return Visit(MakeCXCursor(Init, StmtParent, TU));
665 return false;
666}
667
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000668bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
669 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
670 if (Visit(TSInfo->getTypeLoc()))
671 return true;
672
673 return false;
674}
675
Douglas Gregora67e03f2010-09-09 21:42:20 +0000676/// \brief Compare two base or member initializers based on their source order.
677static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
678 CXXBaseOrMemberInitializer const * const *X
679 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
680 CXXBaseOrMemberInitializer const * const *Y
681 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
682
683 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
684 return -1;
685 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
686 return 1;
687 else
688 return 0;
689}
690
Douglas Gregorb1373d02010-01-20 20:59:29 +0000691bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000692 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
693 // Visit the function declaration's syntactic components in the order
694 // written. This requires a bit of work.
695 TypeLoc TL = TSInfo->getTypeLoc();
696 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
697
698 // If we have a function declared directly (without the use of a typedef),
699 // visit just the return type. Otherwise, just visit the function's type
700 // now.
701 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
702 (!FTL && Visit(TL)))
703 return true;
704
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000705 // Visit the nested-name-specifier, if present.
706 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
707 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
708 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000709
710 // Visit the declaration name.
711 if (VisitDeclarationNameInfo(ND->getNameInfo()))
712 return true;
713
714 // FIXME: Visit explicitly-specified template arguments!
715
716 // Visit the function parameters, if we have a function type.
717 if (FTL && VisitFunctionTypeLoc(*FTL, true))
718 return true;
719
720 // FIXME: Attributes?
721 }
722
Douglas Gregora67e03f2010-09-09 21:42:20 +0000723 if (ND->isThisDeclarationADefinition()) {
724 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
725 // Find the initializers that were written in the source.
726 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
727 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
728 IEnd = Constructor->init_end();
729 I != IEnd; ++I) {
730 if (!(*I)->isWritten())
731 continue;
732
733 WrittenInits.push_back(*I);
734 }
735
736 // Sort the initializers in source order
737 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
738 &CompareCXXBaseOrMemberInitializers);
739
740 // Visit the initializers in source order
741 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
742 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000743 if (Init->isAnyMemberInitializer()) {
744 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000745 Init->getMemberLocation(), TU)))
746 return true;
747 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
748 if (Visit(BaseInfo->getTypeLoc()))
749 return true;
750 }
751
752 // Visit the initializer value.
753 if (Expr *Initializer = Init->getInit())
754 if (Visit(MakeCXCursor(Initializer, ND, TU)))
755 return true;
756 }
757 }
758
759 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
760 return true;
761 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000762
Douglas Gregorb1373d02010-01-20 20:59:29 +0000763 return false;
764}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000765
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000766bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
767 if (VisitDeclaratorDecl(D))
768 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770 if (Expr *BitWidth = D->getBitWidth())
771 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000772
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000773 return false;
774}
775
776bool CursorVisitor::VisitVarDecl(VarDecl *D) {
777 if (VisitDeclaratorDecl(D))
778 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780 if (Expr *Init = D->getInit())
781 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000783 return false;
784}
785
Douglas Gregor84b51d72010-09-01 20:16:53 +0000786bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
787 if (VisitDeclaratorDecl(D))
788 return true;
789
790 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
791 if (Expr *DefArg = D->getDefaultArgument())
792 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
793
794 return false;
795}
796
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000797bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
798 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
799 // before visiting these template parameters.
800 if (VisitTemplateParameters(D->getTemplateParameters()))
801 return true;
802
803 return VisitFunctionDecl(D->getTemplatedDecl());
804}
805
Douglas Gregor39d6f072010-08-31 19:02:00 +0000806bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
807 // FIXME: Visit the "outer" template parameter lists on the TagDecl
808 // before visiting these template parameters.
809 if (VisitTemplateParameters(D->getTemplateParameters()))
810 return true;
811
812 return VisitCXXRecordDecl(D->getTemplatedDecl());
813}
814
Douglas Gregor84b51d72010-09-01 20:16:53 +0000815bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
816 if (VisitTemplateParameters(D->getTemplateParameters()))
817 return true;
818
819 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
820 VisitTemplateArgumentLoc(D->getDefaultArgument()))
821 return true;
822
823 return false;
824}
825
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000826bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000827 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
828 if (Visit(TSInfo->getTypeLoc()))
829 return true;
830
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832 PEnd = ND->param_end();
833 P != PEnd; ++P) {
834 if (Visit(MakeCXCursor(*P, TU)))
835 return true;
836 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000837
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000838 if (ND->isThisDeclarationADefinition() &&
839 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
840 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 return false;
843}
844
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000845namespace {
846 struct ContainerDeclsSort {
847 SourceManager &SM;
848 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
849 bool operator()(Decl *A, Decl *B) {
850 SourceLocation L_A = A->getLocStart();
851 SourceLocation L_B = B->getLocStart();
852 assert(L_A.isValid() && L_B.isValid());
853 return SM.isBeforeInTranslationUnit(L_A, L_B);
854 }
855 };
856}
857
Douglas Gregora59e3902010-01-21 23:27:09 +0000858bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000859 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
860 // an @implementation can lexically contain Decls that are not properly
861 // nested in the AST. When we identify such cases, we need to retrofit
862 // this nesting here.
863 if (!DI_current)
864 return VisitDeclContext(D);
865
866 // Scan the Decls that immediately come after the container
867 // in the current DeclContext. If any fall within the
868 // container's lexical region, stash them into a vector
869 // for later processing.
870 llvm::SmallVector<Decl *, 24> DeclsInContainer;
871 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000872 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000873 if (EndLoc.isValid()) {
874 DeclContext::decl_iterator next = *DI_current;
875 while (++next != DE_current) {
876 Decl *D_next = *next;
877 if (!D_next)
878 break;
879 SourceLocation L = D_next->getLocStart();
880 if (!L.isValid())
881 break;
882 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
883 *DI_current = next;
884 DeclsInContainer.push_back(D_next);
885 continue;
886 }
887 break;
888 }
889 }
890
891 // The common case.
892 if (DeclsInContainer.empty())
893 return VisitDeclContext(D);
894
895 // Get all the Decls in the DeclContext, and sort them with the
896 // additional ones we've collected. Then visit them.
897 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
898 I!=E; ++I) {
899 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000900 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
901 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000902 continue;
903 DeclsInContainer.push_back(subDecl);
904 }
905
906 // Now sort the Decls so that they appear in lexical order.
907 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
908 ContainerDeclsSort(SM));
909
910 // Now visit the decls.
911 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
912 E = DeclsInContainer.end(); I != E; ++I) {
913 CXCursor Cursor = MakeCXCursor(*I, TU);
914 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
915 if (!V.hasValue())
916 continue;
917 if (!V.getValue())
918 return false;
919 if (Visit(Cursor, true))
920 return true;
921 }
922 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000923}
924
Douglas Gregorb1373d02010-01-20 20:59:29 +0000925bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000926 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
927 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000928 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000929
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000930 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
931 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
932 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000933 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000934 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000935
Douglas Gregora59e3902010-01-21 23:27:09 +0000936 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000937}
938
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000939bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
940 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
941 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
942 E = PID->protocol_end(); I != E; ++I, ++PL)
943 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
944 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000945
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000946 return VisitObjCContainerDecl(PID);
947}
948
Ted Kremenek23173d72010-05-18 21:09:07 +0000949bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000950 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000951 return true;
952
Ted Kremenek23173d72010-05-18 21:09:07 +0000953 // FIXME: This implements a workaround with @property declarations also being
954 // installed in the DeclContext for the @interface. Eventually this code
955 // should be removed.
956 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
957 if (!CDecl || !CDecl->IsClassExtension())
958 return false;
959
960 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
961 if (!ID)
962 return false;
963
964 IdentifierInfo *PropertyId = PD->getIdentifier();
965 ObjCPropertyDecl *prevDecl =
966 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
967
968 if (!prevDecl)
969 return false;
970
971 // Visit synthesized methods since they will be skipped when visiting
972 // the @interface.
973 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000974 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000975 if (Visit(MakeCXCursor(MD, TU)))
976 return true;
977
978 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000979 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000980 if (Visit(MakeCXCursor(MD, TU)))
981 return true;
982
983 return false;
984}
985
Douglas Gregorb1373d02010-01-20 20:59:29 +0000986bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000987 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988 if (D->getSuperClass() &&
989 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000991 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000992 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000994 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
995 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
996 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000997 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000998 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999
Douglas Gregora59e3902010-01-21 23:27:09 +00001000 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001001}
1002
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001003bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1004 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001005}
1006
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001007bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001008 // 'ID' could be null when dealing with invalid code.
1009 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1010 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001013 return VisitObjCImplDecl(D);
1014}
1015
1016bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1017#if 0
1018 // Issue callbacks for super class.
1019 // FIXME: No source location information!
1020 if (D->getSuperClass() &&
1021 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001023 TU)))
1024 return true;
1025#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001027 return VisitObjCImplDecl(D);
1028}
1029
1030bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1031 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1032 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1033 E = D->protocol_end();
1034 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001035 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001036 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037
1038 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001039}
1040
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001041bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1042 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1043 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1044 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001047}
1048
Douglas Gregora4ffd852010-11-17 01:03:52 +00001049bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1050 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1051 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1052
1053 return false;
1054}
1055
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001056bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1057 return VisitDeclContext(D);
1058}
1059
Douglas Gregor69319002010-08-31 23:48:11 +00001060bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001061 // Visit nested-name-specifier.
1062 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1063 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1064 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001065
1066 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1067 D->getTargetNameLoc(), TU));
1068}
1069
Douglas Gregor7e242562010-09-01 19:52:22 +00001070bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001071 // Visit nested-name-specifier.
1072 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1073 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1074 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001075
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001076 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1077 return true;
1078
Douglas Gregor7e242562010-09-01 19:52:22 +00001079 return VisitDeclarationNameInfo(D->getNameInfo());
1080}
1081
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001082bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001083 // Visit nested-name-specifier.
1084 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1085 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1086 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001087
1088 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1089 D->getIdentLocation(), TU));
1090}
1091
Douglas Gregor7e242562010-09-01 19:52:22 +00001092bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001093 // Visit nested-name-specifier.
1094 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1095 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1096 return true;
1097
Douglas Gregor7e242562010-09-01 19:52:22 +00001098 return VisitDeclarationNameInfo(D->getNameInfo());
1099}
1100
1101bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1102 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001103 // Visit nested-name-specifier.
1104 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1105 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1106 return true;
1107
Douglas Gregor7e242562010-09-01 19:52:22 +00001108 return false;
1109}
1110
Douglas Gregor01829d32010-08-31 14:41:23 +00001111bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1112 switch (Name.getName().getNameKind()) {
1113 case clang::DeclarationName::Identifier:
1114 case clang::DeclarationName::CXXLiteralOperatorName:
1115 case clang::DeclarationName::CXXOperatorName:
1116 case clang::DeclarationName::CXXUsingDirective:
1117 return false;
1118
1119 case clang::DeclarationName::CXXConstructorName:
1120 case clang::DeclarationName::CXXDestructorName:
1121 case clang::DeclarationName::CXXConversionFunctionName:
1122 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1123 return Visit(TSInfo->getTypeLoc());
1124 return false;
1125
1126 case clang::DeclarationName::ObjCZeroArgSelector:
1127 case clang::DeclarationName::ObjCOneArgSelector:
1128 case clang::DeclarationName::ObjCMultiArgSelector:
1129 // FIXME: Per-identifier location info?
1130 return false;
1131 }
1132
1133 return false;
1134}
1135
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001136bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1137 SourceRange Range) {
1138 // FIXME: This whole routine is a hack to work around the lack of proper
1139 // source information in nested-name-specifiers (PR5791). Since we do have
1140 // a beginning source location, we can visit the first component of the
1141 // nested-name-specifier, if it's a single-token component.
1142 if (!NNS)
1143 return false;
1144
1145 // Get the first component in the nested-name-specifier.
1146 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1147 NNS = Prefix;
1148
1149 switch (NNS->getKind()) {
1150 case NestedNameSpecifier::Namespace:
1151 // FIXME: The token at this source location might actually have been a
1152 // namespace alias, but we don't model that. Lame!
1153 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1154 TU));
1155
1156 case NestedNameSpecifier::TypeSpec: {
1157 // If the type has a form where we know that the beginning of the source
1158 // range matches up with a reference cursor. Visit the appropriate reference
1159 // cursor.
1160 Type *T = NNS->getAsType();
1161 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1162 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1163 if (const TagType *Tag = dyn_cast<TagType>(T))
1164 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1165 if (const TemplateSpecializationType *TST
1166 = dyn_cast<TemplateSpecializationType>(T))
1167 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1168 break;
1169 }
1170
1171 case NestedNameSpecifier::TypeSpecWithTemplate:
1172 case NestedNameSpecifier::Global:
1173 case NestedNameSpecifier::Identifier:
1174 break;
1175 }
1176
1177 return false;
1178}
1179
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001180bool CursorVisitor::VisitTemplateParameters(
1181 const TemplateParameterList *Params) {
1182 if (!Params)
1183 return false;
1184
1185 for (TemplateParameterList::const_iterator P = Params->begin(),
1186 PEnd = Params->end();
1187 P != PEnd; ++P) {
1188 if (Visit(MakeCXCursor(*P, TU)))
1189 return true;
1190 }
1191
1192 return false;
1193}
1194
Douglas Gregor0b36e612010-08-31 20:37:03 +00001195bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1196 switch (Name.getKind()) {
1197 case TemplateName::Template:
1198 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1199
1200 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001201 // Visit the overloaded template set.
1202 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1203 return true;
1204
Douglas Gregor0b36e612010-08-31 20:37:03 +00001205 return false;
1206
1207 case TemplateName::DependentTemplate:
1208 // FIXME: Visit nested-name-specifier.
1209 return false;
1210
1211 case TemplateName::QualifiedTemplate:
1212 // FIXME: Visit nested-name-specifier.
1213 return Visit(MakeCursorTemplateRef(
1214 Name.getAsQualifiedTemplateName()->getDecl(),
1215 Loc, TU));
1216 }
1217
1218 return false;
1219}
1220
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001221bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1222 switch (TAL.getArgument().getKind()) {
1223 case TemplateArgument::Null:
1224 case TemplateArgument::Integral:
1225 return false;
1226
1227 case TemplateArgument::Pack:
1228 // FIXME: Implement when variadic templates come along.
1229 return false;
1230
1231 case TemplateArgument::Type:
1232 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1233 return Visit(TSInfo->getTypeLoc());
1234 return false;
1235
1236 case TemplateArgument::Declaration:
1237 if (Expr *E = TAL.getSourceDeclExpression())
1238 return Visit(MakeCXCursor(E, StmtParent, TU));
1239 return false;
1240
1241 case TemplateArgument::Expression:
1242 if (Expr *E = TAL.getSourceExpression())
1243 return Visit(MakeCXCursor(E, StmtParent, TU));
1244 return false;
1245
1246 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001247 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1248 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001249 }
1250
1251 return false;
1252}
1253
Ted Kremeneka0536d82010-05-07 01:04:29 +00001254bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1255 return VisitDeclContext(D);
1256}
1257
Douglas Gregor01829d32010-08-31 14:41:23 +00001258bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1259 return Visit(TL.getUnqualifiedLoc());
1260}
1261
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001262bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001263 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001264
1265 // Some builtin types (such as Objective-C's "id", "sel", and
1266 // "Class") have associated declarations. Create cursors for those.
1267 QualType VisitType;
1268 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001269 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001271 case BuiltinType::Char_U:
1272 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273 case BuiltinType::Char16:
1274 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001275 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 case BuiltinType::UInt:
1277 case BuiltinType::ULong:
1278 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001279 case BuiltinType::UInt128:
1280 case BuiltinType::Char_S:
1281 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001282 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001283 case BuiltinType::Short:
1284 case BuiltinType::Int:
1285 case BuiltinType::Long:
1286 case BuiltinType::LongLong:
1287 case BuiltinType::Int128:
1288 case BuiltinType::Float:
1289 case BuiltinType::Double:
1290 case BuiltinType::LongDouble:
1291 case BuiltinType::NullPtr:
1292 case BuiltinType::Overload:
1293 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001294 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001295
1296 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001297 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001298
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001299 case BuiltinType::ObjCId:
1300 VisitType = Context.getObjCIdType();
1301 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001302
1303 case BuiltinType::ObjCClass:
1304 VisitType = Context.getObjCClassType();
1305 break;
1306
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001307 case BuiltinType::ObjCSel:
1308 VisitType = Context.getObjCSelType();
1309 break;
1310 }
1311
1312 if (!VisitType.isNull()) {
1313 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001314 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001315 TU));
1316 }
1317
1318 return false;
1319}
1320
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001321bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1322 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1323}
1324
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001325bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1326 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1327}
1328
1329bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1330 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1331}
1332
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001333bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001334 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001335 // no context information with which we can match up the depth/index in the
1336 // type to the appropriate
1337 return false;
1338}
1339
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1341 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1342 return true;
1343
John McCallc12c5bb2010-05-15 11:32:37 +00001344 return false;
1345}
1346
1347bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1348 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1349 return true;
1350
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001351 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1352 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1353 TU)))
1354 return true;
1355 }
1356
1357 return false;
1358}
1359
1360bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001361 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001362}
1363
1364bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1365 return Visit(TL.getPointeeLoc());
1366}
1367
1368bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1369 return Visit(TL.getPointeeLoc());
1370}
1371
1372bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1373 return Visit(TL.getPointeeLoc());
1374}
1375
1376bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378}
1379
1380bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001381 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001382}
1383
Douglas Gregor01829d32010-08-31 14:41:23 +00001384bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1385 bool SkipResultType) {
1386 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387 return true;
1388
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001389 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001390 if (Decl *D = TL.getArg(I))
1391 if (Visit(MakeCXCursor(D, TU)))
1392 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393
1394 return false;
1395}
1396
1397bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1398 if (Visit(TL.getElementLoc()))
1399 return true;
1400
1401 if (Expr *Size = TL.getSizeExpr())
1402 return Visit(MakeCXCursor(Size, StmtParent, TU));
1403
1404 return false;
1405}
1406
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001407bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1408 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001409 // Visit the template name.
1410 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1411 TL.getTemplateNameLoc()))
1412 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001413
1414 // Visit the template arguments.
1415 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1416 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1417 return true;
1418
1419 return false;
1420}
1421
Douglas Gregor2332c112010-01-21 20:48:56 +00001422bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1423 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1424}
1425
1426bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1427 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1428 return Visit(TSInfo->getTypeLoc());
1429
1430 return false;
1431}
1432
Ted Kremenek3064ef92010-08-27 21:34:58 +00001433bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1434 if (D->isDefinition()) {
1435 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1436 E = D->bases_end(); I != E; ++I) {
1437 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1438 return true;
1439 }
1440 }
1441
1442 return VisitTagDecl(D);
1443}
1444
Ted Kremenek09dfa372010-02-18 05:46:33 +00001445bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001446 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1447 i != e; ++i)
1448 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001449 return true;
1450
1451 return false;
1452}
1453
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001454//===----------------------------------------------------------------------===//
1455// Data-recursive visitor methods.
1456//===----------------------------------------------------------------------===//
1457
Ted Kremenek28a71942010-11-13 00:36:47 +00001458namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001459#define DEF_JOB(NAME, DATA, KIND)\
1460class NAME : public VisitorJob {\
1461public:\
1462 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1463 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001464 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001465};
1466
1467DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1468DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001469DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001470DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001471DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1472 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001473#undef DEF_JOB
1474
1475class DeclVisit : public VisitorJob {
1476public:
1477 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1478 VisitorJob(parent, VisitorJob::DeclVisitKind,
1479 d, isFirst ? (void*) 1 : (void*) 0) {}
1480 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001481 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001482 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001483 Decl *get() const { return static_cast<Decl*>(data[0]); }
1484 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001485};
Ted Kremenek035dc412010-11-13 00:36:50 +00001486class TypeLocVisit : public VisitorJob {
1487public:
1488 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1489 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1490 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1491
1492 static bool classof(const VisitorJob *VJ) {
1493 return VJ->getKind() == TypeLocVisitKind;
1494 }
1495
Ted Kremenek82f3c502010-11-15 22:23:26 +00001496 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001497 QualType T = QualType::getFromOpaquePtr(data[0]);
1498 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001499 }
1500};
1501
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001502class LabelRefVisit : public VisitorJob {
1503public:
1504 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1505 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1506 (void*) labelLoc.getRawEncoding()) {}
1507
1508 static bool classof(const VisitorJob *VJ) {
1509 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1510 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001511 LabelStmt *get() const { return static_cast<LabelStmt*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001512 SourceLocation getLoc() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001513 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); }
1514};
1515class NestedNameSpecifierVisit : public VisitorJob {
1516public:
1517 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1518 CXCursor parent)
1519 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
1520 NS, (void*) R.getBegin().getRawEncoding(),
1521 (void*) R.getEnd().getRawEncoding()) {}
1522 static bool classof(const VisitorJob *VJ) {
1523 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1524 }
1525 NestedNameSpecifier *get() const {
1526 return static_cast<NestedNameSpecifier*>(data[0]);
1527 }
1528 SourceRange getSourceRange() const {
1529 SourceLocation A =
1530 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1531 SourceLocation B =
1532 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1533 return SourceRange(A, B);
1534 }
1535};
1536class DeclarationNameInfoVisit : public VisitorJob {
1537public:
1538 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1539 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1540 static bool classof(const VisitorJob *VJ) {
1541 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1542 }
1543 DeclarationNameInfo get() const {
1544 Stmt *S = static_cast<Stmt*>(data[0]);
1545 switch (S->getStmtClass()) {
1546 default:
1547 llvm_unreachable("Unhandled Stmt");
1548 case Stmt::CXXDependentScopeMemberExprClass:
1549 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1550 case Stmt::DependentScopeDeclRefExprClass:
1551 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1552 }
1553 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001554};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001555class MemberRefVisit : public VisitorJob {
1556public:
1557 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1558 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1559 (void*) L.getRawEncoding()) {}
1560 static bool classof(const VisitorJob *VJ) {
1561 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1562 }
1563 FieldDecl *get() const {
1564 return static_cast<FieldDecl*>(data[0]);
1565 }
1566 SourceLocation getLoc() const {
1567 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1568 }
1569};
Ted Kremenek28a71942010-11-13 00:36:47 +00001570class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1571 VisitorWorkList &WL;
1572 CXCursor Parent;
1573public:
1574 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1575 : WL(wl), Parent(parent) {}
1576
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001577 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001578 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001579 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001580 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001581 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001582 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001583 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001584 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001585 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001586 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001587 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001588 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001589 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001590 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001591 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001592 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001593 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001594 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001595 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1596 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001597 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001598 void VisitIfStmt(IfStmt *If);
1599 void VisitInitListExpr(InitListExpr *IE);
1600 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001601 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001602 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001603 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1604 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001605 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001606 void VisitStmt(Stmt *S);
1607 void VisitSwitchStmt(SwitchStmt *S);
1608 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001609 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001610 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001611 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001612 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001613
1614private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001615 void AddDeclarationNameInfo(Stmt *S);
1616 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001617 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001618 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001619 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001620 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001621 void AddTypeLoc(TypeSourceInfo *TI);
1622 void EnqueueChildren(Stmt *S);
1623};
1624} // end anonyous namespace
1625
Ted Kremenekf64d8032010-11-18 00:02:32 +00001626void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1627 // 'S' should always be non-null, since it comes from the
1628 // statement we are visiting.
1629 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1630}
1631void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1632 SourceRange R) {
1633 if (N)
1634 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1635}
Ted Kremenek28a71942010-11-13 00:36:47 +00001636void EnqueueVisitor::AddStmt(Stmt *S) {
1637 if (S)
1638 WL.push_back(StmtVisit(S, Parent));
1639}
Ted Kremenek035dc412010-11-13 00:36:50 +00001640void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001641 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001642 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001643}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001644void EnqueueVisitor::
1645 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1646 if (A)
1647 WL.push_back(ExplicitTemplateArgsVisit(
1648 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1649}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001650void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1651 if (D)
1652 WL.push_back(MemberRefVisit(D, L, Parent));
1653}
Ted Kremenek28a71942010-11-13 00:36:47 +00001654void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1655 if (TI)
1656 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1657 }
1658void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001659 unsigned size = WL.size();
1660 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1661 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001662 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001663 }
1664 if (size == WL.size())
1665 return;
1666 // Now reverse the entries we just added. This will match the DFS
1667 // ordering performed by the worklist.
1668 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1669 std::reverse(I, E);
1670}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001671void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1672 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1673}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001674void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1675 AddDecl(B->getBlockDecl());
1676}
Ted Kremenek28a71942010-11-13 00:36:47 +00001677void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1678 EnqueueChildren(E);
1679 AddTypeLoc(E->getTypeSourceInfo());
1680}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001681void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1682 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1683 E = S->body_rend(); I != E; ++I) {
1684 AddStmt(*I);
1685 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001686}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001687void EnqueueVisitor::
1688VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1689 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1690 AddDeclarationNameInfo(E);
1691 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1692 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1693 if (!E->isImplicitAccess())
1694 AddStmt(E->getBase());
1695}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001696void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1697 // Enqueue the initializer or constructor arguments.
1698 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1699 AddStmt(E->getConstructorArg(I-1));
1700 // Enqueue the array size, if any.
1701 AddStmt(E->getArraySize());
1702 // Enqueue the allocated type.
1703 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1704 // Enqueue the placement arguments.
1705 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1706 AddStmt(E->getPlacementArg(I-1));
1707}
Ted Kremenek28a71942010-11-13 00:36:47 +00001708void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001709 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1710 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001711 AddStmt(CE->getCallee());
1712 AddStmt(CE->getArg(0));
1713}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001714void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1715 // Visit the name of the type being destroyed.
1716 AddTypeLoc(E->getDestroyedTypeInfo());
1717 // Visit the scope type that looks disturbingly like the nested-name-specifier
1718 // but isn't.
1719 AddTypeLoc(E->getScopeTypeInfo());
1720 // Visit the nested-name-specifier.
1721 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1722 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1723 // Visit base expression.
1724 AddStmt(E->getBase());
1725}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001726void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1727 AddTypeLoc(E->getTypeSourceInfo());
1728}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001729void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1730 EnqueueChildren(E);
1731 AddTypeLoc(E->getTypeSourceInfo());
1732}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001733void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1734 EnqueueChildren(E);
1735 if (E->isTypeOperand())
1736 AddTypeLoc(E->getTypeOperandSourceInfo());
1737}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001738
1739void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1740 *E) {
1741 EnqueueChildren(E);
1742 AddTypeLoc(E->getTypeSourceInfo());
1743}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001744void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1745 EnqueueChildren(E);
1746 if (E->isTypeOperand())
1747 AddTypeLoc(E->getTypeOperandSourceInfo());
1748}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001749void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001750 if (DR->hasExplicitTemplateArgs()) {
1751 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1752 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001753 WL.push_back(DeclRefExprParts(DR, Parent));
1754}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001755void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1756 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1757 AddDeclarationNameInfo(E);
1758 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1759 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1760}
Ted Kremenek035dc412010-11-13 00:36:50 +00001761void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1762 unsigned size = WL.size();
1763 bool isFirst = true;
1764 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1765 D != DEnd; ++D) {
1766 AddDecl(*D, isFirst);
1767 isFirst = false;
1768 }
1769 if (size == WL.size())
1770 return;
1771 // Now reverse the entries we just added. This will match the DFS
1772 // ordering performed by the worklist.
1773 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1774 std::reverse(I, E);
1775}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001776void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1777 AddStmt(E->getInit());
1778 typedef DesignatedInitExpr::Designator Designator;
1779 for (DesignatedInitExpr::reverse_designators_iterator
1780 D = E->designators_rbegin(), DEnd = E->designators_rend();
1781 D != DEnd; ++D) {
1782 if (D->isFieldDesignator()) {
1783 if (FieldDecl *Field = D->getField())
1784 AddMemberRef(Field, D->getFieldLoc());
1785 continue;
1786 }
1787 if (D->isArrayDesignator()) {
1788 AddStmt(E->getArrayIndex(*D));
1789 continue;
1790 }
1791 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1792 AddStmt(E->getArrayRangeEnd(*D));
1793 AddStmt(E->getArrayRangeStart(*D));
1794 }
1795}
Ted Kremenek28a71942010-11-13 00:36:47 +00001796void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1797 EnqueueChildren(E);
1798 AddTypeLoc(E->getTypeInfoAsWritten());
1799}
1800void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1801 AddStmt(FS->getBody());
1802 AddStmt(FS->getInc());
1803 AddStmt(FS->getCond());
1804 AddDecl(FS->getConditionVariable());
1805 AddStmt(FS->getInit());
1806}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001807void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1808 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1809}
Ted Kremenek28a71942010-11-13 00:36:47 +00001810void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1811 AddStmt(If->getElse());
1812 AddStmt(If->getThen());
1813 AddStmt(If->getCond());
1814 AddDecl(If->getConditionVariable());
1815}
1816void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1817 // We care about the syntactic form of the initializer list, only.
1818 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1819 IE = Syntactic;
1820 EnqueueChildren(IE);
1821}
1822void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001823 WL.push_back(MemberExprParts(M, Parent));
1824
1825 // If the base of the member access expression is an implicit 'this', don't
1826 // visit it.
1827 // FIXME: If we ever want to show these implicit accesses, this will be
1828 // unfortunate. However, clang_getCursor() relies on this behavior.
1829 if (CXXThisExpr *This
1830 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1831 if (This->isImplicit())
1832 return;
1833
Ted Kremenek28a71942010-11-13 00:36:47 +00001834 AddStmt(M->getBase());
1835}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001836void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1837 AddTypeLoc(E->getEncodedTypeSourceInfo());
1838}
Ted Kremenek28a71942010-11-13 00:36:47 +00001839void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1840 EnqueueChildren(M);
1841 AddTypeLoc(M->getClassReceiverTypeInfo());
1842}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001843void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1844 // Visit the components of the offsetof expression.
1845 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1846 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1847 const OffsetOfNode &Node = E->getComponent(I-1);
1848 switch (Node.getKind()) {
1849 case OffsetOfNode::Array:
1850 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1851 break;
1852 case OffsetOfNode::Field:
1853 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1854 break;
1855 case OffsetOfNode::Identifier:
1856 case OffsetOfNode::Base:
1857 continue;
1858 }
1859 }
1860 // Visit the type into which we're computing the offset.
1861 AddTypeLoc(E->getTypeSourceInfo());
1862}
Ted Kremenek28a71942010-11-13 00:36:47 +00001863void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001864 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001865 WL.push_back(OverloadExprParts(E, Parent));
1866}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001867void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1868 EnqueueChildren(E);
1869 if (E->isArgumentType())
1870 AddTypeLoc(E->getArgumentTypeInfo());
1871}
Ted Kremenek28a71942010-11-13 00:36:47 +00001872void EnqueueVisitor::VisitStmt(Stmt *S) {
1873 EnqueueChildren(S);
1874}
1875void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1876 AddStmt(S->getBody());
1877 AddStmt(S->getCond());
1878 AddDecl(S->getConditionVariable());
1879}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001880
Ted Kremenek28a71942010-11-13 00:36:47 +00001881void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1882 AddStmt(W->getBody());
1883 AddStmt(W->getCond());
1884 AddDecl(W->getConditionVariable());
1885}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001886void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1887 AddTypeLoc(E->getQueriedTypeSourceInfo());
1888}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001889
1890void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00001891 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00001892 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00001893}
1894
Ted Kremenek28a71942010-11-13 00:36:47 +00001895void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1896 VisitOverloadExpr(U);
1897 if (!U->isImplicitAccess())
1898 AddStmt(U->getBase());
1899}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001900void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1901 AddStmt(E->getSubExpr());
1902 AddTypeLoc(E->getWrittenTypeInfo());
1903}
Ted Kremenek60458782010-11-12 21:34:16 +00001904
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001905void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001906 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001907}
1908
1909bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1910 if (RegionOfInterest.isValid()) {
1911 SourceRange Range = getRawCursorExtent(C);
1912 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1913 return false;
1914 }
1915 return true;
1916}
1917
1918bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1919 while (!WL.empty()) {
1920 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001921 VisitorJob LI = WL.back();
1922 WL.pop_back();
1923
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001924 // Set the Parent field, then back to its old value once we're done.
1925 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1926
1927 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001928 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001929 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001930 if (!D)
1931 continue;
1932
1933 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001934 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001935 return true;
1936
1937 continue;
1938 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001939 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1940 const ExplicitTemplateArgumentList *ArgList =
1941 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1942 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1943 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1944 Arg != ArgEnd; ++Arg) {
1945 if (VisitTemplateArgumentLoc(*Arg))
1946 return true;
1947 }
1948 continue;
1949 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001950 case VisitorJob::TypeLocVisitKind: {
1951 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001952 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001953 return true;
1954 continue;
1955 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001956 case VisitorJob::LabelRefVisitKind: {
1957 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1958 if (Visit(MakeCursorLabelRef(LS,
1959 cast<LabelRefVisit>(&LI)->getLoc(),
1960 TU)))
1961 return true;
1962 continue;
1963 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001964 case VisitorJob::NestedNameSpecifierVisitKind: {
1965 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
1966 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
1967 return true;
1968 continue;
1969 }
1970 case VisitorJob::DeclarationNameInfoVisitKind: {
1971 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
1972 ->get()))
1973 return true;
1974 continue;
1975 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00001976 case VisitorJob::MemberRefVisitKind: {
1977 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
1978 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
1979 return true;
1980 continue;
1981 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001982 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001983 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001984 if (!S)
1985 continue;
1986
Ted Kremenekf1107452010-11-12 18:26:56 +00001987 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001988 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001989 if (!IsInRegionOfInterest(Cursor))
1990 continue;
1991 switch (Visitor(Cursor, Parent, ClientData)) {
1992 case CXChildVisit_Break: return true;
1993 case CXChildVisit_Continue: break;
1994 case CXChildVisit_Recurse:
1995 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00001996 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001997 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001998 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001999 }
2000 case VisitorJob::MemberExprPartsKind: {
2001 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002002 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002003
2004 // Visit the nested-name-specifier
2005 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2006 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2007 return true;
2008
2009 // Visit the declaration name.
2010 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2011 return true;
2012
2013 // Visit the explicitly-specified template arguments, if any.
2014 if (M->hasExplicitTemplateArgs()) {
2015 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2016 *ArgEnd = Arg + M->getNumTemplateArgs();
2017 Arg != ArgEnd; ++Arg) {
2018 if (VisitTemplateArgumentLoc(*Arg))
2019 return true;
2020 }
2021 }
2022 continue;
2023 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002024 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002025 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002026 // Visit nested-name-specifier, if present.
2027 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2028 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2029 return true;
2030 // Visit declaration name.
2031 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2032 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002033 continue;
2034 }
Ted Kremenek60458782010-11-12 21:34:16 +00002035 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002036 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002037 // Visit the nested-name-specifier.
2038 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2039 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2040 return true;
2041 // Visit the declaration name.
2042 if (VisitDeclarationNameInfo(O->getNameInfo()))
2043 return true;
2044 // Visit the overloaded declaration reference.
2045 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2046 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002047 continue;
2048 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002049 }
2050 }
2051 return false;
2052}
2053
Ted Kremenekcdba6592010-11-18 00:42:18 +00002054bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002055 VisitorWorkList *WL = 0;
2056 if (!WorkListFreeList.empty()) {
2057 WL = WorkListFreeList.back();
2058 WL->clear();
2059 WorkListFreeList.pop_back();
2060 }
2061 else {
2062 WL = new VisitorWorkList();
2063 WorkListCache.push_back(WL);
2064 }
2065 EnqueueWorkList(*WL, S);
2066 bool result = RunVisitorWorkList(*WL);
2067 WorkListFreeList.push_back(WL);
2068 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002069}
2070
2071//===----------------------------------------------------------------------===//
2072// Misc. API hooks.
2073//===----------------------------------------------------------------------===//
2074
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002075static llvm::sys::Mutex EnableMultithreadingMutex;
2076static bool EnabledMultithreading;
2077
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002078extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002079CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2080 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002081 // Disable pretty stack trace functionality, which will otherwise be a very
2082 // poor citizen of the world and set up all sorts of signal handlers.
2083 llvm::DisablePrettyStackTrace = true;
2084
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002085 // We use crash recovery to make some of our APIs more reliable, implicitly
2086 // enable it.
2087 llvm::CrashRecoveryContext::Enable();
2088
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002089 // Enable support for multithreading in LLVM.
2090 {
2091 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2092 if (!EnabledMultithreading) {
2093 llvm::llvm_start_multithreaded();
2094 EnabledMultithreading = true;
2095 }
2096 }
2097
Douglas Gregora030b7c2010-01-22 20:35:53 +00002098 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002099 if (excludeDeclarationsFromPCH)
2100 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002101 if (displayDiagnostics)
2102 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002103 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002104}
2105
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002106void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002107 if (CIdx)
2108 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002109}
2110
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002111CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002112 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002113 if (!CIdx)
2114 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002115
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002116 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002117 FileSystemOptions FileSystemOpts;
2118 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002119
Douglas Gregor28019772010-04-05 23:52:57 +00002120 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002121 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002122 CXXIdx->getOnlyLocalDecls(),
2123 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002124 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002125}
2126
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002127unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002128 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002129 CXTranslationUnit_CacheCompletionResults |
2130 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002131}
2132
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002133CXTranslationUnit
2134clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2135 const char *source_filename,
2136 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002137 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002138 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002139 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002140 return clang_parseTranslationUnit(CIdx, source_filename,
2141 command_line_args, num_command_line_args,
2142 unsaved_files, num_unsaved_files,
2143 CXTranslationUnit_DetailedPreprocessingRecord);
2144}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002145
2146struct ParseTranslationUnitInfo {
2147 CXIndex CIdx;
2148 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002149 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002150 int num_command_line_args;
2151 struct CXUnsavedFile *unsaved_files;
2152 unsigned num_unsaved_files;
2153 unsigned options;
2154 CXTranslationUnit result;
2155};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002156static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002157 ParseTranslationUnitInfo *PTUI =
2158 static_cast<ParseTranslationUnitInfo*>(UserData);
2159 CXIndex CIdx = PTUI->CIdx;
2160 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002161 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002162 int num_command_line_args = PTUI->num_command_line_args;
2163 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2164 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2165 unsigned options = PTUI->options;
2166 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002167
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002168 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002169 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002170
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002171 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2172
Douglas Gregor44c181a2010-07-23 00:33:23 +00002173 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002174 bool CompleteTranslationUnit
2175 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002176 bool CacheCodeCompetionResults
2177 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002178 bool CXXPrecompilePreamble
2179 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2180 bool CXXChainedPCH
2181 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002182
Douglas Gregor5352ac02010-01-28 00:27:43 +00002183 // Configure the diagnostics.
2184 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002185 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2186 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002187
Douglas Gregor4db64a42010-01-23 00:14:00 +00002188 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2189 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002190 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002191 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002192 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002193 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2194 Buffer));
2195 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002196
Douglas Gregorb10daed2010-10-11 16:52:23 +00002197 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002198
Ted Kremenek139ba862009-10-22 00:03:57 +00002199 // The 'source_filename' argument is optional. If the caller does not
2200 // specify it then it is assumed that the source file is specified
2201 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002202 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002203 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002204
2205 // Since the Clang C library is primarily used by batch tools dealing with
2206 // (often very broken) source code, where spell-checking can have a
2207 // significant negative impact on performance (particularly when
2208 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002209 // Only do this if we haven't found a spell-checking-related argument.
2210 bool FoundSpellCheckingArgument = false;
2211 for (int I = 0; I != num_command_line_args; ++I) {
2212 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2213 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2214 FoundSpellCheckingArgument = true;
2215 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002216 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002217 }
2218 if (!FoundSpellCheckingArgument)
2219 Args.push_back("-fno-spell-checking");
2220
2221 Args.insert(Args.end(), command_line_args,
2222 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002223
Douglas Gregor44c181a2010-07-23 00:33:23 +00002224 // Do we need the detailed preprocessing record?
2225 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002226 Args.push_back("-Xclang");
2227 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002228 }
2229
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002230 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002231 llvm::OwningPtr<ASTUnit> Unit(
2232 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2233 Diags,
2234 CXXIdx->getClangResourcesPath(),
2235 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002236 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002237 RemappedFiles.data(),
2238 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002239 PrecompilePreamble,
2240 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002241 CacheCodeCompetionResults,
2242 CXXPrecompilePreamble,
2243 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002244
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002245 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002246 // Make sure to check that 'Unit' is non-NULL.
2247 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2248 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2249 DEnd = Unit->stored_diag_end();
2250 D != DEnd; ++D) {
2251 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2252 CXString Msg = clang_formatDiagnostic(&Diag,
2253 clang_defaultDiagnosticDisplayOptions());
2254 fprintf(stderr, "%s\n", clang_getCString(Msg));
2255 clang_disposeString(Msg);
2256 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002257#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002258 // On Windows, force a flush, since there may be multiple copies of
2259 // stderr and stdout in the file system, all with different buffers
2260 // but writing to the same device.
2261 fflush(stderr);
2262#endif
2263 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002264 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002265
Ted Kremeneka60ed472010-11-16 08:15:36 +00002266 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002267}
2268CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2269 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002270 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002271 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002272 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002273 unsigned num_unsaved_files,
2274 unsigned options) {
2275 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002276 num_command_line_args, unsaved_files,
2277 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002278 llvm::CrashRecoveryContext CRC;
2279
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002280 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002281 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2282 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2283 fprintf(stderr, " 'command_line_args' : [");
2284 for (int i = 0; i != num_command_line_args; ++i) {
2285 if (i)
2286 fprintf(stderr, ", ");
2287 fprintf(stderr, "'%s'", command_line_args[i]);
2288 }
2289 fprintf(stderr, "],\n");
2290 fprintf(stderr, " 'unsaved_files' : [");
2291 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2292 if (i)
2293 fprintf(stderr, ", ");
2294 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2295 unsaved_files[i].Length);
2296 }
2297 fprintf(stderr, "],\n");
2298 fprintf(stderr, " 'options' : %d,\n", options);
2299 fprintf(stderr, "}\n");
2300
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002301 return 0;
2302 }
2303
2304 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002305}
2306
Douglas Gregor19998442010-08-13 15:35:05 +00002307unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2308 return CXSaveTranslationUnit_None;
2309}
2310
2311int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2312 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002313 if (!TU)
2314 return 1;
2315
Ted Kremeneka60ed472010-11-16 08:15:36 +00002316 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002317}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002318
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002319void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002320 if (CTUnit) {
2321 // If the translation unit has been marked as unsafe to free, just discard
2322 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002323 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002324 return;
2325
Ted Kremeneka60ed472010-11-16 08:15:36 +00002326 delete static_cast<ASTUnit *>(CTUnit->TUData);
2327 disposeCXStringPool(CTUnit->StringPool);
2328 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002329 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002330}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002331
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002332unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2333 return CXReparse_None;
2334}
2335
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002336struct ReparseTranslationUnitInfo {
2337 CXTranslationUnit TU;
2338 unsigned num_unsaved_files;
2339 struct CXUnsavedFile *unsaved_files;
2340 unsigned options;
2341 int result;
2342};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002343
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002344static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002345 ReparseTranslationUnitInfo *RTUI =
2346 static_cast<ReparseTranslationUnitInfo*>(UserData);
2347 CXTranslationUnit TU = RTUI->TU;
2348 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2349 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2350 unsigned options = RTUI->options;
2351 (void) options;
2352 RTUI->result = 1;
2353
Douglas Gregorabc563f2010-07-19 21:46:24 +00002354 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002355 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002356
Ted Kremeneka60ed472010-11-16 08:15:36 +00002357 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002358 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002359
2360 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2361 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2362 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2363 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002364 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002365 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2366 Buffer));
2367 }
2368
Douglas Gregor593b0c12010-09-23 18:47:53 +00002369 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2370 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002371}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002372
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002373int clang_reparseTranslationUnit(CXTranslationUnit TU,
2374 unsigned num_unsaved_files,
2375 struct CXUnsavedFile *unsaved_files,
2376 unsigned options) {
2377 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2378 options, 0 };
2379 llvm::CrashRecoveryContext CRC;
2380
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002381 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002382 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002383 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002384 return 1;
2385 }
2386
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002387
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002388 return RTUI.result;
2389}
2390
Douglas Gregordf95a132010-08-09 20:45:32 +00002391
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002392CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002393 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002394 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002395
Ted Kremeneka60ed472010-11-16 08:15:36 +00002396 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002397 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002398}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002399
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002400CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002401 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002402 return Result;
2403}
2404
Ted Kremenekfb480492010-01-13 21:46:36 +00002405} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002406
Ted Kremenekfb480492010-01-13 21:46:36 +00002407//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002408// CXSourceLocation and CXSourceRange Operations.
2409//===----------------------------------------------------------------------===//
2410
Douglas Gregorb9790342010-01-22 21:44:22 +00002411extern "C" {
2412CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002413 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002414 return Result;
2415}
2416
2417unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002418 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2419 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2420 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002421}
2422
2423CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2424 CXFile file,
2425 unsigned line,
2426 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002427 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002428 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002429
Ted Kremeneka60ed472010-11-16 08:15:36 +00002430 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002431 SourceLocation SLoc
2432 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002433 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002434 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002435 if (SLoc.isInvalid()) return clang_getNullLocation();
2436
2437 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2438}
2439
2440CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2441 CXFile file,
2442 unsigned offset) {
2443 if (!tu || !file)
2444 return clang_getNullLocation();
2445
Ted Kremeneka60ed472010-11-16 08:15:36 +00002446 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002447 SourceLocation Start
2448 = CXXUnit->getSourceManager().getLocation(
2449 static_cast<const FileEntry *>(file),
2450 1, 1);
2451 if (Start.isInvalid()) return clang_getNullLocation();
2452
2453 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2454
2455 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002456
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002457 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002458}
2459
Douglas Gregor5352ac02010-01-28 00:27:43 +00002460CXSourceRange clang_getNullRange() {
2461 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2462 return Result;
2463}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002464
Douglas Gregor5352ac02010-01-28 00:27:43 +00002465CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2466 if (begin.ptr_data[0] != end.ptr_data[0] ||
2467 begin.ptr_data[1] != end.ptr_data[1])
2468 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002469
2470 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002471 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002472 return Result;
2473}
2474
Douglas Gregor46766dc2010-01-26 19:19:08 +00002475void clang_getInstantiationLocation(CXSourceLocation location,
2476 CXFile *file,
2477 unsigned *line,
2478 unsigned *column,
2479 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002480 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2481
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002482 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002483 if (file)
2484 *file = 0;
2485 if (line)
2486 *line = 0;
2487 if (column)
2488 *column = 0;
2489 if (offset)
2490 *offset = 0;
2491 return;
2492 }
2493
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002494 const SourceManager &SM =
2495 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002496 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002497
2498 if (file)
2499 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2500 if (line)
2501 *line = SM.getInstantiationLineNumber(InstLoc);
2502 if (column)
2503 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002504 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002505 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002506}
2507
Douglas Gregora9b06d42010-11-09 06:24:54 +00002508void clang_getSpellingLocation(CXSourceLocation location,
2509 CXFile *file,
2510 unsigned *line,
2511 unsigned *column,
2512 unsigned *offset) {
2513 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2514
2515 if (!location.ptr_data[0] || Loc.isInvalid()) {
2516 if (file)
2517 *file = 0;
2518 if (line)
2519 *line = 0;
2520 if (column)
2521 *column = 0;
2522 if (offset)
2523 *offset = 0;
2524 return;
2525 }
2526
2527 const SourceManager &SM =
2528 *static_cast<const SourceManager*>(location.ptr_data[0]);
2529 SourceLocation SpellLoc = Loc;
2530 if (SpellLoc.isMacroID()) {
2531 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2532 if (SimpleSpellingLoc.isFileID() &&
2533 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2534 SpellLoc = SimpleSpellingLoc;
2535 else
2536 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2537 }
2538
2539 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2540 FileID FID = LocInfo.first;
2541 unsigned FileOffset = LocInfo.second;
2542
2543 if (file)
2544 *file = (void *)SM.getFileEntryForID(FID);
2545 if (line)
2546 *line = SM.getLineNumber(FID, FileOffset);
2547 if (column)
2548 *column = SM.getColumnNumber(FID, FileOffset);
2549 if (offset)
2550 *offset = FileOffset;
2551}
2552
Douglas Gregor1db19de2010-01-19 21:36:55 +00002553CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002554 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002555 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002556 return Result;
2557}
2558
2559CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002560 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002561 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002562 return Result;
2563}
2564
Douglas Gregorb9790342010-01-22 21:44:22 +00002565} // end: extern "C"
2566
Douglas Gregor1db19de2010-01-19 21:36:55 +00002567//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002568// CXFile Operations.
2569//===----------------------------------------------------------------------===//
2570
2571extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002572CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002573 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002574 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002575
Steve Naroff88145032009-10-27 14:35:18 +00002576 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002577 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002578}
2579
2580time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002581 if (!SFile)
2582 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002583
Steve Naroff88145032009-10-27 14:35:18 +00002584 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2585 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002586}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002587
Douglas Gregorb9790342010-01-22 21:44:22 +00002588CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2589 if (!tu)
2590 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002591
Ted Kremeneka60ed472010-11-16 08:15:36 +00002592 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002593
Douglas Gregorb9790342010-01-22 21:44:22 +00002594 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002595 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002596}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002597
Ted Kremenekfb480492010-01-13 21:46:36 +00002598} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002599
Ted Kremenekfb480492010-01-13 21:46:36 +00002600//===----------------------------------------------------------------------===//
2601// CXCursor Operations.
2602//===----------------------------------------------------------------------===//
2603
Ted Kremenekfb480492010-01-13 21:46:36 +00002604static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002605 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2606 return getDeclFromExpr(CE->getSubExpr());
2607
Ted Kremenekfb480492010-01-13 21:46:36 +00002608 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2609 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002610 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2611 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002612 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2613 return ME->getMemberDecl();
2614 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2615 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002616 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002617 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002618
Ted Kremenekfb480492010-01-13 21:46:36 +00002619 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2620 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002621 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2622 if (!CE->isElidable())
2623 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002624 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2625 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002626
Douglas Gregordb1314e2010-10-01 21:11:22 +00002627 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2628 return PE->getProtocol();
2629
Ted Kremenekfb480492010-01-13 21:46:36 +00002630 return 0;
2631}
2632
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002633static SourceLocation getLocationFromExpr(Expr *E) {
2634 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2635 return /*FIXME:*/Msg->getLeftLoc();
2636 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2637 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002638 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2639 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002640 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2641 return Member->getMemberLoc();
2642 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2643 return Ivar->getLocation();
2644 return E->getLocStart();
2645}
2646
Ted Kremenekfb480492010-01-13 21:46:36 +00002647extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002648
2649unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002650 CXCursorVisitor visitor,
2651 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002652 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2653 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002654 return CursorVis.VisitChildren(parent);
2655}
2656
David Chisnall3387c652010-11-03 14:12:26 +00002657#ifndef __has_feature
2658#define __has_feature(x) 0
2659#endif
2660#if __has_feature(blocks)
2661typedef enum CXChildVisitResult
2662 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2663
2664static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2665 CXClientData client_data) {
2666 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2667 return block(cursor, parent);
2668}
2669#else
2670// If we are compiled with a compiler that doesn't have native blocks support,
2671// define and call the block manually, so the
2672typedef struct _CXChildVisitResult
2673{
2674 void *isa;
2675 int flags;
2676 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002677 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2678 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002679} *CXCursorVisitorBlock;
2680
2681static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2682 CXClientData client_data) {
2683 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2684 return block->invoke(block, cursor, parent);
2685}
2686#endif
2687
2688
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002689unsigned clang_visitChildrenWithBlock(CXCursor parent,
2690 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002691 return clang_visitChildren(parent, visitWithBlock, block);
2692}
2693
Douglas Gregor78205d42010-01-20 21:45:58 +00002694static CXString getDeclSpelling(Decl *D) {
2695 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002696 if (!ND) {
2697 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2698 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2699 return createCXString(Property->getIdentifier()->getName());
2700
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002701 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002702 }
2703
Douglas Gregor78205d42010-01-20 21:45:58 +00002704 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002705 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002706
Douglas Gregor78205d42010-01-20 21:45:58 +00002707 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2708 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2709 // and returns different names. NamedDecl returns the class name and
2710 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002711 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002712
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002713 if (isa<UsingDirectiveDecl>(D))
2714 return createCXString("");
2715
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002716 llvm::SmallString<1024> S;
2717 llvm::raw_svector_ostream os(S);
2718 ND->printName(os);
2719
2720 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002721}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002722
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002723CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002724 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002725 return clang_getTranslationUnitSpelling(
2726 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002727
Steve Narofff334b4e2009-09-02 18:26:48 +00002728 if (clang_isReference(C.kind)) {
2729 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002730 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002731 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002732 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002733 }
2734 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002735 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002736 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002737 }
2738 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002739 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002740 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002741 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002742 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002743 case CXCursor_CXXBaseSpecifier: {
2744 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2745 return createCXString(B->getType().getAsString());
2746 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002747 case CXCursor_TypeRef: {
2748 TypeDecl *Type = getCursorTypeRef(C).first;
2749 assert(Type && "Missing type decl");
2750
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002751 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2752 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002753 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002754 case CXCursor_TemplateRef: {
2755 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002756 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002757
2758 return createCXString(Template->getNameAsString());
2759 }
Douglas Gregor69319002010-08-31 23:48:11 +00002760
2761 case CXCursor_NamespaceRef: {
2762 NamedDecl *NS = getCursorNamespaceRef(C).first;
2763 assert(NS && "Missing namespace decl");
2764
2765 return createCXString(NS->getNameAsString());
2766 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002767
Douglas Gregora67e03f2010-09-09 21:42:20 +00002768 case CXCursor_MemberRef: {
2769 FieldDecl *Field = getCursorMemberRef(C).first;
2770 assert(Field && "Missing member decl");
2771
2772 return createCXString(Field->getNameAsString());
2773 }
2774
Douglas Gregor36897b02010-09-10 00:22:18 +00002775 case CXCursor_LabelRef: {
2776 LabelStmt *Label = getCursorLabelRef(C).first;
2777 assert(Label && "Missing label");
2778
2779 return createCXString(Label->getID()->getName());
2780 }
2781
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002782 case CXCursor_OverloadedDeclRef: {
2783 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2784 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2785 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2786 return createCXString(ND->getNameAsString());
2787 return createCXString("");
2788 }
2789 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2790 return createCXString(E->getName().getAsString());
2791 OverloadedTemplateStorage *Ovl
2792 = Storage.get<OverloadedTemplateStorage*>();
2793 if (Ovl->size() == 0)
2794 return createCXString("");
2795 return createCXString((*Ovl->begin())->getNameAsString());
2796 }
2797
Daniel Dunbaracca7252009-11-30 20:42:49 +00002798 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002799 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002800 }
2801 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002802
2803 if (clang_isExpression(C.kind)) {
2804 Decl *D = getDeclFromExpr(getCursorExpr(C));
2805 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002806 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002807 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002808 }
2809
Douglas Gregor36897b02010-09-10 00:22:18 +00002810 if (clang_isStatement(C.kind)) {
2811 Stmt *S = getCursorStmt(C);
2812 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2813 return createCXString(Label->getID()->getName());
2814
2815 return createCXString("");
2816 }
2817
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002818 if (C.kind == CXCursor_MacroInstantiation)
2819 return createCXString(getCursorMacroInstantiation(C)->getName()
2820 ->getNameStart());
2821
Douglas Gregor572feb22010-03-18 18:04:21 +00002822 if (C.kind == CXCursor_MacroDefinition)
2823 return createCXString(getCursorMacroDefinition(C)->getName()
2824 ->getNameStart());
2825
Douglas Gregorecdcb882010-10-20 22:00:55 +00002826 if (C.kind == CXCursor_InclusionDirective)
2827 return createCXString(getCursorInclusionDirective(C)->getFileName());
2828
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002829 if (clang_isDeclaration(C.kind))
2830 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002831
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002832 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002833}
2834
Douglas Gregor358559d2010-10-02 22:49:11 +00002835CXString clang_getCursorDisplayName(CXCursor C) {
2836 if (!clang_isDeclaration(C.kind))
2837 return clang_getCursorSpelling(C);
2838
2839 Decl *D = getCursorDecl(C);
2840 if (!D)
2841 return createCXString("");
2842
2843 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2844 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2845 D = FunTmpl->getTemplatedDecl();
2846
2847 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2848 llvm::SmallString<64> Str;
2849 llvm::raw_svector_ostream OS(Str);
2850 OS << Function->getNameAsString();
2851 if (Function->getPrimaryTemplate())
2852 OS << "<>";
2853 OS << "(";
2854 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2855 if (I)
2856 OS << ", ";
2857 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2858 }
2859
2860 if (Function->isVariadic()) {
2861 if (Function->getNumParams())
2862 OS << ", ";
2863 OS << "...";
2864 }
2865 OS << ")";
2866 return createCXString(OS.str());
2867 }
2868
2869 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2870 llvm::SmallString<64> Str;
2871 llvm::raw_svector_ostream OS(Str);
2872 OS << ClassTemplate->getNameAsString();
2873 OS << "<";
2874 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2875 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2876 if (I)
2877 OS << ", ";
2878
2879 NamedDecl *Param = Params->getParam(I);
2880 if (Param->getIdentifier()) {
2881 OS << Param->getIdentifier()->getName();
2882 continue;
2883 }
2884
2885 // There is no parameter name, which makes this tricky. Try to come up
2886 // with something useful that isn't too long.
2887 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2888 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2889 else if (NonTypeTemplateParmDecl *NTTP
2890 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2891 OS << NTTP->getType().getAsString(Policy);
2892 else
2893 OS << "template<...> class";
2894 }
2895
2896 OS << ">";
2897 return createCXString(OS.str());
2898 }
2899
2900 if (ClassTemplateSpecializationDecl *ClassSpec
2901 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2902 // If the type was explicitly written, use that.
2903 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2904 return createCXString(TSInfo->getType().getAsString(Policy));
2905
2906 llvm::SmallString<64> Str;
2907 llvm::raw_svector_ostream OS(Str);
2908 OS << ClassSpec->getNameAsString();
2909 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002910 ClassSpec->getTemplateArgs().data(),
2911 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002912 Policy);
2913 return createCXString(OS.str());
2914 }
2915
2916 return clang_getCursorSpelling(C);
2917}
2918
Ted Kremeneke68fff62010-02-17 00:41:32 +00002919CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002920 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002921 case CXCursor_FunctionDecl:
2922 return createCXString("FunctionDecl");
2923 case CXCursor_TypedefDecl:
2924 return createCXString("TypedefDecl");
2925 case CXCursor_EnumDecl:
2926 return createCXString("EnumDecl");
2927 case CXCursor_EnumConstantDecl:
2928 return createCXString("EnumConstantDecl");
2929 case CXCursor_StructDecl:
2930 return createCXString("StructDecl");
2931 case CXCursor_UnionDecl:
2932 return createCXString("UnionDecl");
2933 case CXCursor_ClassDecl:
2934 return createCXString("ClassDecl");
2935 case CXCursor_FieldDecl:
2936 return createCXString("FieldDecl");
2937 case CXCursor_VarDecl:
2938 return createCXString("VarDecl");
2939 case CXCursor_ParmDecl:
2940 return createCXString("ParmDecl");
2941 case CXCursor_ObjCInterfaceDecl:
2942 return createCXString("ObjCInterfaceDecl");
2943 case CXCursor_ObjCCategoryDecl:
2944 return createCXString("ObjCCategoryDecl");
2945 case CXCursor_ObjCProtocolDecl:
2946 return createCXString("ObjCProtocolDecl");
2947 case CXCursor_ObjCPropertyDecl:
2948 return createCXString("ObjCPropertyDecl");
2949 case CXCursor_ObjCIvarDecl:
2950 return createCXString("ObjCIvarDecl");
2951 case CXCursor_ObjCInstanceMethodDecl:
2952 return createCXString("ObjCInstanceMethodDecl");
2953 case CXCursor_ObjCClassMethodDecl:
2954 return createCXString("ObjCClassMethodDecl");
2955 case CXCursor_ObjCImplementationDecl:
2956 return createCXString("ObjCImplementationDecl");
2957 case CXCursor_ObjCCategoryImplDecl:
2958 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002959 case CXCursor_CXXMethod:
2960 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002961 case CXCursor_UnexposedDecl:
2962 return createCXString("UnexposedDecl");
2963 case CXCursor_ObjCSuperClassRef:
2964 return createCXString("ObjCSuperClassRef");
2965 case CXCursor_ObjCProtocolRef:
2966 return createCXString("ObjCProtocolRef");
2967 case CXCursor_ObjCClassRef:
2968 return createCXString("ObjCClassRef");
2969 case CXCursor_TypeRef:
2970 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002971 case CXCursor_TemplateRef:
2972 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002973 case CXCursor_NamespaceRef:
2974 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002975 case CXCursor_MemberRef:
2976 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002977 case CXCursor_LabelRef:
2978 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002979 case CXCursor_OverloadedDeclRef:
2980 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002981 case CXCursor_UnexposedExpr:
2982 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002983 case CXCursor_BlockExpr:
2984 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002985 case CXCursor_DeclRefExpr:
2986 return createCXString("DeclRefExpr");
2987 case CXCursor_MemberRefExpr:
2988 return createCXString("MemberRefExpr");
2989 case CXCursor_CallExpr:
2990 return createCXString("CallExpr");
2991 case CXCursor_ObjCMessageExpr:
2992 return createCXString("ObjCMessageExpr");
2993 case CXCursor_UnexposedStmt:
2994 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002995 case CXCursor_LabelStmt:
2996 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002997 case CXCursor_InvalidFile:
2998 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002999 case CXCursor_InvalidCode:
3000 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003001 case CXCursor_NoDeclFound:
3002 return createCXString("NoDeclFound");
3003 case CXCursor_NotImplemented:
3004 return createCXString("NotImplemented");
3005 case CXCursor_TranslationUnit:
3006 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003007 case CXCursor_UnexposedAttr:
3008 return createCXString("UnexposedAttr");
3009 case CXCursor_IBActionAttr:
3010 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003011 case CXCursor_IBOutletAttr:
3012 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003013 case CXCursor_IBOutletCollectionAttr:
3014 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003015 case CXCursor_PreprocessingDirective:
3016 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003017 case CXCursor_MacroDefinition:
3018 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003019 case CXCursor_MacroInstantiation:
3020 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003021 case CXCursor_InclusionDirective:
3022 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003023 case CXCursor_Namespace:
3024 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003025 case CXCursor_LinkageSpec:
3026 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003027 case CXCursor_CXXBaseSpecifier:
3028 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003029 case CXCursor_Constructor:
3030 return createCXString("CXXConstructor");
3031 case CXCursor_Destructor:
3032 return createCXString("CXXDestructor");
3033 case CXCursor_ConversionFunction:
3034 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003035 case CXCursor_TemplateTypeParameter:
3036 return createCXString("TemplateTypeParameter");
3037 case CXCursor_NonTypeTemplateParameter:
3038 return createCXString("NonTypeTemplateParameter");
3039 case CXCursor_TemplateTemplateParameter:
3040 return createCXString("TemplateTemplateParameter");
3041 case CXCursor_FunctionTemplate:
3042 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003043 case CXCursor_ClassTemplate:
3044 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003045 case CXCursor_ClassTemplatePartialSpecialization:
3046 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003047 case CXCursor_NamespaceAlias:
3048 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003049 case CXCursor_UsingDirective:
3050 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003051 case CXCursor_UsingDeclaration:
3052 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003053 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003054
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003055 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003056 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003057}
Steve Naroff89922f82009-08-31 00:59:03 +00003058
Ted Kremeneke68fff62010-02-17 00:41:32 +00003059enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3060 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003061 CXClientData client_data) {
3062 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003063
3064 // If our current best cursor is the construction of a temporary object,
3065 // don't replace that cursor with a type reference, because we want
3066 // clang_getCursor() to point at the constructor.
3067 if (clang_isExpression(BestCursor->kind) &&
3068 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3069 cursor.kind == CXCursor_TypeRef)
3070 return CXChildVisit_Recurse;
3071
Douglas Gregor85fe1562010-12-10 07:23:11 +00003072 // Don't override a preprocessing cursor with another preprocessing
3073 // cursor; we want the outermost preprocessing cursor.
3074 if (clang_isPreprocessing(cursor.kind) &&
3075 clang_isPreprocessing(BestCursor->kind))
3076 return CXChildVisit_Recurse;
3077
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003078 *BestCursor = cursor;
3079 return CXChildVisit_Recurse;
3080}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003081
Douglas Gregorb9790342010-01-22 21:44:22 +00003082CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3083 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003084 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003085
Ted Kremeneka60ed472010-11-16 08:15:36 +00003086 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003087 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3088
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003089 // Translate the given source location to make it point at the beginning of
3090 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003091 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003092
3093 // Guard against an invalid SourceLocation, or we may assert in one
3094 // of the following calls.
3095 if (SLoc.isInvalid())
3096 return clang_getNullCursor();
3097
Douglas Gregor40749ee2010-11-03 00:35:38 +00003098 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003099 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3100 CXXUnit->getASTContext().getLangOptions());
3101
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003102 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3103 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003104 // FIXME: Would be great to have a "hint" cursor, then walk from that
3105 // hint cursor upward until we find a cursor whose source range encloses
3106 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003107 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3108 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003109 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003110 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003111 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003112
3113 if (Logging) {
3114 CXFile SearchFile;
3115 unsigned SearchLine, SearchColumn;
3116 CXFile ResultFile;
3117 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003118 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3119 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003120 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3121
3122 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3123 0);
3124 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3125 &ResultColumn, 0);
3126 SearchFileName = clang_getFileName(SearchFile);
3127 ResultFileName = clang_getFileName(ResultFile);
3128 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003129 USR = clang_getCursorUSR(Result);
3130 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003131 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3132 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003133 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3134 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003135 clang_disposeString(SearchFileName);
3136 clang_disposeString(ResultFileName);
3137 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003138 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003139
3140 CXCursor Definition = clang_getCursorDefinition(Result);
3141 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3142 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3143 CXString DefinitionKindSpelling
3144 = clang_getCursorKindSpelling(Definition.kind);
3145 CXFile DefinitionFile;
3146 unsigned DefinitionLine, DefinitionColumn;
3147 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3148 &DefinitionLine, &DefinitionColumn, 0);
3149 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3150 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3151 clang_getCString(DefinitionKindSpelling),
3152 clang_getCString(DefinitionFileName),
3153 DefinitionLine, DefinitionColumn);
3154 clang_disposeString(DefinitionFileName);
3155 clang_disposeString(DefinitionKindSpelling);
3156 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003157 }
3158
Ted Kremeneke68fff62010-02-17 00:41:32 +00003159 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003160}
3161
Ted Kremenek73885552009-11-17 19:28:59 +00003162CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003163 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003164}
3165
3166unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003167 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003168}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003169
Douglas Gregor9ce55842010-11-20 00:09:34 +00003170unsigned clang_hashCursor(CXCursor C) {
3171 unsigned Index = 0;
3172 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3173 Index = 1;
3174
3175 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3176 std::make_pair(C.kind, C.data[Index]));
3177}
3178
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003179unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003180 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3181}
3182
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003183unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003184 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3185}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003186
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003187unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003188 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3189}
3190
Douglas Gregor97b98722010-01-19 23:20:36 +00003191unsigned clang_isExpression(enum CXCursorKind K) {
3192 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3193}
3194
3195unsigned clang_isStatement(enum CXCursorKind K) {
3196 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3197}
3198
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003199unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3200 return K == CXCursor_TranslationUnit;
3201}
3202
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003203unsigned clang_isPreprocessing(enum CXCursorKind K) {
3204 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3205}
3206
Ted Kremenekad6eff62010-03-08 21:17:29 +00003207unsigned clang_isUnexposed(enum CXCursorKind K) {
3208 switch (K) {
3209 case CXCursor_UnexposedDecl:
3210 case CXCursor_UnexposedExpr:
3211 case CXCursor_UnexposedStmt:
3212 case CXCursor_UnexposedAttr:
3213 return true;
3214 default:
3215 return false;
3216 }
3217}
3218
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003219CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003220 return C.kind;
3221}
3222
Douglas Gregor98258af2010-01-18 22:46:11 +00003223CXSourceLocation clang_getCursorLocation(CXCursor C) {
3224 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003225 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003226 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003227 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3228 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003229 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003230 }
3231
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003232 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003233 std::pair<ObjCProtocolDecl *, SourceLocation> P
3234 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003235 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003236 }
3237
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003238 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003239 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3240 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003241 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003242 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003243
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003244 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003245 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003246 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003247 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003248
3249 case CXCursor_TemplateRef: {
3250 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3251 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3252 }
3253
Douglas Gregor69319002010-08-31 23:48:11 +00003254 case CXCursor_NamespaceRef: {
3255 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3256 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3257 }
3258
Douglas Gregora67e03f2010-09-09 21:42:20 +00003259 case CXCursor_MemberRef: {
3260 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3261 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3262 }
3263
Ted Kremenek3064ef92010-08-27 21:34:58 +00003264 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003265 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3266 if (!BaseSpec)
3267 return clang_getNullLocation();
3268
3269 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3270 return cxloc::translateSourceLocation(getCursorContext(C),
3271 TSInfo->getTypeLoc().getBeginLoc());
3272
3273 return cxloc::translateSourceLocation(getCursorContext(C),
3274 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003275 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003276
Douglas Gregor36897b02010-09-10 00:22:18 +00003277 case CXCursor_LabelRef: {
3278 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3279 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3280 }
3281
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003282 case CXCursor_OverloadedDeclRef:
3283 return cxloc::translateSourceLocation(getCursorContext(C),
3284 getCursorOverloadedDeclRef(C).second);
3285
Douglas Gregorf46034a2010-01-18 23:41:10 +00003286 default:
3287 // FIXME: Need a way to enumerate all non-reference cases.
3288 llvm_unreachable("Missed a reference kind");
3289 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003290 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003291
3292 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003293 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003294 getLocationFromExpr(getCursorExpr(C)));
3295
Douglas Gregor36897b02010-09-10 00:22:18 +00003296 if (clang_isStatement(C.kind))
3297 return cxloc::translateSourceLocation(getCursorContext(C),
3298 getCursorStmt(C)->getLocStart());
3299
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003300 if (C.kind == CXCursor_PreprocessingDirective) {
3301 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3302 return cxloc::translateSourceLocation(getCursorContext(C), L);
3303 }
Douglas Gregor48072312010-03-18 15:23:44 +00003304
3305 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003306 SourceLocation L
3307 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003308 return cxloc::translateSourceLocation(getCursorContext(C), L);
3309 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003310
3311 if (C.kind == CXCursor_MacroDefinition) {
3312 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3313 return cxloc::translateSourceLocation(getCursorContext(C), L);
3314 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003315
3316 if (C.kind == CXCursor_InclusionDirective) {
3317 SourceLocation L
3318 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3319 return cxloc::translateSourceLocation(getCursorContext(C), L);
3320 }
3321
Ted Kremenek9a700d22010-05-12 06:16:13 +00003322 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003323 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003324
Douglas Gregorf46034a2010-01-18 23:41:10 +00003325 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003326 SourceLocation Loc = D->getLocation();
3327 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3328 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003329 // FIXME: Multiple variables declared in a single declaration
3330 // currently lack the information needed to correctly determine their
3331 // ranges when accounting for the type-specifier. We use context
3332 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3333 // and if so, whether it is the first decl.
3334 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3335 if (!cxcursor::isFirstInDeclGroup(C))
3336 Loc = VD->getLocation();
3337 }
3338
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003339 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003340}
Douglas Gregora7bde202010-01-19 00:34:46 +00003341
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003342} // end extern "C"
3343
3344static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003345 if (clang_isReference(C.kind)) {
3346 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003347 case CXCursor_ObjCSuperClassRef:
3348 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003349
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003350 case CXCursor_ObjCProtocolRef:
3351 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003352
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003353 case CXCursor_ObjCClassRef:
3354 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003355
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003356 case CXCursor_TypeRef:
3357 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003358
3359 case CXCursor_TemplateRef:
3360 return getCursorTemplateRef(C).second;
3361
Douglas Gregor69319002010-08-31 23:48:11 +00003362 case CXCursor_NamespaceRef:
3363 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003364
3365 case CXCursor_MemberRef:
3366 return getCursorMemberRef(C).second;
3367
Ted Kremenek3064ef92010-08-27 21:34:58 +00003368 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003369 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003370
Douglas Gregor36897b02010-09-10 00:22:18 +00003371 case CXCursor_LabelRef:
3372 return getCursorLabelRef(C).second;
3373
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003374 case CXCursor_OverloadedDeclRef:
3375 return getCursorOverloadedDeclRef(C).second;
3376
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003377 default:
3378 // FIXME: Need a way to enumerate all non-reference cases.
3379 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003380 }
3381 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003382
3383 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003384 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003385
3386 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003387 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003388
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003389 if (C.kind == CXCursor_PreprocessingDirective)
3390 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003391
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003392 if (C.kind == CXCursor_MacroInstantiation)
3393 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003394
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003395 if (C.kind == CXCursor_MacroDefinition)
3396 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003397
3398 if (C.kind == CXCursor_InclusionDirective)
3399 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3400
Ted Kremenek007a7c92010-11-01 23:26:51 +00003401 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3402 Decl *D = cxcursor::getCursorDecl(C);
3403 SourceRange R = D->getSourceRange();
3404 // FIXME: Multiple variables declared in a single declaration
3405 // currently lack the information needed to correctly determine their
3406 // ranges when accounting for the type-specifier. We use context
3407 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3408 // and if so, whether it is the first decl.
3409 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3410 if (!cxcursor::isFirstInDeclGroup(C))
3411 R.setBegin(VD->getLocation());
3412 }
3413 return R;
3414 }
Douglas Gregor66537982010-11-17 17:14:07 +00003415 return SourceRange();
3416}
3417
3418/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3419/// the decl-specifier-seq for declarations.
3420static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3421 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3422 Decl *D = cxcursor::getCursorDecl(C);
3423 SourceRange R = D->getSourceRange();
3424
3425 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3426 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3427 TypeLoc TL = TI->getTypeLoc();
3428 SourceLocation TLoc = TL.getSourceRange().getBegin();
3429 if (TLoc.isValid() && R.getBegin().isValid() &&
3430 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3431 R.setBegin(TLoc);
3432 }
3433
3434 // FIXME: Multiple variables declared in a single declaration
3435 // currently lack the information needed to correctly determine their
3436 // ranges when accounting for the type-specifier. We use context
3437 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3438 // and if so, whether it is the first decl.
3439 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3440 if (!cxcursor::isFirstInDeclGroup(C))
3441 R.setBegin(VD->getLocation());
3442 }
3443 }
3444
3445 return R;
3446 }
3447
3448 return getRawCursorExtent(C);
3449}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003450
3451extern "C" {
3452
3453CXSourceRange clang_getCursorExtent(CXCursor C) {
3454 SourceRange R = getRawCursorExtent(C);
3455 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003456 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003457
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003458 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003459}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003460
3461CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003462 if (clang_isInvalid(C.kind))
3463 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003464
Ted Kremeneka60ed472010-11-16 08:15:36 +00003465 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003466 if (clang_isDeclaration(C.kind)) {
3467 Decl *D = getCursorDecl(C);
3468 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003469 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003470 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003471 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003472 if (ObjCForwardProtocolDecl *Protocols
3473 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003474 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003475 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3476 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3477 return MakeCXCursor(Property, tu);
3478
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003479 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003480 }
3481
Douglas Gregor97b98722010-01-19 23:20:36 +00003482 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003483 Expr *E = getCursorExpr(C);
3484 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003485 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003486 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003487
3488 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003489 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003490
Douglas Gregor97b98722010-01-19 23:20:36 +00003491 return clang_getNullCursor();
3492 }
3493
Douglas Gregor36897b02010-09-10 00:22:18 +00003494 if (clang_isStatement(C.kind)) {
3495 Stmt *S = getCursorStmt(C);
3496 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003497 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003498
3499 return clang_getNullCursor();
3500 }
3501
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003502 if (C.kind == CXCursor_MacroInstantiation) {
3503 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003504 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003505 }
3506
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003507 if (!clang_isReference(C.kind))
3508 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003509
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003510 switch (C.kind) {
3511 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003512 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003513
3514 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003515 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003516
3517 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003518 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003519
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003520 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003521 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003522
3523 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003524 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003525
Douglas Gregor69319002010-08-31 23:48:11 +00003526 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003527 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003528
Douglas Gregora67e03f2010-09-09 21:42:20 +00003529 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003530 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003531
Ted Kremenek3064ef92010-08-27 21:34:58 +00003532 case CXCursor_CXXBaseSpecifier: {
3533 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3534 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003535 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003536 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003537
Douglas Gregor36897b02010-09-10 00:22:18 +00003538 case CXCursor_LabelRef:
3539 // FIXME: We end up faking the "parent" declaration here because we
3540 // don't want to make CXCursor larger.
3541 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003542 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3543 .getTranslationUnitDecl(),
3544 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003545
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003546 case CXCursor_OverloadedDeclRef:
3547 return C;
3548
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003549 default:
3550 // We would prefer to enumerate all non-reference cursor kinds here.
3551 llvm_unreachable("Unhandled reference cursor kind");
3552 break;
3553 }
3554 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003555
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003556 return clang_getNullCursor();
3557}
3558
Douglas Gregorb6998662010-01-19 19:34:47 +00003559CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003560 if (clang_isInvalid(C.kind))
3561 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003562
Ted Kremeneka60ed472010-11-16 08:15:36 +00003563 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003564
Douglas Gregorb6998662010-01-19 19:34:47 +00003565 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003566 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003567 C = clang_getCursorReferenced(C);
3568 WasReference = true;
3569 }
3570
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003571 if (C.kind == CXCursor_MacroInstantiation)
3572 return clang_getCursorReferenced(C);
3573
Douglas Gregorb6998662010-01-19 19:34:47 +00003574 if (!clang_isDeclaration(C.kind))
3575 return clang_getNullCursor();
3576
3577 Decl *D = getCursorDecl(C);
3578 if (!D)
3579 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003580
Douglas Gregorb6998662010-01-19 19:34:47 +00003581 switch (D->getKind()) {
3582 // Declaration kinds that don't really separate the notions of
3583 // declaration and definition.
3584 case Decl::Namespace:
3585 case Decl::Typedef:
3586 case Decl::TemplateTypeParm:
3587 case Decl::EnumConstant:
3588 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003589 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003590 case Decl::ObjCIvar:
3591 case Decl::ObjCAtDefsField:
3592 case Decl::ImplicitParam:
3593 case Decl::ParmVar:
3594 case Decl::NonTypeTemplateParm:
3595 case Decl::TemplateTemplateParm:
3596 case Decl::ObjCCategoryImpl:
3597 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003598 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003599 case Decl::LinkageSpec:
3600 case Decl::ObjCPropertyImpl:
3601 case Decl::FileScopeAsm:
3602 case Decl::StaticAssert:
3603 case Decl::Block:
3604 return C;
3605
3606 // Declaration kinds that don't make any sense here, but are
3607 // nonetheless harmless.
3608 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003609 break;
3610
3611 // Declaration kinds for which the definition is not resolvable.
3612 case Decl::UnresolvedUsingTypename:
3613 case Decl::UnresolvedUsingValue:
3614 break;
3615
3616 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003617 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003618 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003619
3620 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003621 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003622
3623 case Decl::Enum:
3624 case Decl::Record:
3625 case Decl::CXXRecord:
3626 case Decl::ClassTemplateSpecialization:
3627 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003628 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003629 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003630 return clang_getNullCursor();
3631
3632 case Decl::Function:
3633 case Decl::CXXMethod:
3634 case Decl::CXXConstructor:
3635 case Decl::CXXDestructor:
3636 case Decl::CXXConversion: {
3637 const FunctionDecl *Def = 0;
3638 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003639 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003640 return clang_getNullCursor();
3641 }
3642
3643 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003644 // Ask the variable if it has a definition.
3645 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003646 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003647 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003648 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003649
Douglas Gregorb6998662010-01-19 19:34:47 +00003650 case Decl::FunctionTemplate: {
3651 const FunctionDecl *Def = 0;
3652 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003653 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003654 return clang_getNullCursor();
3655 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003656
Douglas Gregorb6998662010-01-19 19:34:47 +00003657 case Decl::ClassTemplate: {
3658 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003659 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003660 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003661 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003662 return clang_getNullCursor();
3663 }
3664
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003665 case Decl::Using:
3666 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003667 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003668
3669 case Decl::UsingShadow:
3670 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003671 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003672 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003673
3674 case Decl::ObjCMethod: {
3675 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3676 if (Method->isThisDeclarationADefinition())
3677 return C;
3678
3679 // Dig out the method definition in the associated
3680 // @implementation, if we have it.
3681 // FIXME: The ASTs should make finding the definition easier.
3682 if (ObjCInterfaceDecl *Class
3683 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3684 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3685 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3686 Method->isInstanceMethod()))
3687 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003688 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003689
3690 return clang_getNullCursor();
3691 }
3692
3693 case Decl::ObjCCategory:
3694 if (ObjCCategoryImplDecl *Impl
3695 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003696 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003697 return clang_getNullCursor();
3698
3699 case Decl::ObjCProtocol:
3700 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3701 return C;
3702 return clang_getNullCursor();
3703
3704 case Decl::ObjCInterface:
3705 // There are two notions of a "definition" for an Objective-C
3706 // class: the interface and its implementation. When we resolved a
3707 // reference to an Objective-C class, produce the @interface as
3708 // the definition; when we were provided with the interface,
3709 // produce the @implementation as the definition.
3710 if (WasReference) {
3711 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3712 return C;
3713 } else if (ObjCImplementationDecl *Impl
3714 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003715 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003716 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003717
Douglas Gregorb6998662010-01-19 19:34:47 +00003718 case Decl::ObjCProperty:
3719 // FIXME: We don't really know where to find the
3720 // ObjCPropertyImplDecls that implement this property.
3721 return clang_getNullCursor();
3722
3723 case Decl::ObjCCompatibleAlias:
3724 if (ObjCInterfaceDecl *Class
3725 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3726 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003727 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003728
Douglas Gregorb6998662010-01-19 19:34:47 +00003729 return clang_getNullCursor();
3730
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003731 case Decl::ObjCForwardProtocol:
3732 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003733 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003734
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003735 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003736 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003737 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003738
3739 case Decl::Friend:
3740 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003741 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003742 return clang_getNullCursor();
3743
3744 case Decl::FriendTemplate:
3745 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003746 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003747 return clang_getNullCursor();
3748 }
3749
3750 return clang_getNullCursor();
3751}
3752
3753unsigned clang_isCursorDefinition(CXCursor C) {
3754 if (!clang_isDeclaration(C.kind))
3755 return 0;
3756
3757 return clang_getCursorDefinition(C) == C;
3758}
3759
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003760CXCursor clang_getCanonicalCursor(CXCursor C) {
3761 if (!clang_isDeclaration(C.kind))
3762 return C;
3763
3764 if (Decl *D = getCursorDecl(C))
3765 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3766
3767 return C;
3768}
3769
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003770unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003771 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003772 return 0;
3773
3774 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3775 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3776 return E->getNumDecls();
3777
3778 if (OverloadedTemplateStorage *S
3779 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3780 return S->size();
3781
3782 Decl *D = Storage.get<Decl*>();
3783 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003784 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003785 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3786 return Classes->size();
3787 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3788 return Protocols->protocol_size();
3789
3790 return 0;
3791}
3792
3793CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003794 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003795 return clang_getNullCursor();
3796
3797 if (index >= clang_getNumOverloadedDecls(cursor))
3798 return clang_getNullCursor();
3799
Ted Kremeneka60ed472010-11-16 08:15:36 +00003800 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003801 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3802 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003803 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003804
3805 if (OverloadedTemplateStorage *S
3806 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003807 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003808
3809 Decl *D = Storage.get<Decl*>();
3810 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3811 // FIXME: This is, unfortunately, linear time.
3812 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3813 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003814 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003815 }
3816
3817 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003818 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003819
3820 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003821 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003822
3823 return clang_getNullCursor();
3824}
3825
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003826void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003827 const char **startBuf,
3828 const char **endBuf,
3829 unsigned *startLine,
3830 unsigned *startColumn,
3831 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003832 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003833 assert(getCursorDecl(C) && "CXCursor has null decl");
3834 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003835 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3836 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003837
Steve Naroff4ade6d62009-09-23 17:52:52 +00003838 SourceManager &SM = FD->getASTContext().getSourceManager();
3839 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3840 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3841 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3842 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3843 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3844 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3845}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003847void clang_enableStackTraces(void) {
3848 llvm::sys::PrintStackTraceOnErrorSignal();
3849}
3850
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003851void clang_executeOnThread(void (*fn)(void*), void *user_data,
3852 unsigned stack_size) {
3853 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3854}
3855
Ted Kremenekfb480492010-01-13 21:46:36 +00003856} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003857
Ted Kremenekfb480492010-01-13 21:46:36 +00003858//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859// Token-based Operations.
3860//===----------------------------------------------------------------------===//
3861
3862/* CXToken layout:
3863 * int_data[0]: a CXTokenKind
3864 * int_data[1]: starting token location
3865 * int_data[2]: token length
3866 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003867 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003868 * otherwise unused.
3869 */
3870extern "C" {
3871
3872CXTokenKind clang_getTokenKind(CXToken CXTok) {
3873 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3874}
3875
3876CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3877 switch (clang_getTokenKind(CXTok)) {
3878 case CXToken_Identifier:
3879 case CXToken_Keyword:
3880 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003881 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3882 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003883
3884 case CXToken_Literal: {
3885 // We have stashed the starting pointer in the ptr_data field. Use it.
3886 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003887 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003888 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003889
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 case CXToken_Punctuation:
3891 case CXToken_Comment:
3892 break;
3893 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
3895 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003896 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003897 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003898 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003899 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003900
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003901 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3902 std::pair<FileID, unsigned> LocInfo
3903 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003904 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003905 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003906 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3907 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003908 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003909
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003910 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003911}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003912
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003913CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003914 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003915 if (!CXXUnit)
3916 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003917
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003918 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3919 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3920}
3921
3922CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003923 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003924 if (!CXXUnit)
3925 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003926
3927 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003928 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3929}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003930
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003931void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3932 CXToken **Tokens, unsigned *NumTokens) {
3933 if (Tokens)
3934 *Tokens = 0;
3935 if (NumTokens)
3936 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003937
Ted Kremeneka60ed472010-11-16 08:15:36 +00003938 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003939 if (!CXXUnit || !Tokens || !NumTokens)
3940 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003941
Douglas Gregorbdf60622010-03-05 21:16:25 +00003942 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3943
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003944 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003945 if (R.isInvalid())
3946 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003947
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003948 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3949 std::pair<FileID, unsigned> BeginLocInfo
3950 = SourceMgr.getDecomposedLoc(R.getBegin());
3951 std::pair<FileID, unsigned> EndLocInfo
3952 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003953
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003954 // Cannot tokenize across files.
3955 if (BeginLocInfo.first != EndLocInfo.first)
3956 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003957
3958 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003959 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003960 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003961 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003962 if (Invalid)
3963 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003964
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003965 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3966 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003967 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003968 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003969
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003970 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003971 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003972 llvm::SmallVector<CXToken, 32> CXTokens;
3973 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003974 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003975 do {
3976 // Lex the next token
3977 Lex.LexFromRawLexer(Tok);
3978 if (Tok.is(tok::eof))
3979 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003980
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003981 // Initialize the CXToken.
3982 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003983
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003984 // - Common fields
3985 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3986 CXTok.int_data[2] = Tok.getLength();
3987 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003988
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003989 // - Kind-specific fields
3990 if (Tok.isLiteral()) {
3991 CXTok.int_data[0] = CXToken_Literal;
3992 CXTok.ptr_data = (void *)Tok.getLiteralData();
3993 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003994 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003995 std::pair<FileID, unsigned> LocInfo
3996 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003997 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003998 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003999 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4000 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004001 return;
4002
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004003 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004004 IdentifierInfo *II
4005 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004006
David Chisnall096428b2010-10-13 21:44:48 +00004007 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004008 CXTok.int_data[0] = CXToken_Keyword;
4009 }
4010 else {
4011 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
4012 CXToken_Identifier
4013 : CXToken_Keyword;
4014 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004015 CXTok.ptr_data = II;
4016 } else if (Tok.is(tok::comment)) {
4017 CXTok.int_data[0] = CXToken_Comment;
4018 CXTok.ptr_data = 0;
4019 } else {
4020 CXTok.int_data[0] = CXToken_Punctuation;
4021 CXTok.ptr_data = 0;
4022 }
4023 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004024 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004025 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004026
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004027 if (CXTokens.empty())
4028 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004029
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004030 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4031 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4032 *NumTokens = CXTokens.size();
4033}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004034
Ted Kremenek6db61092010-05-05 00:55:15 +00004035void clang_disposeTokens(CXTranslationUnit TU,
4036 CXToken *Tokens, unsigned NumTokens) {
4037 free(Tokens);
4038}
4039
4040} // end: extern "C"
4041
4042//===----------------------------------------------------------------------===//
4043// Token annotation APIs.
4044//===----------------------------------------------------------------------===//
4045
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004046typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004047static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4048 CXCursor parent,
4049 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004050namespace {
4051class AnnotateTokensWorker {
4052 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004053 CXToken *Tokens;
4054 CXCursor *Cursors;
4055 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004056 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004057 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004058 CursorVisitor AnnotateVis;
4059 SourceManager &SrcMgr;
4060
4061 bool MoreTokens() const { return TokIdx < NumTokens; }
4062 unsigned NextToken() const { return TokIdx; }
4063 void AdvanceToken() { ++TokIdx; }
4064 SourceLocation GetTokenLoc(unsigned tokI) {
4065 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4066 }
4067
Ted Kremenek6db61092010-05-05 00:55:15 +00004068public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004069 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004070 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004071 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004072 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004073 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004074 AnnotateVis(tu,
4075 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004076 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004077 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004078
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004079 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004080 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004081 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004082 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004083 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004084 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004085};
4086}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004087
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004088void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4089 // Walk the AST within the region of interest, annotating tokens
4090 // along the way.
4091 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004092
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004093 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4094 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004095 if (Pos != Annotated.end() &&
4096 (clang_isInvalid(Cursors[I].kind) ||
4097 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004098 Cursors[I] = Pos->second;
4099 }
4100
4101 // Finish up annotating any tokens left.
4102 if (!MoreTokens())
4103 return;
4104
4105 const CXCursor &C = clang_getNullCursor();
4106 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4107 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4108 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004109 }
4110}
4111
Ted Kremenek6db61092010-05-05 00:55:15 +00004112enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004113AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004114 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004115 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004116 if (cursorRange.isInvalid())
4117 return CXChildVisit_Recurse;
4118
Douglas Gregor4419b672010-10-21 06:10:04 +00004119 if (clang_isPreprocessing(cursor.kind)) {
4120 // For macro instantiations, just note where the beginning of the macro
4121 // instantiation occurs.
4122 if (cursor.kind == CXCursor_MacroInstantiation) {
4123 Annotated[Loc.int_data] = cursor;
4124 return CXChildVisit_Recurse;
4125 }
4126
Douglas Gregor4419b672010-10-21 06:10:04 +00004127 // Items in the preprocessing record are kept separate from items in
4128 // declarations, so we keep a separate token index.
4129 unsigned SavedTokIdx = TokIdx;
4130 TokIdx = PreprocessingTokIdx;
4131
4132 // Skip tokens up until we catch up to the beginning of the preprocessing
4133 // entry.
4134 while (MoreTokens()) {
4135 const unsigned I = NextToken();
4136 SourceLocation TokLoc = GetTokenLoc(I);
4137 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4138 case RangeBefore:
4139 AdvanceToken();
4140 continue;
4141 case RangeAfter:
4142 case RangeOverlap:
4143 break;
4144 }
4145 break;
4146 }
4147
4148 // Look at all of the tokens within this range.
4149 while (MoreTokens()) {
4150 const unsigned I = NextToken();
4151 SourceLocation TokLoc = GetTokenLoc(I);
4152 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4153 case RangeBefore:
4154 assert(0 && "Infeasible");
4155 case RangeAfter:
4156 break;
4157 case RangeOverlap:
4158 Cursors[I] = cursor;
4159 AdvanceToken();
4160 continue;
4161 }
4162 break;
4163 }
4164
4165 // Save the preprocessing token index; restore the non-preprocessing
4166 // token index.
4167 PreprocessingTokIdx = TokIdx;
4168 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004169 return CXChildVisit_Recurse;
4170 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004171
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004172 if (cursorRange.isInvalid())
4173 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004174
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004175 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4176
Ted Kremeneka333c662010-05-12 05:29:33 +00004177 // Adjust the annotated range based specific declarations.
4178 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4179 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004180 Decl *D = cxcursor::getCursorDecl(cursor);
4181 // Don't visit synthesized ObjC methods, since they have no syntatic
4182 // representation in the source.
4183 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4184 if (MD->isSynthesized())
4185 return CXChildVisit_Continue;
4186 }
4187 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004188 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4189 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004190 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004191 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004192 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004193 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004194 }
4195 }
4196 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004197
Ted Kremenek3f404602010-08-14 01:14:06 +00004198 // If the location of the cursor occurs within a macro instantiation, record
4199 // the spelling location of the cursor in our annotation map. We can then
4200 // paper over the token labelings during a post-processing step to try and
4201 // get cursor mappings for tokens that are the *arguments* of a macro
4202 // instantiation.
4203 if (L.isMacroID()) {
4204 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4205 // Only invalidate the old annotation if it isn't part of a preprocessing
4206 // directive. Here we assume that the default construction of CXCursor
4207 // results in CXCursor.kind being an initialized value (i.e., 0). If
4208 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004209
Ted Kremenek3f404602010-08-14 01:14:06 +00004210 CXCursor &oldC = Annotated[rawEncoding];
4211 if (!clang_isPreprocessing(oldC.kind))
4212 oldC = cursor;
4213 }
4214
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004215 const enum CXCursorKind K = clang_getCursorKind(parent);
4216 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004217 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4218 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004219
4220 while (MoreTokens()) {
4221 const unsigned I = NextToken();
4222 SourceLocation TokLoc = GetTokenLoc(I);
4223 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4224 case RangeBefore:
4225 Cursors[I] = updateC;
4226 AdvanceToken();
4227 continue;
4228 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229 case RangeOverlap:
4230 break;
4231 }
4232 break;
4233 }
4234
4235 // Visit children to get their cursor information.
4236 const unsigned BeforeChildren = NextToken();
4237 VisitChildren(cursor);
4238 const unsigned AfterChildren = NextToken();
4239
4240 // Adjust 'Last' to the last token within the extent of the cursor.
4241 while (MoreTokens()) {
4242 const unsigned I = NextToken();
4243 SourceLocation TokLoc = GetTokenLoc(I);
4244 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4245 case RangeBefore:
4246 assert(0 && "Infeasible");
4247 case RangeAfter:
4248 break;
4249 case RangeOverlap:
4250 Cursors[I] = updateC;
4251 AdvanceToken();
4252 continue;
4253 }
4254 break;
4255 }
4256 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004257
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004258 // Scan the tokens that are at the beginning of the cursor, but are not
4259 // capture by the child cursors.
4260
4261 // For AST elements within macros, rely on a post-annotate pass to
4262 // to correctly annotate the tokens with cursors. Otherwise we can
4263 // get confusing results of having tokens that map to cursors that really
4264 // are expanded by an instantiation.
4265 if (L.isMacroID())
4266 cursor = clang_getNullCursor();
4267
4268 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4269 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4270 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004271
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004272 Cursors[I] = cursor;
4273 }
4274 // Scan the tokens that are at the end of the cursor, but are not captured
4275 // but the child cursors.
4276 for (unsigned I = AfterChildren; I != Last; ++I)
4277 Cursors[I] = cursor;
4278
4279 TokIdx = Last;
4280 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004281}
4282
Ted Kremenek6db61092010-05-05 00:55:15 +00004283static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4284 CXCursor parent,
4285 CXClientData client_data) {
4286 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4287}
4288
Ted Kremenekab979612010-11-11 08:05:23 +00004289// This gets run a separate thread to avoid stack blowout.
4290static void runAnnotateTokensWorker(void *UserData) {
4291 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4292}
4293
Ted Kremenek6db61092010-05-05 00:55:15 +00004294extern "C" {
4295
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004296void clang_annotateTokens(CXTranslationUnit TU,
4297 CXToken *Tokens, unsigned NumTokens,
4298 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004299
4300 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004301 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004302
Douglas Gregor4419b672010-10-21 06:10:04 +00004303 // Any token we don't specifically annotate will have a NULL cursor.
4304 CXCursor C = clang_getNullCursor();
4305 for (unsigned I = 0; I != NumTokens; ++I)
4306 Cursors[I] = C;
4307
Ted Kremeneka60ed472010-11-16 08:15:36 +00004308 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004309 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004310 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004311
Douglas Gregorbdf60622010-03-05 21:16:25 +00004312 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004313
Douglas Gregor0396f462010-03-19 05:22:59 +00004314 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004315 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004316 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4317 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004318 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4319 clang_getTokenLocation(TU,
4320 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004321
Douglas Gregor0396f462010-03-19 05:22:59 +00004322 // A mapping from the source locations found when re-lexing or traversing the
4323 // region of interest to the corresponding cursors.
4324 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004325
4326 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004327 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004328 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4329 std::pair<FileID, unsigned> BeginLocInfo
4330 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4331 std::pair<FileID, unsigned> EndLocInfo
4332 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004333
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004334 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004335 bool Invalid = false;
4336 if (BeginLocInfo.first == EndLocInfo.first &&
4337 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4338 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004339 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4340 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004341 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004342 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004343 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004344
4345 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004346 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004347 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004348 Token Tok;
4349 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004350
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004351 reprocess:
4352 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4353 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004354 // don't see it while preprocessing these tokens later, but keep track
4355 // of all of the token locations inside this preprocessing directive so
4356 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004357 //
4358 // FIXME: Some simple tests here could identify macro definitions and
4359 // #undefs, to provide specific cursor kinds for those.
4360 std::vector<SourceLocation> Locations;
4361 do {
4362 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004363 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004364 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004365
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004366 using namespace cxcursor;
4367 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004368 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4369 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004370 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004371 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4372 Annotated[Locations[I].getRawEncoding()] = Cursor;
4373 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004374
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004375 if (Tok.isAtStartOfLine())
4376 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004377
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004378 continue;
4379 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004380
Douglas Gregor48072312010-03-18 15:23:44 +00004381 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004382 break;
4383 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004384 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004385
Douglas Gregor0396f462010-03-19 05:22:59 +00004386 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004387 // a specific cursor.
4388 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004389 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004390
4391 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004392 // FIXME: We use a ridiculous stack size here because the data-recursion
4393 // algorithm uses a large stack frame than the non-data recursive version,
4394 // and AnnotationTokensWorker currently transforms the data-recursion
4395 // algorithm back into a traditional recursion by explicitly calling
4396 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004397 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004398 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4399 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004400 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4401 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004402}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004403} // end: extern "C"
4404
4405//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004406// Operations for querying linkage of a cursor.
4407//===----------------------------------------------------------------------===//
4408
4409extern "C" {
4410CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004411 if (!clang_isDeclaration(cursor.kind))
4412 return CXLinkage_Invalid;
4413
Ted Kremenek16b42592010-03-03 06:36:57 +00004414 Decl *D = cxcursor::getCursorDecl(cursor);
4415 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4416 switch (ND->getLinkage()) {
4417 case NoLinkage: return CXLinkage_NoLinkage;
4418 case InternalLinkage: return CXLinkage_Internal;
4419 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4420 case ExternalLinkage: return CXLinkage_External;
4421 };
4422
4423 return CXLinkage_Invalid;
4424}
4425} // end: extern "C"
4426
4427//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004428// Operations for querying language of a cursor.
4429//===----------------------------------------------------------------------===//
4430
4431static CXLanguageKind getDeclLanguage(const Decl *D) {
4432 switch (D->getKind()) {
4433 default:
4434 break;
4435 case Decl::ImplicitParam:
4436 case Decl::ObjCAtDefsField:
4437 case Decl::ObjCCategory:
4438 case Decl::ObjCCategoryImpl:
4439 case Decl::ObjCClass:
4440 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004441 case Decl::ObjCForwardProtocol:
4442 case Decl::ObjCImplementation:
4443 case Decl::ObjCInterface:
4444 case Decl::ObjCIvar:
4445 case Decl::ObjCMethod:
4446 case Decl::ObjCProperty:
4447 case Decl::ObjCPropertyImpl:
4448 case Decl::ObjCProtocol:
4449 return CXLanguage_ObjC;
4450 case Decl::CXXConstructor:
4451 case Decl::CXXConversion:
4452 case Decl::CXXDestructor:
4453 case Decl::CXXMethod:
4454 case Decl::CXXRecord:
4455 case Decl::ClassTemplate:
4456 case Decl::ClassTemplatePartialSpecialization:
4457 case Decl::ClassTemplateSpecialization:
4458 case Decl::Friend:
4459 case Decl::FriendTemplate:
4460 case Decl::FunctionTemplate:
4461 case Decl::LinkageSpec:
4462 case Decl::Namespace:
4463 case Decl::NamespaceAlias:
4464 case Decl::NonTypeTemplateParm:
4465 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004466 case Decl::TemplateTemplateParm:
4467 case Decl::TemplateTypeParm:
4468 case Decl::UnresolvedUsingTypename:
4469 case Decl::UnresolvedUsingValue:
4470 case Decl::Using:
4471 case Decl::UsingDirective:
4472 case Decl::UsingShadow:
4473 return CXLanguage_CPlusPlus;
4474 }
4475
4476 return CXLanguage_C;
4477}
4478
4479extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004480
4481enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4482 if (clang_isDeclaration(cursor.kind))
4483 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4484 if (D->hasAttr<UnavailableAttr>() ||
4485 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4486 return CXAvailability_Available;
4487
4488 if (D->hasAttr<DeprecatedAttr>())
4489 return CXAvailability_Deprecated;
4490 }
4491
4492 return CXAvailability_Available;
4493}
4494
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004495CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4496 if (clang_isDeclaration(cursor.kind))
4497 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4498
4499 return CXLanguage_Invalid;
4500}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004501
4502CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4503 if (clang_isDeclaration(cursor.kind)) {
4504 if (Decl *D = getCursorDecl(cursor)) {
4505 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004506 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004507 }
4508 }
4509
4510 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4511 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004512 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004513 }
4514
4515 return clang_getNullCursor();
4516}
4517
4518CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4519 if (clang_isDeclaration(cursor.kind)) {
4520 if (Decl *D = getCursorDecl(cursor)) {
4521 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004522 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004523 }
4524 }
4525
4526 // FIXME: Note that we can't easily compute the lexical context of a
4527 // statement or expression, so we return nothing.
4528 return clang_getNullCursor();
4529}
4530
Douglas Gregor9f592342010-10-01 20:25:15 +00004531static void CollectOverriddenMethods(DeclContext *Ctx,
4532 ObjCMethodDecl *Method,
4533 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4534 if (!Ctx)
4535 return;
4536
4537 // If we have a class or category implementation, jump straight to the
4538 // interface.
4539 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4540 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4541
4542 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4543 if (!Container)
4544 return;
4545
4546 // Check whether we have a matching method at this level.
4547 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4548 Method->isInstanceMethod()))
4549 if (Method != Overridden) {
4550 // We found an override at this level; there is no need to look
4551 // into other protocols or categories.
4552 Methods.push_back(Overridden);
4553 return;
4554 }
4555
4556 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4557 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4558 PEnd = Protocol->protocol_end();
4559 P != PEnd; ++P)
4560 CollectOverriddenMethods(*P, Method, Methods);
4561 }
4562
4563 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4564 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4565 PEnd = Category->protocol_end();
4566 P != PEnd; ++P)
4567 CollectOverriddenMethods(*P, Method, Methods);
4568 }
4569
4570 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4571 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4572 PEnd = Interface->protocol_end();
4573 P != PEnd; ++P)
4574 CollectOverriddenMethods(*P, Method, Methods);
4575
4576 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4577 Category; Category = Category->getNextClassCategory())
4578 CollectOverriddenMethods(Category, Method, Methods);
4579
4580 // We only look into the superclass if we haven't found anything yet.
4581 if (Methods.empty())
4582 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4583 return CollectOverriddenMethods(Super, Method, Methods);
4584 }
4585}
4586
4587void clang_getOverriddenCursors(CXCursor cursor,
4588 CXCursor **overridden,
4589 unsigned *num_overridden) {
4590 if (overridden)
4591 *overridden = 0;
4592 if (num_overridden)
4593 *num_overridden = 0;
4594 if (!overridden || !num_overridden)
4595 return;
4596
4597 if (!clang_isDeclaration(cursor.kind))
4598 return;
4599
4600 Decl *D = getCursorDecl(cursor);
4601 if (!D)
4602 return;
4603
4604 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004605 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004606 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4607 *num_overridden = CXXMethod->size_overridden_methods();
4608 if (!*num_overridden)
4609 return;
4610
4611 *overridden = new CXCursor [*num_overridden];
4612 unsigned I = 0;
4613 for (CXXMethodDecl::method_iterator
4614 M = CXXMethod->begin_overridden_methods(),
4615 MEnd = CXXMethod->end_overridden_methods();
4616 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004617 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004618 return;
4619 }
4620
4621 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4622 if (!Method)
4623 return;
4624
4625 // Handle Objective-C methods.
4626 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4627 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4628
4629 if (Methods.empty())
4630 return;
4631
4632 *num_overridden = Methods.size();
4633 *overridden = new CXCursor [Methods.size()];
4634 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004635 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004636}
4637
4638void clang_disposeOverriddenCursors(CXCursor *overridden) {
4639 delete [] overridden;
4640}
4641
Douglas Gregorecdcb882010-10-20 22:00:55 +00004642CXFile clang_getIncludedFile(CXCursor cursor) {
4643 if (cursor.kind != CXCursor_InclusionDirective)
4644 return 0;
4645
4646 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4647 return (void *)ID->getFile();
4648}
4649
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004650} // end: extern "C"
4651
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004652
4653//===----------------------------------------------------------------------===//
4654// C++ AST instrospection.
4655//===----------------------------------------------------------------------===//
4656
4657extern "C" {
4658unsigned clang_CXXMethod_isStatic(CXCursor C) {
4659 if (!clang_isDeclaration(C.kind))
4660 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004661
4662 CXXMethodDecl *Method = 0;
4663 Decl *D = cxcursor::getCursorDecl(C);
4664 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4665 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4666 else
4667 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4668 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004669}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004670
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004671} // end: extern "C"
4672
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004673//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004674// Attribute introspection.
4675//===----------------------------------------------------------------------===//
4676
4677extern "C" {
4678CXType clang_getIBOutletCollectionType(CXCursor C) {
4679 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004680 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004681
4682 IBOutletCollectionAttr *A =
4683 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4684
Ted Kremeneka60ed472010-11-16 08:15:36 +00004685 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004686}
4687} // end: extern "C"
4688
4689//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004690// Misc. utility functions.
4691//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004692
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004693/// Default to using an 8 MB stack size on "safety" threads.
4694static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004695
4696namespace clang {
4697
4698bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004699 void (*Fn)(void*), void *UserData,
4700 unsigned Size) {
4701 if (!Size)
4702 Size = GetSafetyThreadStackSize();
4703 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004704 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4705 return CRC.RunSafely(Fn, UserData);
4706}
4707
4708unsigned GetSafetyThreadStackSize() {
4709 return SafetyStackThreadSize;
4710}
4711
4712void SetSafetyThreadStackSize(unsigned Value) {
4713 SafetyStackThreadSize = Value;
4714}
4715
4716}
4717
Ted Kremenek04bb7162010-01-22 22:44:15 +00004718extern "C" {
4719
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004720CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004721 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004722}
4723
4724} // end: extern "C"