blob: ca6efe8d885f8417c5a07f44b85760af433dc753 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
37#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000038#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000039#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000040#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000042#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000043#include "llvm/Support/Mutex.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000047#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000048
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Ted Kremeneka60ed472010-11-16 08:15:36 +000053static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
54 if (!TU)
55 return 0;
56 CXTranslationUnit D = new CXTranslationUnitImpl();
57 D->TUData = TU;
58 D->StringPool = createCXStringPool();
59 return D;
60}
61
Douglas Gregor33e9abd2010-01-22 19:49:59 +000062/// \brief The result of comparing two source ranges.
63enum RangeComparisonResult {
64 /// \brief Either the ranges overlap or one of the ranges is invalid.
65 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000066
Douglas Gregor33e9abd2010-01-22 19:49:59 +000067 /// \brief The first range ends before the second range starts.
68 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000069
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070 /// \brief The first range starts after the second range ends.
71 RangeAfter
72};
73
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076static RangeComparisonResult RangeCompare(SourceManager &SM,
77 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 SourceRange R2) {
79 assert(R1.isValid() && "First range is invalid?");
80 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000081 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000082 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000085 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 return RangeAfter;
87 return RangeOverlap;
88}
89
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000090/// \brief Determine if a source location falls within, before, or after a
91/// a given source range.
92static RangeComparisonResult LocationCompare(SourceManager &SM,
93 SourceLocation L, SourceRange R) {
94 assert(R.isValid() && "First range is invalid?");
95 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000096 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
99 return RangeBefore;
100 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
101 return RangeAfter;
102 return RangeOverlap;
103}
104
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105/// \brief Translate a Clang source range into a CIndex source range.
106///
107/// Clang internally represents ranges where the end location points to the
108/// start of the token at the end. However, for external clients it is more
109/// useful to have a CXSourceRange be a proper half-open interval. This routine
110/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000111CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000113 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000115 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000117 if (EndLoc.isValid() && EndLoc.isMacroID())
118 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000119 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000120 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000121 EndLoc = EndLoc.getFileLocWithOffset(Length);
122 }
123
124 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
125 R.getBegin().getRawEncoding(),
126 EndLoc.getRawEncoding() };
127 return Result;
128}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000129
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
133
Steve Naroff89922f82009-08-31 00:59:03 +0000134namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135
136class VisitorJob {
137public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000138 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000139 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000140 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000141 ExplicitTemplateArgsVisitKind,
142 NestedNameSpecifierVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000143 DeclarationNameInfoVisitKind,
144 MemberRefVisitKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000145protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000146 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147 CXCursor parent;
148 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
150 : parent(C), K(k) {
151 data[0] = d1;
152 data[1] = d2;
153 data[2] = d3;
154 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000155public:
156 Kind getKind() const { return K; }
157 const CXCursor &getParent() const { return parent; }
158 static bool classof(VisitorJob *VJ) { return true; }
159};
160
161typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
162
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000164class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000165 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000168 CXTranslationUnit TU;
169 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The declaration that serves at the parent of any statement or
175 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000176 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000178 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000179 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000184 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
185 // to the visitor. Declarations with a PCH level greater than this value will
186 // be suppressed.
187 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000188
189 /// \brief When valid, a source range to which the cursor should restrict
190 /// its search.
191 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000193 // FIXME: Eventually remove. This part of a hack to support proper
194 // iteration over all Decls contained lexically within an ObjC container.
195 DeclContext::decl_iterator *DI_current;
196 DeclContext::decl_iterator DE_current;
197
Ted Kremenekd1ded662010-11-15 23:31:32 +0000198 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
199 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
200 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
201
Douglas Gregorb1373d02010-01-20 20:59:29 +0000202 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000203 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000204
205 /// \brief Determine whether this particular source range comes before, comes
206 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000208 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000209 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
210
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000211 class SetParentRAII {
212 CXCursor &Parent;
213 Decl *&StmtParent;
214 CXCursor OldParent;
215
216 public:
217 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
218 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
219 {
220 Parent = NewParent;
221 if (clang_isDeclaration(Parent.kind))
222 StmtParent = getCursorDecl(Parent);
223 }
224
225 ~SetParentRAII() {
226 Parent = OldParent;
227 if (clang_isDeclaration(Parent.kind))
228 StmtParent = getCursorDecl(Parent);
229 }
230 };
231
Steve Naroff89922f82009-08-31 00:59:03 +0000232public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000233 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
234 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000237 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
238 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000239 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
240 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 {
242 Parent.kind = CXCursor_NoDeclFound;
243 Parent.data[0] = 0;
244 Parent.data[1] = 0;
245 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000246 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000247 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000248
Ted Kremenekd1ded662010-11-15 23:31:32 +0000249 ~CursorVisitor() {
250 // Free the pre-allocated worklists for data-recursion.
251 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
252 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
253 delete *I;
254 }
255 }
256
Ted Kremeneka60ed472010-11-16 08:15:36 +0000257 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
258 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000259
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000260 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000261
262 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
263 getPreprocessedEntities();
264
Douglas Gregorb1373d02010-01-20 20:59:29 +0000265 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000266
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000267 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000268 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000269 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000270 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000271 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000273 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
274 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000276 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000277 bool VisitClassTemplatePartialSpecializationDecl(
278 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000279 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000280 bool VisitEnumConstantDecl(EnumConstantDecl *D);
281 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
282 bool VisitFunctionDecl(FunctionDecl *ND);
283 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000284 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000285 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000287 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000288 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
290 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
291 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
292 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000293 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
295 bool VisitObjCImplDecl(ObjCImplDecl *D);
296 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
297 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
299 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
300 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000301 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000302 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000303 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000304 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000305 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000306 bool VisitUsingDecl(UsingDecl *D);
307 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
308 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000309
Douglas Gregor01829d32010-08-31 14:41:23 +0000310 // Name visitor
311 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000312 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000313
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000314 // Template visitors
315 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000316 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000317 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
318
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000319 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000320 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000322 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
324 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000325 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000326 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000327 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000329 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitPointerTypeLoc(PointerTypeLoc TL);
331 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
332 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
333 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
334 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000335 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000337 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000338 // FIXME: Implement visitors here when the unimplemented TypeLocs get
339 // implemented
340 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000341 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000342 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000343
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000344 // Data-recursive visitor functions.
345 bool IsInRegionOfInterest(CXCursor C);
346 bool RunVisitorWorkList(VisitorWorkList &WL);
347 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000348 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000349};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000350
Ted Kremenekab188932010-01-05 19:32:54 +0000351} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000352
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000353static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000354static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
355
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000356
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000358 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359}
360
Douglas Gregorb1373d02010-01-20 20:59:29 +0000361/// \brief Visit the given cursor and, if requested by the visitor,
362/// its children.
363///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000364/// \param Cursor the cursor to visit.
365///
366/// \param CheckRegionOfInterest if true, then the caller already checked that
367/// this cursor is within the region of interest.
368///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369/// \returns true if the visitation should be aborted, false if it
370/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 if (clang_isInvalid(Cursor.kind))
373 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000374
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 if (clang_isDeclaration(Cursor.kind)) {
376 Decl *D = getCursorDecl(Cursor);
377 assert(D && "Invalid declaration cursor");
378 if (D->getPCHLevel() > MaxPCHLevel)
379 return false;
380
381 if (D->isImplicit())
382 return false;
383 }
384
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385 // If we have a range of interest, and this cursor doesn't intersect with it,
386 // we're done.
387 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000388 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000389 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390 return false;
391 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000392
Douglas Gregorb1373d02010-01-20 20:59:29 +0000393 switch (Visitor(Cursor, Parent, ClientData)) {
394 case CXChildVisit_Break:
395 return true;
396
397 case CXChildVisit_Continue:
398 return false;
399
400 case CXChildVisit_Recurse:
401 return VisitChildren(Cursor);
402 }
403
Douglas Gregorfd643772010-01-25 16:45:46 +0000404 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405}
406
Douglas Gregor788f5a12010-03-20 00:41:21 +0000407std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
408CursorVisitor::getPreprocessedEntities() {
409 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000410 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000411
412 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000413 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000414
Douglas Gregor89d99802010-11-30 06:16:57 +0000415 PreprocessingRecord::iterator StartEntity, EndEntity;
416 if (OnlyLocalDecls) {
417 StartEntity = AU->pp_entity_begin();
418 EndEntity = AU->pp_entity_end();
419 } else {
420 StartEntity = PPRec.begin();
421 EndEntity = PPRec.end();
422 }
423
Douglas Gregor788f5a12010-03-20 00:41:21 +0000424 // There is no region of interest; we have to walk everything.
425 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000426 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000427
428 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000429 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000430 std::pair<FileID, unsigned> Begin
431 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
432 std::pair<FileID, unsigned> End
433 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
434
435 // The region of interest spans files; we have to walk everything.
436 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000437 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000438
439 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000440 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000441 if (ByFileMap.empty()) {
442 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000443 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000444 std::pair<FileID, unsigned> P
445 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000446
Douglas Gregor788f5a12010-03-20 00:41:21 +0000447 ByFileMap[P.first].push_back(*E);
448 }
449 }
450
451 return std::make_pair(ByFileMap[Begin.first].begin(),
452 ByFileMap[Begin.first].end());
453}
454
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000456///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457/// \returns true if the visitation should be aborted, false if it
458/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000459bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000460 if (clang_isReference(Cursor.kind)) {
461 // By definition, references have no children.
462 return false;
463 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464
465 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000467 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 if (clang_isDeclaration(Cursor.kind)) {
470 Decl *D = getCursorDecl(Cursor);
471 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000472 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000474
Douglas Gregora59e3902010-01-21 23:27:09 +0000475 if (clang_isStatement(Cursor.kind))
476 return Visit(getCursorStmt(Cursor));
477 if (clang_isExpression(Cursor.kind))
478 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000481 CXTranslationUnit tu = getCursorTU(Cursor);
482 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000483 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
484 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000485 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
486 TLEnd = CXXUnit->top_level_end();
487 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000488 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000489 return true;
490 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 } else if (VisitDeclContext(
492 CXXUnit->getASTContext().getTranslationUnitDecl()))
493 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000494
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000496 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 // FIXME: Once we have the ability to deserialize a preprocessing record,
498 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000499 PreprocessingRecord::iterator E, EEnd;
500 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000502 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000504
Douglas Gregor0396f462010-03-19 05:22:59 +0000505 continue;
506 }
507
508 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000509 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 return true;
511
512 continue;
513 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000514
515 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000516 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000517 return true;
518
519 continue;
520 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 }
522 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000523 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000525
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 return false;
528}
529
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000531 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
532 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533
Ted Kremenek664cffd2010-07-22 11:30:19 +0000534 if (Stmt *Body = B->getBody())
535 return Visit(MakeCXCursor(Body, StmtParent, TU));
536
537 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000538}
539
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000540llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
541 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000542 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543 if (Range.isInvalid())
544 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000545
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000546 switch (CompareRegionOfInterest(Range)) {
547 case RangeBefore:
548 // This declaration comes before the region of interest; skip it.
549 return llvm::Optional<bool>();
550
551 case RangeAfter:
552 // This declaration comes after the region of interest; we're done.
553 return false;
554
555 case RangeOverlap:
556 // This declaration overlaps the region of interest; visit it.
557 break;
558 }
559 }
560 return true;
561}
562
563bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
564 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
565
566 // FIXME: Eventually remove. This part of a hack to support proper
567 // iteration over all Decls contained lexically within an ObjC container.
568 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
569 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
570
571 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000572 Decl *D = *I;
573 if (D->getLexicalDeclContext() != DC)
574 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000575 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000576 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
577 if (!V.hasValue())
578 continue;
579 if (!V.getValue())
580 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000581 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582 return true;
583 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000585}
586
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000587bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
588 llvm_unreachable("Translation units are visited directly by Visit()");
589 return false;
590}
591
592bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
593 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
594 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000596 return false;
597}
598
599bool CursorVisitor::VisitTagDecl(TagDecl *D) {
600 return VisitDeclContext(D);
601}
602
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000603bool CursorVisitor::VisitClassTemplateSpecializationDecl(
604 ClassTemplateSpecializationDecl *D) {
605 bool ShouldVisitBody = false;
606 switch (D->getSpecializationKind()) {
607 case TSK_Undeclared:
608 case TSK_ImplicitInstantiation:
609 // Nothing to visit
610 return false;
611
612 case TSK_ExplicitInstantiationDeclaration:
613 case TSK_ExplicitInstantiationDefinition:
614 break;
615
616 case TSK_ExplicitSpecialization:
617 ShouldVisitBody = true;
618 break;
619 }
620
621 // Visit the template arguments used in the specialization.
622 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
623 TypeLoc TL = SpecType->getTypeLoc();
624 if (TemplateSpecializationTypeLoc *TSTLoc
625 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
626 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
627 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
628 return true;
629 }
630 }
631
632 if (ShouldVisitBody && VisitCXXRecordDecl(D))
633 return true;
634
635 return false;
636}
637
Douglas Gregor74dbe642010-08-31 19:31:58 +0000638bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
639 ClassTemplatePartialSpecializationDecl *D) {
640 // FIXME: Visit the "outer" template parameter lists on the TagDecl
641 // before visiting these template parameters.
642 if (VisitTemplateParameters(D->getTemplateParameters()))
643 return true;
644
645 // Visit the partial specialization arguments.
646 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
647 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
648 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
649 return true;
650
651 return VisitCXXRecordDecl(D);
652}
653
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000654bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000655 // Visit the default argument.
656 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
657 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
658 if (Visit(DefArg->getTypeLoc()))
659 return true;
660
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000661 return false;
662}
663
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000664bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
665 if (Expr *Init = D->getInitExpr())
666 return Visit(MakeCXCursor(Init, StmtParent, TU));
667 return false;
668}
669
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000670bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
671 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
672 if (Visit(TSInfo->getTypeLoc()))
673 return true;
674
675 return false;
676}
677
Douglas Gregora67e03f2010-09-09 21:42:20 +0000678/// \brief Compare two base or member initializers based on their source order.
679static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
680 CXXBaseOrMemberInitializer const * const *X
681 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
682 CXXBaseOrMemberInitializer const * const *Y
683 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
684
685 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
686 return -1;
687 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
688 return 1;
689 else
690 return 0;
691}
692
Douglas Gregorb1373d02010-01-20 20:59:29 +0000693bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000694 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
695 // Visit the function declaration's syntactic components in the order
696 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000697 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000698 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
699
700 // If we have a function declared directly (without the use of a typedef),
701 // visit just the return type. Otherwise, just visit the function's type
702 // now.
703 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
704 (!FTL && Visit(TL)))
705 return true;
706
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000707 // Visit the nested-name-specifier, if present.
708 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
709 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
710 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000711
712 // Visit the declaration name.
713 if (VisitDeclarationNameInfo(ND->getNameInfo()))
714 return true;
715
716 // FIXME: Visit explicitly-specified template arguments!
717
718 // Visit the function parameters, if we have a function type.
719 if (FTL && VisitFunctionTypeLoc(*FTL, true))
720 return true;
721
722 // FIXME: Attributes?
723 }
724
Douglas Gregora67e03f2010-09-09 21:42:20 +0000725 if (ND->isThisDeclarationADefinition()) {
726 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
727 // Find the initializers that were written in the source.
728 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
729 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
730 IEnd = Constructor->init_end();
731 I != IEnd; ++I) {
732 if (!(*I)->isWritten())
733 continue;
734
735 WrittenInits.push_back(*I);
736 }
737
738 // Sort the initializers in source order
739 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
740 &CompareCXXBaseOrMemberInitializers);
741
742 // Visit the initializers in source order
743 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
744 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000745 if (Init->isAnyMemberInitializer()) {
746 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000747 Init->getMemberLocation(), TU)))
748 return true;
749 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
750 if (Visit(BaseInfo->getTypeLoc()))
751 return true;
752 }
753
754 // Visit the initializer value.
755 if (Expr *Initializer = Init->getInit())
756 if (Visit(MakeCXCursor(Initializer, ND, TU)))
757 return true;
758 }
759 }
760
761 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
762 return true;
763 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000764
Douglas Gregorb1373d02010-01-20 20:59:29 +0000765 return false;
766}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000767
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000768bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
769 if (VisitDeclaratorDecl(D))
770 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772 if (Expr *BitWidth = D->getBitWidth())
773 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000774
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000775 return false;
776}
777
778bool CursorVisitor::VisitVarDecl(VarDecl *D) {
779 if (VisitDeclaratorDecl(D))
780 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000781
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000782 if (Expr *Init = D->getInit())
783 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785 return false;
786}
787
Douglas Gregor84b51d72010-09-01 20:16:53 +0000788bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
789 if (VisitDeclaratorDecl(D))
790 return true;
791
792 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
793 if (Expr *DefArg = D->getDefaultArgument())
794 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
795
796 return false;
797}
798
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000799bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
800 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
801 // before visiting these template parameters.
802 if (VisitTemplateParameters(D->getTemplateParameters()))
803 return true;
804
805 return VisitFunctionDecl(D->getTemplatedDecl());
806}
807
Douglas Gregor39d6f072010-08-31 19:02:00 +0000808bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
809 // FIXME: Visit the "outer" template parameter lists on the TagDecl
810 // before visiting these template parameters.
811 if (VisitTemplateParameters(D->getTemplateParameters()))
812 return true;
813
814 return VisitCXXRecordDecl(D->getTemplatedDecl());
815}
816
Douglas Gregor84b51d72010-09-01 20:16:53 +0000817bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
818 if (VisitTemplateParameters(D->getTemplateParameters()))
819 return true;
820
821 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
822 VisitTemplateArgumentLoc(D->getDefaultArgument()))
823 return true;
824
825 return false;
826}
827
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000828bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000829 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
830 if (Visit(TSInfo->getTypeLoc()))
831 return true;
832
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000834 PEnd = ND->param_end();
835 P != PEnd; ++P) {
836 if (Visit(MakeCXCursor(*P, TU)))
837 return true;
838 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 if (ND->isThisDeclarationADefinition() &&
841 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
842 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000843
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000844 return false;
845}
846
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000847namespace {
848 struct ContainerDeclsSort {
849 SourceManager &SM;
850 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
851 bool operator()(Decl *A, Decl *B) {
852 SourceLocation L_A = A->getLocStart();
853 SourceLocation L_B = B->getLocStart();
854 assert(L_A.isValid() && L_B.isValid());
855 return SM.isBeforeInTranslationUnit(L_A, L_B);
856 }
857 };
858}
859
Douglas Gregora59e3902010-01-21 23:27:09 +0000860bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000861 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
862 // an @implementation can lexically contain Decls that are not properly
863 // nested in the AST. When we identify such cases, we need to retrofit
864 // this nesting here.
865 if (!DI_current)
866 return VisitDeclContext(D);
867
868 // Scan the Decls that immediately come after the container
869 // in the current DeclContext. If any fall within the
870 // container's lexical region, stash them into a vector
871 // for later processing.
872 llvm::SmallVector<Decl *, 24> DeclsInContainer;
873 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000874 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000875 if (EndLoc.isValid()) {
876 DeclContext::decl_iterator next = *DI_current;
877 while (++next != DE_current) {
878 Decl *D_next = *next;
879 if (!D_next)
880 break;
881 SourceLocation L = D_next->getLocStart();
882 if (!L.isValid())
883 break;
884 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
885 *DI_current = next;
886 DeclsInContainer.push_back(D_next);
887 continue;
888 }
889 break;
890 }
891 }
892
893 // The common case.
894 if (DeclsInContainer.empty())
895 return VisitDeclContext(D);
896
897 // Get all the Decls in the DeclContext, and sort them with the
898 // additional ones we've collected. Then visit them.
899 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
900 I!=E; ++I) {
901 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000902 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
903 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000904 continue;
905 DeclsInContainer.push_back(subDecl);
906 }
907
908 // Now sort the Decls so that they appear in lexical order.
909 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
910 ContainerDeclsSort(SM));
911
912 // Now visit the decls.
913 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
914 E = DeclsInContainer.end(); I != E; ++I) {
915 CXCursor Cursor = MakeCXCursor(*I, TU);
916 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
917 if (!V.hasValue())
918 continue;
919 if (!V.getValue())
920 return false;
921 if (Visit(Cursor, true))
922 return true;
923 }
924 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000925}
926
Douglas Gregorb1373d02010-01-20 20:59:29 +0000927bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000928 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
929 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000930 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000931
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000932 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
933 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
934 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000935 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000936 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000937
Douglas Gregora59e3902010-01-21 23:27:09 +0000938 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000939}
940
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000941bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
942 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
943 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
944 E = PID->protocol_end(); I != E; ++I, ++PL)
945 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
946 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000947
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000948 return VisitObjCContainerDecl(PID);
949}
950
Ted Kremenek23173d72010-05-18 21:09:07 +0000951bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000952 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000953 return true;
954
Ted Kremenek23173d72010-05-18 21:09:07 +0000955 // FIXME: This implements a workaround with @property declarations also being
956 // installed in the DeclContext for the @interface. Eventually this code
957 // should be removed.
958 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
959 if (!CDecl || !CDecl->IsClassExtension())
960 return false;
961
962 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
963 if (!ID)
964 return false;
965
966 IdentifierInfo *PropertyId = PD->getIdentifier();
967 ObjCPropertyDecl *prevDecl =
968 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
969
970 if (!prevDecl)
971 return false;
972
973 // Visit synthesized methods since they will be skipped when visiting
974 // the @interface.
975 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000976 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000977 if (Visit(MakeCXCursor(MD, TU)))
978 return true;
979
980 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000981 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000982 if (Visit(MakeCXCursor(MD, TU)))
983 return true;
984
985 return false;
986}
987
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000989 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000990 if (D->getSuperClass() &&
991 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000993 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000994 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000996 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
997 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
998 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000999 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001000 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001001
Douglas Gregora59e3902010-01-21 23:27:09 +00001002 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001003}
1004
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001005bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1006 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001007}
1008
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001009bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001010 // 'ID' could be null when dealing with invalid code.
1011 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1012 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001015 return VisitObjCImplDecl(D);
1016}
1017
1018bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1019#if 0
1020 // Issue callbacks for super class.
1021 // FIXME: No source location information!
1022 if (D->getSuperClass() &&
1023 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001025 TU)))
1026 return true;
1027#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029 return VisitObjCImplDecl(D);
1030}
1031
1032bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1033 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1034 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1035 E = D->protocol_end();
1036 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001037 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001038 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039
1040 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001041}
1042
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1044 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1045 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1046 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001048 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001049}
1050
Douglas Gregora4ffd852010-11-17 01:03:52 +00001051bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1052 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1053 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1054
1055 return false;
1056}
1057
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001058bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1059 return VisitDeclContext(D);
1060}
1061
Douglas Gregor69319002010-08-31 23:48:11 +00001062bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001063 // Visit nested-name-specifier.
1064 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1065 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1066 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001067
1068 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1069 D->getTargetNameLoc(), TU));
1070}
1071
Douglas Gregor7e242562010-09-01 19:52:22 +00001072bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001073 // Visit nested-name-specifier.
1074 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1075 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1076 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001077
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001078 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1079 return true;
1080
Douglas Gregor7e242562010-09-01 19:52:22 +00001081 return VisitDeclarationNameInfo(D->getNameInfo());
1082}
1083
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001084bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001085 // Visit nested-name-specifier.
1086 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1087 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1088 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001089
1090 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1091 D->getIdentLocation(), TU));
1092}
1093
Douglas Gregor7e242562010-09-01 19:52:22 +00001094bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001095 // Visit nested-name-specifier.
1096 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1097 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1098 return true;
1099
Douglas Gregor7e242562010-09-01 19:52:22 +00001100 return VisitDeclarationNameInfo(D->getNameInfo());
1101}
1102
1103bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1104 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105 // Visit nested-name-specifier.
1106 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1107 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1108 return true;
1109
Douglas Gregor7e242562010-09-01 19:52:22 +00001110 return false;
1111}
1112
Douglas Gregor01829d32010-08-31 14:41:23 +00001113bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1114 switch (Name.getName().getNameKind()) {
1115 case clang::DeclarationName::Identifier:
1116 case clang::DeclarationName::CXXLiteralOperatorName:
1117 case clang::DeclarationName::CXXOperatorName:
1118 case clang::DeclarationName::CXXUsingDirective:
1119 return false;
1120
1121 case clang::DeclarationName::CXXConstructorName:
1122 case clang::DeclarationName::CXXDestructorName:
1123 case clang::DeclarationName::CXXConversionFunctionName:
1124 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1125 return Visit(TSInfo->getTypeLoc());
1126 return false;
1127
1128 case clang::DeclarationName::ObjCZeroArgSelector:
1129 case clang::DeclarationName::ObjCOneArgSelector:
1130 case clang::DeclarationName::ObjCMultiArgSelector:
1131 // FIXME: Per-identifier location info?
1132 return false;
1133 }
1134
1135 return false;
1136}
1137
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001138bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1139 SourceRange Range) {
1140 // FIXME: This whole routine is a hack to work around the lack of proper
1141 // source information in nested-name-specifiers (PR5791). Since we do have
1142 // a beginning source location, we can visit the first component of the
1143 // nested-name-specifier, if it's a single-token component.
1144 if (!NNS)
1145 return false;
1146
1147 // Get the first component in the nested-name-specifier.
1148 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1149 NNS = Prefix;
1150
1151 switch (NNS->getKind()) {
1152 case NestedNameSpecifier::Namespace:
1153 // FIXME: The token at this source location might actually have been a
1154 // namespace alias, but we don't model that. Lame!
1155 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1156 TU));
1157
1158 case NestedNameSpecifier::TypeSpec: {
1159 // If the type has a form where we know that the beginning of the source
1160 // range matches up with a reference cursor. Visit the appropriate reference
1161 // cursor.
1162 Type *T = NNS->getAsType();
1163 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1164 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1165 if (const TagType *Tag = dyn_cast<TagType>(T))
1166 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1167 if (const TemplateSpecializationType *TST
1168 = dyn_cast<TemplateSpecializationType>(T))
1169 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1170 break;
1171 }
1172
1173 case NestedNameSpecifier::TypeSpecWithTemplate:
1174 case NestedNameSpecifier::Global:
1175 case NestedNameSpecifier::Identifier:
1176 break;
1177 }
1178
1179 return false;
1180}
1181
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001182bool CursorVisitor::VisitTemplateParameters(
1183 const TemplateParameterList *Params) {
1184 if (!Params)
1185 return false;
1186
1187 for (TemplateParameterList::const_iterator P = Params->begin(),
1188 PEnd = Params->end();
1189 P != PEnd; ++P) {
1190 if (Visit(MakeCXCursor(*P, TU)))
1191 return true;
1192 }
1193
1194 return false;
1195}
1196
Douglas Gregor0b36e612010-08-31 20:37:03 +00001197bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1198 switch (Name.getKind()) {
1199 case TemplateName::Template:
1200 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1201
1202 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001203 // Visit the overloaded template set.
1204 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1205 return true;
1206
Douglas Gregor0b36e612010-08-31 20:37:03 +00001207 return false;
1208
1209 case TemplateName::DependentTemplate:
1210 // FIXME: Visit nested-name-specifier.
1211 return false;
1212
1213 case TemplateName::QualifiedTemplate:
1214 // FIXME: Visit nested-name-specifier.
1215 return Visit(MakeCursorTemplateRef(
1216 Name.getAsQualifiedTemplateName()->getDecl(),
1217 Loc, TU));
1218 }
1219
1220 return false;
1221}
1222
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001223bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1224 switch (TAL.getArgument().getKind()) {
1225 case TemplateArgument::Null:
1226 case TemplateArgument::Integral:
1227 return false;
1228
1229 case TemplateArgument::Pack:
1230 // FIXME: Implement when variadic templates come along.
1231 return false;
1232
1233 case TemplateArgument::Type:
1234 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1235 return Visit(TSInfo->getTypeLoc());
1236 return false;
1237
1238 case TemplateArgument::Declaration:
1239 if (Expr *E = TAL.getSourceDeclExpression())
1240 return Visit(MakeCXCursor(E, StmtParent, TU));
1241 return false;
1242
1243 case TemplateArgument::Expression:
1244 if (Expr *E = TAL.getSourceExpression())
1245 return Visit(MakeCXCursor(E, StmtParent, TU));
1246 return false;
1247
1248 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001249 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1250 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001251 }
1252
1253 return false;
1254}
1255
Ted Kremeneka0536d82010-05-07 01:04:29 +00001256bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1257 return VisitDeclContext(D);
1258}
1259
Douglas Gregor01829d32010-08-31 14:41:23 +00001260bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1261 return Visit(TL.getUnqualifiedLoc());
1262}
1263
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001264bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001265 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001266
1267 // Some builtin types (such as Objective-C's "id", "sel", and
1268 // "Class") have associated declarations. Create cursors for those.
1269 QualType VisitType;
1270 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001271 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001272 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001273 case BuiltinType::Char_U:
1274 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001275 case BuiltinType::Char16:
1276 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278 case BuiltinType::UInt:
1279 case BuiltinType::ULong:
1280 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001281 case BuiltinType::UInt128:
1282 case BuiltinType::Char_S:
1283 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001284 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001285 case BuiltinType::Short:
1286 case BuiltinType::Int:
1287 case BuiltinType::Long:
1288 case BuiltinType::LongLong:
1289 case BuiltinType::Int128:
1290 case BuiltinType::Float:
1291 case BuiltinType::Double:
1292 case BuiltinType::LongDouble:
1293 case BuiltinType::NullPtr:
1294 case BuiltinType::Overload:
1295 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001296 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001297
1298 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001299 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001300
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001301 case BuiltinType::ObjCId:
1302 VisitType = Context.getObjCIdType();
1303 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001304
1305 case BuiltinType::ObjCClass:
1306 VisitType = Context.getObjCClassType();
1307 break;
1308
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001309 case BuiltinType::ObjCSel:
1310 VisitType = Context.getObjCSelType();
1311 break;
1312 }
1313
1314 if (!VisitType.isNull()) {
1315 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001316 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001317 TU));
1318 }
1319
1320 return false;
1321}
1322
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001323bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1324 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1325}
1326
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001327bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1328 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1329}
1330
1331bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1332 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1333}
1334
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001335bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001336 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001337 // no context information with which we can match up the depth/index in the
1338 // type to the appropriate
1339 return false;
1340}
1341
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001342bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1343 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1344 return true;
1345
John McCallc12c5bb2010-05-15 11:32:37 +00001346 return false;
1347}
1348
1349bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1350 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1351 return true;
1352
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001353 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1354 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1355 TU)))
1356 return true;
1357 }
1358
1359 return false;
1360}
1361
1362bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001363 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001364}
1365
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001366bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1367 return Visit(TL.getInnerLoc());
1368}
1369
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1371 return Visit(TL.getPointeeLoc());
1372}
1373
1374bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1375 return Visit(TL.getPointeeLoc());
1376}
1377
1378bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1379 return Visit(TL.getPointeeLoc());
1380}
1381
1382bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001383 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384}
1385
1386bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001387 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388}
1389
Douglas Gregor01829d32010-08-31 14:41:23 +00001390bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1391 bool SkipResultType) {
1392 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393 return true;
1394
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001395 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001396 if (Decl *D = TL.getArg(I))
1397 if (Visit(MakeCXCursor(D, TU)))
1398 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001399
1400 return false;
1401}
1402
1403bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1404 if (Visit(TL.getElementLoc()))
1405 return true;
1406
1407 if (Expr *Size = TL.getSizeExpr())
1408 return Visit(MakeCXCursor(Size, StmtParent, TU));
1409
1410 return false;
1411}
1412
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001413bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1414 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001415 // Visit the template name.
1416 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1417 TL.getTemplateNameLoc()))
1418 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001419
1420 // Visit the template arguments.
1421 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1422 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1423 return true;
1424
1425 return false;
1426}
1427
Douglas Gregor2332c112010-01-21 20:48:56 +00001428bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1429 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1430}
1431
1432bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1433 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1434 return Visit(TSInfo->getTypeLoc());
1435
1436 return false;
1437}
1438
Douglas Gregor7536dd52010-12-20 02:24:11 +00001439bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1440 return Visit(TL.getPatternLoc());
1441}
1442
Ted Kremenek3064ef92010-08-27 21:34:58 +00001443bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1444 if (D->isDefinition()) {
1445 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1446 E = D->bases_end(); I != E; ++I) {
1447 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1448 return true;
1449 }
1450 }
1451
1452 return VisitTagDecl(D);
1453}
1454
Ted Kremenek09dfa372010-02-18 05:46:33 +00001455bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001456 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1457 i != e; ++i)
1458 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001459 return true;
1460
1461 return false;
1462}
1463
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001464//===----------------------------------------------------------------------===//
1465// Data-recursive visitor methods.
1466//===----------------------------------------------------------------------===//
1467
Ted Kremenek28a71942010-11-13 00:36:47 +00001468namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001469#define DEF_JOB(NAME, DATA, KIND)\
1470class NAME : public VisitorJob {\
1471public:\
1472 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1473 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001474 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001475};
1476
1477DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1478DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001479DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001480DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001481DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1482 ExplicitTemplateArgsVisitKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001483#undef DEF_JOB
1484
1485class DeclVisit : public VisitorJob {
1486public:
1487 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1488 VisitorJob(parent, VisitorJob::DeclVisitKind,
1489 d, isFirst ? (void*) 1 : (void*) 0) {}
1490 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001491 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001492 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001493 Decl *get() const { return static_cast<Decl*>(data[0]); }
1494 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001495};
Ted Kremenek035dc412010-11-13 00:36:50 +00001496class TypeLocVisit : public VisitorJob {
1497public:
1498 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1499 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1500 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1501
1502 static bool classof(const VisitorJob *VJ) {
1503 return VJ->getKind() == TypeLocVisitKind;
1504 }
1505
Ted Kremenek82f3c502010-11-15 22:23:26 +00001506 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001507 QualType T = QualType::getFromOpaquePtr(data[0]);
1508 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001509 }
1510};
1511
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001512class LabelRefVisit : public VisitorJob {
1513public:
1514 LabelRefVisit(LabelStmt *LS, SourceLocation labelLoc, CXCursor parent)
1515 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LS,
1516 (void*) labelLoc.getRawEncoding()) {}
1517
1518 static bool classof(const VisitorJob *VJ) {
1519 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1520 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001521 LabelStmt *get() const { return static_cast<LabelStmt*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001522 SourceLocation getLoc() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001523 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); }
1524};
1525class NestedNameSpecifierVisit : public VisitorJob {
1526public:
1527 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1528 CXCursor parent)
1529 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
1530 NS, (void*) R.getBegin().getRawEncoding(),
1531 (void*) R.getEnd().getRawEncoding()) {}
1532 static bool classof(const VisitorJob *VJ) {
1533 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1534 }
1535 NestedNameSpecifier *get() const {
1536 return static_cast<NestedNameSpecifier*>(data[0]);
1537 }
1538 SourceRange getSourceRange() const {
1539 SourceLocation A =
1540 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1541 SourceLocation B =
1542 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1543 return SourceRange(A, B);
1544 }
1545};
1546class DeclarationNameInfoVisit : public VisitorJob {
1547public:
1548 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1549 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1550 static bool classof(const VisitorJob *VJ) {
1551 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1552 }
1553 DeclarationNameInfo get() const {
1554 Stmt *S = static_cast<Stmt*>(data[0]);
1555 switch (S->getStmtClass()) {
1556 default:
1557 llvm_unreachable("Unhandled Stmt");
1558 case Stmt::CXXDependentScopeMemberExprClass:
1559 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1560 case Stmt::DependentScopeDeclRefExprClass:
1561 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1562 }
1563 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001564};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001565class MemberRefVisit : public VisitorJob {
1566public:
1567 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1568 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1569 (void*) L.getRawEncoding()) {}
1570 static bool classof(const VisitorJob *VJ) {
1571 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1572 }
1573 FieldDecl *get() const {
1574 return static_cast<FieldDecl*>(data[0]);
1575 }
1576 SourceLocation getLoc() const {
1577 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1578 }
1579};
Ted Kremenek28a71942010-11-13 00:36:47 +00001580class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1581 VisitorWorkList &WL;
1582 CXCursor Parent;
1583public:
1584 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1585 : WL(wl), Parent(parent) {}
1586
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001587 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001588 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001589 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001590 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001591 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001592 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001593 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001594 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001595 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001596 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001597 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001598 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001599 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001600 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001601 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001602 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001603 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001604 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001605 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1606 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001607 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001608 void VisitIfStmt(IfStmt *If);
1609 void VisitInitListExpr(InitListExpr *IE);
1610 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001611 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001612 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001613 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1614 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001615 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001616 void VisitStmt(Stmt *S);
1617 void VisitSwitchStmt(SwitchStmt *S);
1618 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001619 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001620 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001621 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001622 void VisitVAArgExpr(VAArgExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001623
1624private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001625 void AddDeclarationNameInfo(Stmt *S);
1626 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001627 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001628 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001629 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001630 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001631 void AddTypeLoc(TypeSourceInfo *TI);
1632 void EnqueueChildren(Stmt *S);
1633};
1634} // end anonyous namespace
1635
Ted Kremenekf64d8032010-11-18 00:02:32 +00001636void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1637 // 'S' should always be non-null, since it comes from the
1638 // statement we are visiting.
1639 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1640}
1641void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1642 SourceRange R) {
1643 if (N)
1644 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1645}
Ted Kremenek28a71942010-11-13 00:36:47 +00001646void EnqueueVisitor::AddStmt(Stmt *S) {
1647 if (S)
1648 WL.push_back(StmtVisit(S, Parent));
1649}
Ted Kremenek035dc412010-11-13 00:36:50 +00001650void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001651 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001652 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001653}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001654void EnqueueVisitor::
1655 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1656 if (A)
1657 WL.push_back(ExplicitTemplateArgsVisit(
1658 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1659}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001660void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1661 if (D)
1662 WL.push_back(MemberRefVisit(D, L, Parent));
1663}
Ted Kremenek28a71942010-11-13 00:36:47 +00001664void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1665 if (TI)
1666 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1667 }
1668void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001669 unsigned size = WL.size();
1670 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1671 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001672 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001673 }
1674 if (size == WL.size())
1675 return;
1676 // Now reverse the entries we just added. This will match the DFS
1677 // ordering performed by the worklist.
1678 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1679 std::reverse(I, E);
1680}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001681void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1682 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1683}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001684void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1685 AddDecl(B->getBlockDecl());
1686}
Ted Kremenek28a71942010-11-13 00:36:47 +00001687void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1688 EnqueueChildren(E);
1689 AddTypeLoc(E->getTypeSourceInfo());
1690}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001691void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1692 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1693 E = S->body_rend(); I != E; ++I) {
1694 AddStmt(*I);
1695 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001696}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001697void EnqueueVisitor::
1698VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1699 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1700 AddDeclarationNameInfo(E);
1701 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1702 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1703 if (!E->isImplicitAccess())
1704 AddStmt(E->getBase());
1705}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001706void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1707 // Enqueue the initializer or constructor arguments.
1708 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1709 AddStmt(E->getConstructorArg(I-1));
1710 // Enqueue the array size, if any.
1711 AddStmt(E->getArraySize());
1712 // Enqueue the allocated type.
1713 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1714 // Enqueue the placement arguments.
1715 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1716 AddStmt(E->getPlacementArg(I-1));
1717}
Ted Kremenek28a71942010-11-13 00:36:47 +00001718void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001719 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1720 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001721 AddStmt(CE->getCallee());
1722 AddStmt(CE->getArg(0));
1723}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001724void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1725 // Visit the name of the type being destroyed.
1726 AddTypeLoc(E->getDestroyedTypeInfo());
1727 // Visit the scope type that looks disturbingly like the nested-name-specifier
1728 // but isn't.
1729 AddTypeLoc(E->getScopeTypeInfo());
1730 // Visit the nested-name-specifier.
1731 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1732 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1733 // Visit base expression.
1734 AddStmt(E->getBase());
1735}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001736void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1737 AddTypeLoc(E->getTypeSourceInfo());
1738}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001739void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1740 EnqueueChildren(E);
1741 AddTypeLoc(E->getTypeSourceInfo());
1742}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001743void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1744 EnqueueChildren(E);
1745 if (E->isTypeOperand())
1746 AddTypeLoc(E->getTypeOperandSourceInfo());
1747}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001748
1749void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1750 *E) {
1751 EnqueueChildren(E);
1752 AddTypeLoc(E->getTypeSourceInfo());
1753}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001754void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1755 EnqueueChildren(E);
1756 if (E->isTypeOperand())
1757 AddTypeLoc(E->getTypeOperandSourceInfo());
1758}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001759void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001760 if (DR->hasExplicitTemplateArgs()) {
1761 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1762 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001763 WL.push_back(DeclRefExprParts(DR, Parent));
1764}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001765void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1766 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1767 AddDeclarationNameInfo(E);
1768 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1769 AddNestedNameSpecifier(Qualifier, E->getQualifierRange());
1770}
Ted Kremenek035dc412010-11-13 00:36:50 +00001771void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1772 unsigned size = WL.size();
1773 bool isFirst = true;
1774 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1775 D != DEnd; ++D) {
1776 AddDecl(*D, isFirst);
1777 isFirst = false;
1778 }
1779 if (size == WL.size())
1780 return;
1781 // Now reverse the entries we just added. This will match the DFS
1782 // ordering performed by the worklist.
1783 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1784 std::reverse(I, E);
1785}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001786void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1787 AddStmt(E->getInit());
1788 typedef DesignatedInitExpr::Designator Designator;
1789 for (DesignatedInitExpr::reverse_designators_iterator
1790 D = E->designators_rbegin(), DEnd = E->designators_rend();
1791 D != DEnd; ++D) {
1792 if (D->isFieldDesignator()) {
1793 if (FieldDecl *Field = D->getField())
1794 AddMemberRef(Field, D->getFieldLoc());
1795 continue;
1796 }
1797 if (D->isArrayDesignator()) {
1798 AddStmt(E->getArrayIndex(*D));
1799 continue;
1800 }
1801 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1802 AddStmt(E->getArrayRangeEnd(*D));
1803 AddStmt(E->getArrayRangeStart(*D));
1804 }
1805}
Ted Kremenek28a71942010-11-13 00:36:47 +00001806void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1807 EnqueueChildren(E);
1808 AddTypeLoc(E->getTypeInfoAsWritten());
1809}
1810void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1811 AddStmt(FS->getBody());
1812 AddStmt(FS->getInc());
1813 AddStmt(FS->getCond());
1814 AddDecl(FS->getConditionVariable());
1815 AddStmt(FS->getInit());
1816}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001817void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1818 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1819}
Ted Kremenek28a71942010-11-13 00:36:47 +00001820void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1821 AddStmt(If->getElse());
1822 AddStmt(If->getThen());
1823 AddStmt(If->getCond());
1824 AddDecl(If->getConditionVariable());
1825}
1826void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1827 // We care about the syntactic form of the initializer list, only.
1828 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1829 IE = Syntactic;
1830 EnqueueChildren(IE);
1831}
1832void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001833 WL.push_back(MemberExprParts(M, Parent));
1834
1835 // If the base of the member access expression is an implicit 'this', don't
1836 // visit it.
1837 // FIXME: If we ever want to show these implicit accesses, this will be
1838 // unfortunate. However, clang_getCursor() relies on this behavior.
1839 if (CXXThisExpr *This
1840 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1841 if (This->isImplicit())
1842 return;
1843
Ted Kremenek28a71942010-11-13 00:36:47 +00001844 AddStmt(M->getBase());
1845}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001846void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1847 AddTypeLoc(E->getEncodedTypeSourceInfo());
1848}
Ted Kremenek28a71942010-11-13 00:36:47 +00001849void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1850 EnqueueChildren(M);
1851 AddTypeLoc(M->getClassReceiverTypeInfo());
1852}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001853void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1854 // Visit the components of the offsetof expression.
1855 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1856 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1857 const OffsetOfNode &Node = E->getComponent(I-1);
1858 switch (Node.getKind()) {
1859 case OffsetOfNode::Array:
1860 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1861 break;
1862 case OffsetOfNode::Field:
1863 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1864 break;
1865 case OffsetOfNode::Identifier:
1866 case OffsetOfNode::Base:
1867 continue;
1868 }
1869 }
1870 // Visit the type into which we're computing the offset.
1871 AddTypeLoc(E->getTypeSourceInfo());
1872}
Ted Kremenek28a71942010-11-13 00:36:47 +00001873void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001874 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001875 WL.push_back(OverloadExprParts(E, Parent));
1876}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001877void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1878 EnqueueChildren(E);
1879 if (E->isArgumentType())
1880 AddTypeLoc(E->getArgumentTypeInfo());
1881}
Ted Kremenek28a71942010-11-13 00:36:47 +00001882void EnqueueVisitor::VisitStmt(Stmt *S) {
1883 EnqueueChildren(S);
1884}
1885void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1886 AddStmt(S->getBody());
1887 AddStmt(S->getCond());
1888 AddDecl(S->getConditionVariable());
1889}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001890
Ted Kremenek28a71942010-11-13 00:36:47 +00001891void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1892 AddStmt(W->getBody());
1893 AddStmt(W->getCond());
1894 AddDecl(W->getConditionVariable());
1895}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001896void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1897 AddTypeLoc(E->getQueriedTypeSourceInfo());
1898}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001899
1900void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00001901 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00001902 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00001903}
1904
Ted Kremenek28a71942010-11-13 00:36:47 +00001905void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1906 VisitOverloadExpr(U);
1907 if (!U->isImplicitAccess())
1908 AddStmt(U->getBase());
1909}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001910void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
1911 AddStmt(E->getSubExpr());
1912 AddTypeLoc(E->getWrittenTypeInfo());
1913}
Ted Kremenek60458782010-11-12 21:34:16 +00001914
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001915void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001916 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001917}
1918
1919bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1920 if (RegionOfInterest.isValid()) {
1921 SourceRange Range = getRawCursorExtent(C);
1922 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1923 return false;
1924 }
1925 return true;
1926}
1927
1928bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1929 while (!WL.empty()) {
1930 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001931 VisitorJob LI = WL.back();
1932 WL.pop_back();
1933
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001934 // Set the Parent field, then back to its old value once we're done.
1935 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1936
1937 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001938 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001939 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001940 if (!D)
1941 continue;
1942
1943 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001944 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001945 return true;
1946
1947 continue;
1948 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00001949 case VisitorJob::ExplicitTemplateArgsVisitKind: {
1950 const ExplicitTemplateArgumentList *ArgList =
1951 cast<ExplicitTemplateArgsVisit>(&LI)->get();
1952 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1953 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1954 Arg != ArgEnd; ++Arg) {
1955 if (VisitTemplateArgumentLoc(*Arg))
1956 return true;
1957 }
1958 continue;
1959 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001960 case VisitorJob::TypeLocVisitKind: {
1961 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001962 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001963 return true;
1964 continue;
1965 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001966 case VisitorJob::LabelRefVisitKind: {
1967 LabelStmt *LS = cast<LabelRefVisit>(&LI)->get();
1968 if (Visit(MakeCursorLabelRef(LS,
1969 cast<LabelRefVisit>(&LI)->getLoc(),
1970 TU)))
1971 return true;
1972 continue;
1973 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001974 case VisitorJob::NestedNameSpecifierVisitKind: {
1975 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
1976 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
1977 return true;
1978 continue;
1979 }
1980 case VisitorJob::DeclarationNameInfoVisitKind: {
1981 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
1982 ->get()))
1983 return true;
1984 continue;
1985 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00001986 case VisitorJob::MemberRefVisitKind: {
1987 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
1988 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
1989 return true;
1990 continue;
1991 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001992 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001993 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001994 if (!S)
1995 continue;
1996
Ted Kremenekf1107452010-11-12 18:26:56 +00001997 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001998 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001999 if (!IsInRegionOfInterest(Cursor))
2000 continue;
2001 switch (Visitor(Cursor, Parent, ClientData)) {
2002 case CXChildVisit_Break: return true;
2003 case CXChildVisit_Continue: break;
2004 case CXChildVisit_Recurse:
2005 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002006 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002007 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002008 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002009 }
2010 case VisitorJob::MemberExprPartsKind: {
2011 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002012 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002013
2014 // Visit the nested-name-specifier
2015 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2016 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2017 return true;
2018
2019 // Visit the declaration name.
2020 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2021 return true;
2022
2023 // Visit the explicitly-specified template arguments, if any.
2024 if (M->hasExplicitTemplateArgs()) {
2025 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2026 *ArgEnd = Arg + M->getNumTemplateArgs();
2027 Arg != ArgEnd; ++Arg) {
2028 if (VisitTemplateArgumentLoc(*Arg))
2029 return true;
2030 }
2031 }
2032 continue;
2033 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002034 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002035 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002036 // Visit nested-name-specifier, if present.
2037 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2038 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2039 return true;
2040 // Visit declaration name.
2041 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2042 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002043 continue;
2044 }
Ted Kremenek60458782010-11-12 21:34:16 +00002045 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002046 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002047 // Visit the nested-name-specifier.
2048 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2049 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2050 return true;
2051 // Visit the declaration name.
2052 if (VisitDeclarationNameInfo(O->getNameInfo()))
2053 return true;
2054 // Visit the overloaded declaration reference.
2055 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2056 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002057 continue;
2058 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002059 }
2060 }
2061 return false;
2062}
2063
Ted Kremenekcdba6592010-11-18 00:42:18 +00002064bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002065 VisitorWorkList *WL = 0;
2066 if (!WorkListFreeList.empty()) {
2067 WL = WorkListFreeList.back();
2068 WL->clear();
2069 WorkListFreeList.pop_back();
2070 }
2071 else {
2072 WL = new VisitorWorkList();
2073 WorkListCache.push_back(WL);
2074 }
2075 EnqueueWorkList(*WL, S);
2076 bool result = RunVisitorWorkList(*WL);
2077 WorkListFreeList.push_back(WL);
2078 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002079}
2080
2081//===----------------------------------------------------------------------===//
2082// Misc. API hooks.
2083//===----------------------------------------------------------------------===//
2084
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002085static llvm::sys::Mutex EnableMultithreadingMutex;
2086static bool EnabledMultithreading;
2087
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002088extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002089CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2090 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002091 // Disable pretty stack trace functionality, which will otherwise be a very
2092 // poor citizen of the world and set up all sorts of signal handlers.
2093 llvm::DisablePrettyStackTrace = true;
2094
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002095 // We use crash recovery to make some of our APIs more reliable, implicitly
2096 // enable it.
2097 llvm::CrashRecoveryContext::Enable();
2098
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002099 // Enable support for multithreading in LLVM.
2100 {
2101 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2102 if (!EnabledMultithreading) {
2103 llvm::llvm_start_multithreaded();
2104 EnabledMultithreading = true;
2105 }
2106 }
2107
Douglas Gregora030b7c2010-01-22 20:35:53 +00002108 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002109 if (excludeDeclarationsFromPCH)
2110 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002111 if (displayDiagnostics)
2112 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002113 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002114}
2115
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002116void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002117 if (CIdx)
2118 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002119}
2120
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002121CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002122 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002123 if (!CIdx)
2124 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002125
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002126 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002127 FileSystemOptions FileSystemOpts;
2128 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002129
Douglas Gregor28019772010-04-05 23:52:57 +00002130 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002131 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002132 CXXIdx->getOnlyLocalDecls(),
2133 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002134 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002135}
2136
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002137unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002138 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002139 CXTranslationUnit_CacheCompletionResults |
2140 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002141}
2142
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002143CXTranslationUnit
2144clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2145 const char *source_filename,
2146 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002147 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002148 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002149 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002150 return clang_parseTranslationUnit(CIdx, source_filename,
2151 command_line_args, num_command_line_args,
2152 unsaved_files, num_unsaved_files,
2153 CXTranslationUnit_DetailedPreprocessingRecord);
2154}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002155
2156struct ParseTranslationUnitInfo {
2157 CXIndex CIdx;
2158 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002159 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002160 int num_command_line_args;
2161 struct CXUnsavedFile *unsaved_files;
2162 unsigned num_unsaved_files;
2163 unsigned options;
2164 CXTranslationUnit result;
2165};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002166static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002167 ParseTranslationUnitInfo *PTUI =
2168 static_cast<ParseTranslationUnitInfo*>(UserData);
2169 CXIndex CIdx = PTUI->CIdx;
2170 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002171 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002172 int num_command_line_args = PTUI->num_command_line_args;
2173 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2174 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2175 unsigned options = PTUI->options;
2176 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002177
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002178 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002179 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002180
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002181 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2182
Douglas Gregor44c181a2010-07-23 00:33:23 +00002183 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002184 bool CompleteTranslationUnit
2185 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002186 bool CacheCodeCompetionResults
2187 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002188 bool CXXPrecompilePreamble
2189 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2190 bool CXXChainedPCH
2191 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002192
Douglas Gregor5352ac02010-01-28 00:27:43 +00002193 // Configure the diagnostics.
2194 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002195 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2196 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002197
Douglas Gregor4db64a42010-01-23 00:14:00 +00002198 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2199 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002200 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002201 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002202 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002203 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2204 Buffer));
2205 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002206
Douglas Gregorb10daed2010-10-11 16:52:23 +00002207 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002208
Ted Kremenek139ba862009-10-22 00:03:57 +00002209 // The 'source_filename' argument is optional. If the caller does not
2210 // specify it then it is assumed that the source file is specified
2211 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002212 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002213 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002214
2215 // Since the Clang C library is primarily used by batch tools dealing with
2216 // (often very broken) source code, where spell-checking can have a
2217 // significant negative impact on performance (particularly when
2218 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002219 // Only do this if we haven't found a spell-checking-related argument.
2220 bool FoundSpellCheckingArgument = false;
2221 for (int I = 0; I != num_command_line_args; ++I) {
2222 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2223 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2224 FoundSpellCheckingArgument = true;
2225 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002226 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002227 }
2228 if (!FoundSpellCheckingArgument)
2229 Args.push_back("-fno-spell-checking");
2230
2231 Args.insert(Args.end(), command_line_args,
2232 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002233
Douglas Gregor44c181a2010-07-23 00:33:23 +00002234 // Do we need the detailed preprocessing record?
2235 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002236 Args.push_back("-Xclang");
2237 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002238 }
2239
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002240 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002241 llvm::OwningPtr<ASTUnit> Unit(
2242 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2243 Diags,
2244 CXXIdx->getClangResourcesPath(),
2245 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002246 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002247 RemappedFiles.data(),
2248 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002249 PrecompilePreamble,
2250 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002251 CacheCodeCompetionResults,
2252 CXXPrecompilePreamble,
2253 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002254
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002255 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002256 // Make sure to check that 'Unit' is non-NULL.
2257 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2258 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2259 DEnd = Unit->stored_diag_end();
2260 D != DEnd; ++D) {
2261 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2262 CXString Msg = clang_formatDiagnostic(&Diag,
2263 clang_defaultDiagnosticDisplayOptions());
2264 fprintf(stderr, "%s\n", clang_getCString(Msg));
2265 clang_disposeString(Msg);
2266 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002267#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002268 // On Windows, force a flush, since there may be multiple copies of
2269 // stderr and stdout in the file system, all with different buffers
2270 // but writing to the same device.
2271 fflush(stderr);
2272#endif
2273 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002274 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002275
Ted Kremeneka60ed472010-11-16 08:15:36 +00002276 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002277}
2278CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2279 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002280 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002281 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002282 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002283 unsigned num_unsaved_files,
2284 unsigned options) {
2285 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002286 num_command_line_args, unsaved_files,
2287 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002288 llvm::CrashRecoveryContext CRC;
2289
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002290 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002291 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2292 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2293 fprintf(stderr, " 'command_line_args' : [");
2294 for (int i = 0; i != num_command_line_args; ++i) {
2295 if (i)
2296 fprintf(stderr, ", ");
2297 fprintf(stderr, "'%s'", command_line_args[i]);
2298 }
2299 fprintf(stderr, "],\n");
2300 fprintf(stderr, " 'unsaved_files' : [");
2301 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2302 if (i)
2303 fprintf(stderr, ", ");
2304 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2305 unsaved_files[i].Length);
2306 }
2307 fprintf(stderr, "],\n");
2308 fprintf(stderr, " 'options' : %d,\n", options);
2309 fprintf(stderr, "}\n");
2310
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002311 return 0;
2312 }
2313
2314 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002315}
2316
Douglas Gregor19998442010-08-13 15:35:05 +00002317unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2318 return CXSaveTranslationUnit_None;
2319}
2320
2321int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2322 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002323 if (!TU)
2324 return 1;
2325
Ted Kremeneka60ed472010-11-16 08:15:36 +00002326 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002327}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002328
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002329void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002330 if (CTUnit) {
2331 // If the translation unit has been marked as unsafe to free, just discard
2332 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002333 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002334 return;
2335
Ted Kremeneka60ed472010-11-16 08:15:36 +00002336 delete static_cast<ASTUnit *>(CTUnit->TUData);
2337 disposeCXStringPool(CTUnit->StringPool);
2338 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002339 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002340}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002341
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002342unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2343 return CXReparse_None;
2344}
2345
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002346struct ReparseTranslationUnitInfo {
2347 CXTranslationUnit TU;
2348 unsigned num_unsaved_files;
2349 struct CXUnsavedFile *unsaved_files;
2350 unsigned options;
2351 int result;
2352};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002353
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002354static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002355 ReparseTranslationUnitInfo *RTUI =
2356 static_cast<ReparseTranslationUnitInfo*>(UserData);
2357 CXTranslationUnit TU = RTUI->TU;
2358 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2359 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2360 unsigned options = RTUI->options;
2361 (void) options;
2362 RTUI->result = 1;
2363
Douglas Gregorabc563f2010-07-19 21:46:24 +00002364 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002365 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002366
Ted Kremeneka60ed472010-11-16 08:15:36 +00002367 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002368 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002369
2370 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2371 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2372 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2373 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002374 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002375 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2376 Buffer));
2377 }
2378
Douglas Gregor593b0c12010-09-23 18:47:53 +00002379 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2380 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002381}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002382
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002383int clang_reparseTranslationUnit(CXTranslationUnit TU,
2384 unsigned num_unsaved_files,
2385 struct CXUnsavedFile *unsaved_files,
2386 unsigned options) {
2387 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2388 options, 0 };
2389 llvm::CrashRecoveryContext CRC;
2390
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002391 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002392 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002393 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002394 return 1;
2395 }
2396
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002397
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002398 return RTUI.result;
2399}
2400
Douglas Gregordf95a132010-08-09 20:45:32 +00002401
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002402CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002403 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002404 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002405
Ted Kremeneka60ed472010-11-16 08:15:36 +00002406 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002407 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002408}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002409
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002410CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002411 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002412 return Result;
2413}
2414
Ted Kremenekfb480492010-01-13 21:46:36 +00002415} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002416
Ted Kremenekfb480492010-01-13 21:46:36 +00002417//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002418// CXSourceLocation and CXSourceRange Operations.
2419//===----------------------------------------------------------------------===//
2420
Douglas Gregorb9790342010-01-22 21:44:22 +00002421extern "C" {
2422CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002423 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002424 return Result;
2425}
2426
2427unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002428 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2429 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2430 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002431}
2432
2433CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2434 CXFile file,
2435 unsigned line,
2436 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002437 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002438 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002439
Ted Kremeneka60ed472010-11-16 08:15:36 +00002440 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002441 SourceLocation SLoc
2442 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002443 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002444 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002445 if (SLoc.isInvalid()) return clang_getNullLocation();
2446
2447 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2448}
2449
2450CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2451 CXFile file,
2452 unsigned offset) {
2453 if (!tu || !file)
2454 return clang_getNullLocation();
2455
Ted Kremeneka60ed472010-11-16 08:15:36 +00002456 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002457 SourceLocation Start
2458 = CXXUnit->getSourceManager().getLocation(
2459 static_cast<const FileEntry *>(file),
2460 1, 1);
2461 if (Start.isInvalid()) return clang_getNullLocation();
2462
2463 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2464
2465 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002466
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002467 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002468}
2469
Douglas Gregor5352ac02010-01-28 00:27:43 +00002470CXSourceRange clang_getNullRange() {
2471 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2472 return Result;
2473}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002474
Douglas Gregor5352ac02010-01-28 00:27:43 +00002475CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2476 if (begin.ptr_data[0] != end.ptr_data[0] ||
2477 begin.ptr_data[1] != end.ptr_data[1])
2478 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002479
2480 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002481 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002482 return Result;
2483}
2484
Douglas Gregor46766dc2010-01-26 19:19:08 +00002485void clang_getInstantiationLocation(CXSourceLocation location,
2486 CXFile *file,
2487 unsigned *line,
2488 unsigned *column,
2489 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002490 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2491
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002492 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002493 if (file)
2494 *file = 0;
2495 if (line)
2496 *line = 0;
2497 if (column)
2498 *column = 0;
2499 if (offset)
2500 *offset = 0;
2501 return;
2502 }
2503
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002504 const SourceManager &SM =
2505 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002506 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002507
2508 if (file)
2509 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2510 if (line)
2511 *line = SM.getInstantiationLineNumber(InstLoc);
2512 if (column)
2513 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002514 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002515 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002516}
2517
Douglas Gregora9b06d42010-11-09 06:24:54 +00002518void clang_getSpellingLocation(CXSourceLocation location,
2519 CXFile *file,
2520 unsigned *line,
2521 unsigned *column,
2522 unsigned *offset) {
2523 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2524
2525 if (!location.ptr_data[0] || Loc.isInvalid()) {
2526 if (file)
2527 *file = 0;
2528 if (line)
2529 *line = 0;
2530 if (column)
2531 *column = 0;
2532 if (offset)
2533 *offset = 0;
2534 return;
2535 }
2536
2537 const SourceManager &SM =
2538 *static_cast<const SourceManager*>(location.ptr_data[0]);
2539 SourceLocation SpellLoc = Loc;
2540 if (SpellLoc.isMacroID()) {
2541 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2542 if (SimpleSpellingLoc.isFileID() &&
2543 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2544 SpellLoc = SimpleSpellingLoc;
2545 else
2546 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2547 }
2548
2549 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2550 FileID FID = LocInfo.first;
2551 unsigned FileOffset = LocInfo.second;
2552
2553 if (file)
2554 *file = (void *)SM.getFileEntryForID(FID);
2555 if (line)
2556 *line = SM.getLineNumber(FID, FileOffset);
2557 if (column)
2558 *column = SM.getColumnNumber(FID, FileOffset);
2559 if (offset)
2560 *offset = FileOffset;
2561}
2562
Douglas Gregor1db19de2010-01-19 21:36:55 +00002563CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002564 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002565 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002566 return Result;
2567}
2568
2569CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002570 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002571 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002572 return Result;
2573}
2574
Douglas Gregorb9790342010-01-22 21:44:22 +00002575} // end: extern "C"
2576
Douglas Gregor1db19de2010-01-19 21:36:55 +00002577//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002578// CXFile Operations.
2579//===----------------------------------------------------------------------===//
2580
2581extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002582CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002583 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002584 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Steve Naroff88145032009-10-27 14:35:18 +00002586 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002587 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002588}
2589
2590time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002591 if (!SFile)
2592 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002593
Steve Naroff88145032009-10-27 14:35:18 +00002594 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2595 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002596}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002597
Douglas Gregorb9790342010-01-22 21:44:22 +00002598CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2599 if (!tu)
2600 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002601
Ted Kremeneka60ed472010-11-16 08:15:36 +00002602 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002603
Douglas Gregorb9790342010-01-22 21:44:22 +00002604 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002605 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002606}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002607
Ted Kremenekfb480492010-01-13 21:46:36 +00002608} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002609
Ted Kremenekfb480492010-01-13 21:46:36 +00002610//===----------------------------------------------------------------------===//
2611// CXCursor Operations.
2612//===----------------------------------------------------------------------===//
2613
Ted Kremenekfb480492010-01-13 21:46:36 +00002614static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002615 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2616 return getDeclFromExpr(CE->getSubExpr());
2617
Ted Kremenekfb480492010-01-13 21:46:36 +00002618 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2619 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002620 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2621 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002622 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2623 return ME->getMemberDecl();
2624 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2625 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002626 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002627 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002628
Ted Kremenekfb480492010-01-13 21:46:36 +00002629 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2630 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002631 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2632 if (!CE->isElidable())
2633 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002634 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2635 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002636
Douglas Gregordb1314e2010-10-01 21:11:22 +00002637 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2638 return PE->getProtocol();
2639
Ted Kremenekfb480492010-01-13 21:46:36 +00002640 return 0;
2641}
2642
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002643static SourceLocation getLocationFromExpr(Expr *E) {
2644 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2645 return /*FIXME:*/Msg->getLeftLoc();
2646 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2647 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002648 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2649 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002650 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2651 return Member->getMemberLoc();
2652 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2653 return Ivar->getLocation();
2654 return E->getLocStart();
2655}
2656
Ted Kremenekfb480492010-01-13 21:46:36 +00002657extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002658
2659unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002660 CXCursorVisitor visitor,
2661 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002662 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2663 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002664 return CursorVis.VisitChildren(parent);
2665}
2666
David Chisnall3387c652010-11-03 14:12:26 +00002667#ifndef __has_feature
2668#define __has_feature(x) 0
2669#endif
2670#if __has_feature(blocks)
2671typedef enum CXChildVisitResult
2672 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2673
2674static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2675 CXClientData client_data) {
2676 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2677 return block(cursor, parent);
2678}
2679#else
2680// If we are compiled with a compiler that doesn't have native blocks support,
2681// define and call the block manually, so the
2682typedef struct _CXChildVisitResult
2683{
2684 void *isa;
2685 int flags;
2686 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002687 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2688 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002689} *CXCursorVisitorBlock;
2690
2691static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2692 CXClientData client_data) {
2693 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2694 return block->invoke(block, cursor, parent);
2695}
2696#endif
2697
2698
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002699unsigned clang_visitChildrenWithBlock(CXCursor parent,
2700 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002701 return clang_visitChildren(parent, visitWithBlock, block);
2702}
2703
Douglas Gregor78205d42010-01-20 21:45:58 +00002704static CXString getDeclSpelling(Decl *D) {
2705 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002706 if (!ND) {
2707 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2708 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2709 return createCXString(Property->getIdentifier()->getName());
2710
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002711 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002712 }
2713
Douglas Gregor78205d42010-01-20 21:45:58 +00002714 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002715 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002716
Douglas Gregor78205d42010-01-20 21:45:58 +00002717 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2718 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2719 // and returns different names. NamedDecl returns the class name and
2720 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002721 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002722
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002723 if (isa<UsingDirectiveDecl>(D))
2724 return createCXString("");
2725
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002726 llvm::SmallString<1024> S;
2727 llvm::raw_svector_ostream os(S);
2728 ND->printName(os);
2729
2730 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002731}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002732
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002733CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002734 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002735 return clang_getTranslationUnitSpelling(
2736 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002737
Steve Narofff334b4e2009-09-02 18:26:48 +00002738 if (clang_isReference(C.kind)) {
2739 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002740 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002741 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002742 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002743 }
2744 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002745 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002746 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002747 }
2748 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002749 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002750 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002751 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002752 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002753 case CXCursor_CXXBaseSpecifier: {
2754 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2755 return createCXString(B->getType().getAsString());
2756 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002757 case CXCursor_TypeRef: {
2758 TypeDecl *Type = getCursorTypeRef(C).first;
2759 assert(Type && "Missing type decl");
2760
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002761 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2762 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002763 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002764 case CXCursor_TemplateRef: {
2765 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002766 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002767
2768 return createCXString(Template->getNameAsString());
2769 }
Douglas Gregor69319002010-08-31 23:48:11 +00002770
2771 case CXCursor_NamespaceRef: {
2772 NamedDecl *NS = getCursorNamespaceRef(C).first;
2773 assert(NS && "Missing namespace decl");
2774
2775 return createCXString(NS->getNameAsString());
2776 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002777
Douglas Gregora67e03f2010-09-09 21:42:20 +00002778 case CXCursor_MemberRef: {
2779 FieldDecl *Field = getCursorMemberRef(C).first;
2780 assert(Field && "Missing member decl");
2781
2782 return createCXString(Field->getNameAsString());
2783 }
2784
Douglas Gregor36897b02010-09-10 00:22:18 +00002785 case CXCursor_LabelRef: {
2786 LabelStmt *Label = getCursorLabelRef(C).first;
2787 assert(Label && "Missing label");
2788
2789 return createCXString(Label->getID()->getName());
2790 }
2791
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002792 case CXCursor_OverloadedDeclRef: {
2793 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2794 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2795 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2796 return createCXString(ND->getNameAsString());
2797 return createCXString("");
2798 }
2799 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2800 return createCXString(E->getName().getAsString());
2801 OverloadedTemplateStorage *Ovl
2802 = Storage.get<OverloadedTemplateStorage*>();
2803 if (Ovl->size() == 0)
2804 return createCXString("");
2805 return createCXString((*Ovl->begin())->getNameAsString());
2806 }
2807
Daniel Dunbaracca7252009-11-30 20:42:49 +00002808 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002809 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002810 }
2811 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002812
2813 if (clang_isExpression(C.kind)) {
2814 Decl *D = getDeclFromExpr(getCursorExpr(C));
2815 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002816 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002817 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002818 }
2819
Douglas Gregor36897b02010-09-10 00:22:18 +00002820 if (clang_isStatement(C.kind)) {
2821 Stmt *S = getCursorStmt(C);
2822 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2823 return createCXString(Label->getID()->getName());
2824
2825 return createCXString("");
2826 }
2827
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002828 if (C.kind == CXCursor_MacroInstantiation)
2829 return createCXString(getCursorMacroInstantiation(C)->getName()
2830 ->getNameStart());
2831
Douglas Gregor572feb22010-03-18 18:04:21 +00002832 if (C.kind == CXCursor_MacroDefinition)
2833 return createCXString(getCursorMacroDefinition(C)->getName()
2834 ->getNameStart());
2835
Douglas Gregorecdcb882010-10-20 22:00:55 +00002836 if (C.kind == CXCursor_InclusionDirective)
2837 return createCXString(getCursorInclusionDirective(C)->getFileName());
2838
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002839 if (clang_isDeclaration(C.kind))
2840 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002841
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002842 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002843}
2844
Douglas Gregor358559d2010-10-02 22:49:11 +00002845CXString clang_getCursorDisplayName(CXCursor C) {
2846 if (!clang_isDeclaration(C.kind))
2847 return clang_getCursorSpelling(C);
2848
2849 Decl *D = getCursorDecl(C);
2850 if (!D)
2851 return createCXString("");
2852
2853 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2854 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2855 D = FunTmpl->getTemplatedDecl();
2856
2857 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2858 llvm::SmallString<64> Str;
2859 llvm::raw_svector_ostream OS(Str);
2860 OS << Function->getNameAsString();
2861 if (Function->getPrimaryTemplate())
2862 OS << "<>";
2863 OS << "(";
2864 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2865 if (I)
2866 OS << ", ";
2867 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2868 }
2869
2870 if (Function->isVariadic()) {
2871 if (Function->getNumParams())
2872 OS << ", ";
2873 OS << "...";
2874 }
2875 OS << ")";
2876 return createCXString(OS.str());
2877 }
2878
2879 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2880 llvm::SmallString<64> Str;
2881 llvm::raw_svector_ostream OS(Str);
2882 OS << ClassTemplate->getNameAsString();
2883 OS << "<";
2884 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2885 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2886 if (I)
2887 OS << ", ";
2888
2889 NamedDecl *Param = Params->getParam(I);
2890 if (Param->getIdentifier()) {
2891 OS << Param->getIdentifier()->getName();
2892 continue;
2893 }
2894
2895 // There is no parameter name, which makes this tricky. Try to come up
2896 // with something useful that isn't too long.
2897 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2898 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2899 else if (NonTypeTemplateParmDecl *NTTP
2900 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2901 OS << NTTP->getType().getAsString(Policy);
2902 else
2903 OS << "template<...> class";
2904 }
2905
2906 OS << ">";
2907 return createCXString(OS.str());
2908 }
2909
2910 if (ClassTemplateSpecializationDecl *ClassSpec
2911 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2912 // If the type was explicitly written, use that.
2913 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2914 return createCXString(TSInfo->getType().getAsString(Policy));
2915
2916 llvm::SmallString<64> Str;
2917 llvm::raw_svector_ostream OS(Str);
2918 OS << ClassSpec->getNameAsString();
2919 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002920 ClassSpec->getTemplateArgs().data(),
2921 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002922 Policy);
2923 return createCXString(OS.str());
2924 }
2925
2926 return clang_getCursorSpelling(C);
2927}
2928
Ted Kremeneke68fff62010-02-17 00:41:32 +00002929CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002930 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002931 case CXCursor_FunctionDecl:
2932 return createCXString("FunctionDecl");
2933 case CXCursor_TypedefDecl:
2934 return createCXString("TypedefDecl");
2935 case CXCursor_EnumDecl:
2936 return createCXString("EnumDecl");
2937 case CXCursor_EnumConstantDecl:
2938 return createCXString("EnumConstantDecl");
2939 case CXCursor_StructDecl:
2940 return createCXString("StructDecl");
2941 case CXCursor_UnionDecl:
2942 return createCXString("UnionDecl");
2943 case CXCursor_ClassDecl:
2944 return createCXString("ClassDecl");
2945 case CXCursor_FieldDecl:
2946 return createCXString("FieldDecl");
2947 case CXCursor_VarDecl:
2948 return createCXString("VarDecl");
2949 case CXCursor_ParmDecl:
2950 return createCXString("ParmDecl");
2951 case CXCursor_ObjCInterfaceDecl:
2952 return createCXString("ObjCInterfaceDecl");
2953 case CXCursor_ObjCCategoryDecl:
2954 return createCXString("ObjCCategoryDecl");
2955 case CXCursor_ObjCProtocolDecl:
2956 return createCXString("ObjCProtocolDecl");
2957 case CXCursor_ObjCPropertyDecl:
2958 return createCXString("ObjCPropertyDecl");
2959 case CXCursor_ObjCIvarDecl:
2960 return createCXString("ObjCIvarDecl");
2961 case CXCursor_ObjCInstanceMethodDecl:
2962 return createCXString("ObjCInstanceMethodDecl");
2963 case CXCursor_ObjCClassMethodDecl:
2964 return createCXString("ObjCClassMethodDecl");
2965 case CXCursor_ObjCImplementationDecl:
2966 return createCXString("ObjCImplementationDecl");
2967 case CXCursor_ObjCCategoryImplDecl:
2968 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002969 case CXCursor_CXXMethod:
2970 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002971 case CXCursor_UnexposedDecl:
2972 return createCXString("UnexposedDecl");
2973 case CXCursor_ObjCSuperClassRef:
2974 return createCXString("ObjCSuperClassRef");
2975 case CXCursor_ObjCProtocolRef:
2976 return createCXString("ObjCProtocolRef");
2977 case CXCursor_ObjCClassRef:
2978 return createCXString("ObjCClassRef");
2979 case CXCursor_TypeRef:
2980 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002981 case CXCursor_TemplateRef:
2982 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002983 case CXCursor_NamespaceRef:
2984 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002985 case CXCursor_MemberRef:
2986 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002987 case CXCursor_LabelRef:
2988 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002989 case CXCursor_OverloadedDeclRef:
2990 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002991 case CXCursor_UnexposedExpr:
2992 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002993 case CXCursor_BlockExpr:
2994 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002995 case CXCursor_DeclRefExpr:
2996 return createCXString("DeclRefExpr");
2997 case CXCursor_MemberRefExpr:
2998 return createCXString("MemberRefExpr");
2999 case CXCursor_CallExpr:
3000 return createCXString("CallExpr");
3001 case CXCursor_ObjCMessageExpr:
3002 return createCXString("ObjCMessageExpr");
3003 case CXCursor_UnexposedStmt:
3004 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003005 case CXCursor_LabelStmt:
3006 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003007 case CXCursor_InvalidFile:
3008 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003009 case CXCursor_InvalidCode:
3010 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003011 case CXCursor_NoDeclFound:
3012 return createCXString("NoDeclFound");
3013 case CXCursor_NotImplemented:
3014 return createCXString("NotImplemented");
3015 case CXCursor_TranslationUnit:
3016 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003017 case CXCursor_UnexposedAttr:
3018 return createCXString("UnexposedAttr");
3019 case CXCursor_IBActionAttr:
3020 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003021 case CXCursor_IBOutletAttr:
3022 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003023 case CXCursor_IBOutletCollectionAttr:
3024 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003025 case CXCursor_PreprocessingDirective:
3026 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003027 case CXCursor_MacroDefinition:
3028 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003029 case CXCursor_MacroInstantiation:
3030 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003031 case CXCursor_InclusionDirective:
3032 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003033 case CXCursor_Namespace:
3034 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003035 case CXCursor_LinkageSpec:
3036 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003037 case CXCursor_CXXBaseSpecifier:
3038 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003039 case CXCursor_Constructor:
3040 return createCXString("CXXConstructor");
3041 case CXCursor_Destructor:
3042 return createCXString("CXXDestructor");
3043 case CXCursor_ConversionFunction:
3044 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003045 case CXCursor_TemplateTypeParameter:
3046 return createCXString("TemplateTypeParameter");
3047 case CXCursor_NonTypeTemplateParameter:
3048 return createCXString("NonTypeTemplateParameter");
3049 case CXCursor_TemplateTemplateParameter:
3050 return createCXString("TemplateTemplateParameter");
3051 case CXCursor_FunctionTemplate:
3052 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003053 case CXCursor_ClassTemplate:
3054 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003055 case CXCursor_ClassTemplatePartialSpecialization:
3056 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003057 case CXCursor_NamespaceAlias:
3058 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003059 case CXCursor_UsingDirective:
3060 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003061 case CXCursor_UsingDeclaration:
3062 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003063 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003064
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003065 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003066 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003067}
Steve Naroff89922f82009-08-31 00:59:03 +00003068
Ted Kremeneke68fff62010-02-17 00:41:32 +00003069enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3070 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003071 CXClientData client_data) {
3072 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003073
3074 // If our current best cursor is the construction of a temporary object,
3075 // don't replace that cursor with a type reference, because we want
3076 // clang_getCursor() to point at the constructor.
3077 if (clang_isExpression(BestCursor->kind) &&
3078 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3079 cursor.kind == CXCursor_TypeRef)
3080 return CXChildVisit_Recurse;
3081
Douglas Gregor85fe1562010-12-10 07:23:11 +00003082 // Don't override a preprocessing cursor with another preprocessing
3083 // cursor; we want the outermost preprocessing cursor.
3084 if (clang_isPreprocessing(cursor.kind) &&
3085 clang_isPreprocessing(BestCursor->kind))
3086 return CXChildVisit_Recurse;
3087
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003088 *BestCursor = cursor;
3089 return CXChildVisit_Recurse;
3090}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003091
Douglas Gregorb9790342010-01-22 21:44:22 +00003092CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3093 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003094 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003095
Ted Kremeneka60ed472010-11-16 08:15:36 +00003096 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003097 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3098
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003099 // Translate the given source location to make it point at the beginning of
3100 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003101 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003102
3103 // Guard against an invalid SourceLocation, or we may assert in one
3104 // of the following calls.
3105 if (SLoc.isInvalid())
3106 return clang_getNullCursor();
3107
Douglas Gregor40749ee2010-11-03 00:35:38 +00003108 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003109 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3110 CXXUnit->getASTContext().getLangOptions());
3111
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003112 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3113 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003114 // FIXME: Would be great to have a "hint" cursor, then walk from that
3115 // hint cursor upward until we find a cursor whose source range encloses
3116 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003117 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3118 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003119 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003120 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003121 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003122
3123 if (Logging) {
3124 CXFile SearchFile;
3125 unsigned SearchLine, SearchColumn;
3126 CXFile ResultFile;
3127 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003128 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3129 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003130 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3131
3132 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3133 0);
3134 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3135 &ResultColumn, 0);
3136 SearchFileName = clang_getFileName(SearchFile);
3137 ResultFileName = clang_getFileName(ResultFile);
3138 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003139 USR = clang_getCursorUSR(Result);
3140 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003141 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3142 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003143 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3144 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003145 clang_disposeString(SearchFileName);
3146 clang_disposeString(ResultFileName);
3147 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003148 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003149
3150 CXCursor Definition = clang_getCursorDefinition(Result);
3151 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3152 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3153 CXString DefinitionKindSpelling
3154 = clang_getCursorKindSpelling(Definition.kind);
3155 CXFile DefinitionFile;
3156 unsigned DefinitionLine, DefinitionColumn;
3157 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3158 &DefinitionLine, &DefinitionColumn, 0);
3159 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3160 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3161 clang_getCString(DefinitionKindSpelling),
3162 clang_getCString(DefinitionFileName),
3163 DefinitionLine, DefinitionColumn);
3164 clang_disposeString(DefinitionFileName);
3165 clang_disposeString(DefinitionKindSpelling);
3166 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003167 }
3168
Ted Kremeneke68fff62010-02-17 00:41:32 +00003169 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003170}
3171
Ted Kremenek73885552009-11-17 19:28:59 +00003172CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003173 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003174}
3175
3176unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003177 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003178}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003179
Douglas Gregor9ce55842010-11-20 00:09:34 +00003180unsigned clang_hashCursor(CXCursor C) {
3181 unsigned Index = 0;
3182 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3183 Index = 1;
3184
3185 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3186 std::make_pair(C.kind, C.data[Index]));
3187}
3188
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003189unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003190 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3191}
3192
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003193unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003194 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3195}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003196
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003197unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003198 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3199}
3200
Douglas Gregor97b98722010-01-19 23:20:36 +00003201unsigned clang_isExpression(enum CXCursorKind K) {
3202 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3203}
3204
3205unsigned clang_isStatement(enum CXCursorKind K) {
3206 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3207}
3208
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003209unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3210 return K == CXCursor_TranslationUnit;
3211}
3212
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003213unsigned clang_isPreprocessing(enum CXCursorKind K) {
3214 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3215}
3216
Ted Kremenekad6eff62010-03-08 21:17:29 +00003217unsigned clang_isUnexposed(enum CXCursorKind K) {
3218 switch (K) {
3219 case CXCursor_UnexposedDecl:
3220 case CXCursor_UnexposedExpr:
3221 case CXCursor_UnexposedStmt:
3222 case CXCursor_UnexposedAttr:
3223 return true;
3224 default:
3225 return false;
3226 }
3227}
3228
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003229CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003230 return C.kind;
3231}
3232
Douglas Gregor98258af2010-01-18 22:46:11 +00003233CXSourceLocation clang_getCursorLocation(CXCursor C) {
3234 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003235 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003236 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003237 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3238 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003239 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003240 }
3241
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003242 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003243 std::pair<ObjCProtocolDecl *, SourceLocation> P
3244 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003245 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003246 }
3247
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003248 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003249 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3250 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003251 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003252 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003253
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003254 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003255 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003256 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003257 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003258
3259 case CXCursor_TemplateRef: {
3260 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3261 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3262 }
3263
Douglas Gregor69319002010-08-31 23:48:11 +00003264 case CXCursor_NamespaceRef: {
3265 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3266 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3267 }
3268
Douglas Gregora67e03f2010-09-09 21:42:20 +00003269 case CXCursor_MemberRef: {
3270 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3271 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3272 }
3273
Ted Kremenek3064ef92010-08-27 21:34:58 +00003274 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003275 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3276 if (!BaseSpec)
3277 return clang_getNullLocation();
3278
3279 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3280 return cxloc::translateSourceLocation(getCursorContext(C),
3281 TSInfo->getTypeLoc().getBeginLoc());
3282
3283 return cxloc::translateSourceLocation(getCursorContext(C),
3284 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003285 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003286
Douglas Gregor36897b02010-09-10 00:22:18 +00003287 case CXCursor_LabelRef: {
3288 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3289 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3290 }
3291
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003292 case CXCursor_OverloadedDeclRef:
3293 return cxloc::translateSourceLocation(getCursorContext(C),
3294 getCursorOverloadedDeclRef(C).second);
3295
Douglas Gregorf46034a2010-01-18 23:41:10 +00003296 default:
3297 // FIXME: Need a way to enumerate all non-reference cases.
3298 llvm_unreachable("Missed a reference kind");
3299 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003300 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003301
3302 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003303 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003304 getLocationFromExpr(getCursorExpr(C)));
3305
Douglas Gregor36897b02010-09-10 00:22:18 +00003306 if (clang_isStatement(C.kind))
3307 return cxloc::translateSourceLocation(getCursorContext(C),
3308 getCursorStmt(C)->getLocStart());
3309
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003310 if (C.kind == CXCursor_PreprocessingDirective) {
3311 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3312 return cxloc::translateSourceLocation(getCursorContext(C), L);
3313 }
Douglas Gregor48072312010-03-18 15:23:44 +00003314
3315 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003316 SourceLocation L
3317 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003318 return cxloc::translateSourceLocation(getCursorContext(C), L);
3319 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003320
3321 if (C.kind == CXCursor_MacroDefinition) {
3322 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3323 return cxloc::translateSourceLocation(getCursorContext(C), L);
3324 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003325
3326 if (C.kind == CXCursor_InclusionDirective) {
3327 SourceLocation L
3328 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3329 return cxloc::translateSourceLocation(getCursorContext(C), L);
3330 }
3331
Ted Kremenek9a700d22010-05-12 06:16:13 +00003332 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003333 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003334
Douglas Gregorf46034a2010-01-18 23:41:10 +00003335 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003336 SourceLocation Loc = D->getLocation();
3337 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3338 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003339 // FIXME: Multiple variables declared in a single declaration
3340 // currently lack the information needed to correctly determine their
3341 // ranges when accounting for the type-specifier. We use context
3342 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3343 // and if so, whether it is the first decl.
3344 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3345 if (!cxcursor::isFirstInDeclGroup(C))
3346 Loc = VD->getLocation();
3347 }
3348
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003349 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003350}
Douglas Gregora7bde202010-01-19 00:34:46 +00003351
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003352} // end extern "C"
3353
3354static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003355 if (clang_isReference(C.kind)) {
3356 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003357 case CXCursor_ObjCSuperClassRef:
3358 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003359
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003360 case CXCursor_ObjCProtocolRef:
3361 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003362
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003363 case CXCursor_ObjCClassRef:
3364 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003365
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003366 case CXCursor_TypeRef:
3367 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003368
3369 case CXCursor_TemplateRef:
3370 return getCursorTemplateRef(C).second;
3371
Douglas Gregor69319002010-08-31 23:48:11 +00003372 case CXCursor_NamespaceRef:
3373 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003374
3375 case CXCursor_MemberRef:
3376 return getCursorMemberRef(C).second;
3377
Ted Kremenek3064ef92010-08-27 21:34:58 +00003378 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003379 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003380
Douglas Gregor36897b02010-09-10 00:22:18 +00003381 case CXCursor_LabelRef:
3382 return getCursorLabelRef(C).second;
3383
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003384 case CXCursor_OverloadedDeclRef:
3385 return getCursorOverloadedDeclRef(C).second;
3386
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003387 default:
3388 // FIXME: Need a way to enumerate all non-reference cases.
3389 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003390 }
3391 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003392
3393 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003394 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003395
3396 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003397 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003398
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003399 if (C.kind == CXCursor_PreprocessingDirective)
3400 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003401
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003402 if (C.kind == CXCursor_MacroInstantiation)
3403 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003404
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003405 if (C.kind == CXCursor_MacroDefinition)
3406 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003407
3408 if (C.kind == CXCursor_InclusionDirective)
3409 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3410
Ted Kremenek007a7c92010-11-01 23:26:51 +00003411 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3412 Decl *D = cxcursor::getCursorDecl(C);
3413 SourceRange R = D->getSourceRange();
3414 // FIXME: Multiple variables declared in a single declaration
3415 // currently lack the information needed to correctly determine their
3416 // ranges when accounting for the type-specifier. We use context
3417 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3418 // and if so, whether it is the first decl.
3419 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3420 if (!cxcursor::isFirstInDeclGroup(C))
3421 R.setBegin(VD->getLocation());
3422 }
3423 return R;
3424 }
Douglas Gregor66537982010-11-17 17:14:07 +00003425 return SourceRange();
3426}
3427
3428/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3429/// the decl-specifier-seq for declarations.
3430static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3431 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3432 Decl *D = cxcursor::getCursorDecl(C);
3433 SourceRange R = D->getSourceRange();
3434
3435 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3436 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3437 TypeLoc TL = TI->getTypeLoc();
3438 SourceLocation TLoc = TL.getSourceRange().getBegin();
3439 if (TLoc.isValid() && R.getBegin().isValid() &&
3440 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3441 R.setBegin(TLoc);
3442 }
3443
3444 // FIXME: Multiple variables declared in a single declaration
3445 // currently lack the information needed to correctly determine their
3446 // ranges when accounting for the type-specifier. We use context
3447 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3448 // and if so, whether it is the first decl.
3449 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3450 if (!cxcursor::isFirstInDeclGroup(C))
3451 R.setBegin(VD->getLocation());
3452 }
3453 }
3454
3455 return R;
3456 }
3457
3458 return getRawCursorExtent(C);
3459}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003460
3461extern "C" {
3462
3463CXSourceRange clang_getCursorExtent(CXCursor C) {
3464 SourceRange R = getRawCursorExtent(C);
3465 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003466 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003467
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003468 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003469}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003470
3471CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003472 if (clang_isInvalid(C.kind))
3473 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003474
Ted Kremeneka60ed472010-11-16 08:15:36 +00003475 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003476 if (clang_isDeclaration(C.kind)) {
3477 Decl *D = getCursorDecl(C);
3478 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003479 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003480 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003481 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003482 if (ObjCForwardProtocolDecl *Protocols
3483 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003484 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003485 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3486 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3487 return MakeCXCursor(Property, tu);
3488
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003489 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003490 }
3491
Douglas Gregor97b98722010-01-19 23:20:36 +00003492 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003493 Expr *E = getCursorExpr(C);
3494 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003495 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003496 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003497
3498 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003499 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003500
Douglas Gregor97b98722010-01-19 23:20:36 +00003501 return clang_getNullCursor();
3502 }
3503
Douglas Gregor36897b02010-09-10 00:22:18 +00003504 if (clang_isStatement(C.kind)) {
3505 Stmt *S = getCursorStmt(C);
3506 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003507 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003508
3509 return clang_getNullCursor();
3510 }
3511
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003512 if (C.kind == CXCursor_MacroInstantiation) {
3513 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003514 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003515 }
3516
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003517 if (!clang_isReference(C.kind))
3518 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003519
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003520 switch (C.kind) {
3521 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003522 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003523
3524 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003525 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003526
3527 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003528 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003529
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003530 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003531 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003532
3533 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003534 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003535
Douglas Gregor69319002010-08-31 23:48:11 +00003536 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003537 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003538
Douglas Gregora67e03f2010-09-09 21:42:20 +00003539 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003540 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003541
Ted Kremenek3064ef92010-08-27 21:34:58 +00003542 case CXCursor_CXXBaseSpecifier: {
3543 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3544 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003545 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003546 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003547
Douglas Gregor36897b02010-09-10 00:22:18 +00003548 case CXCursor_LabelRef:
3549 // FIXME: We end up faking the "parent" declaration here because we
3550 // don't want to make CXCursor larger.
3551 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003552 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3553 .getTranslationUnitDecl(),
3554 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003555
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003556 case CXCursor_OverloadedDeclRef:
3557 return C;
3558
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003559 default:
3560 // We would prefer to enumerate all non-reference cursor kinds here.
3561 llvm_unreachable("Unhandled reference cursor kind");
3562 break;
3563 }
3564 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003565
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003566 return clang_getNullCursor();
3567}
3568
Douglas Gregorb6998662010-01-19 19:34:47 +00003569CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003570 if (clang_isInvalid(C.kind))
3571 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003572
Ted Kremeneka60ed472010-11-16 08:15:36 +00003573 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003574
Douglas Gregorb6998662010-01-19 19:34:47 +00003575 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003576 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003577 C = clang_getCursorReferenced(C);
3578 WasReference = true;
3579 }
3580
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003581 if (C.kind == CXCursor_MacroInstantiation)
3582 return clang_getCursorReferenced(C);
3583
Douglas Gregorb6998662010-01-19 19:34:47 +00003584 if (!clang_isDeclaration(C.kind))
3585 return clang_getNullCursor();
3586
3587 Decl *D = getCursorDecl(C);
3588 if (!D)
3589 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003590
Douglas Gregorb6998662010-01-19 19:34:47 +00003591 switch (D->getKind()) {
3592 // Declaration kinds that don't really separate the notions of
3593 // declaration and definition.
3594 case Decl::Namespace:
3595 case Decl::Typedef:
3596 case Decl::TemplateTypeParm:
3597 case Decl::EnumConstant:
3598 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003599 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003600 case Decl::ObjCIvar:
3601 case Decl::ObjCAtDefsField:
3602 case Decl::ImplicitParam:
3603 case Decl::ParmVar:
3604 case Decl::NonTypeTemplateParm:
3605 case Decl::TemplateTemplateParm:
3606 case Decl::ObjCCategoryImpl:
3607 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003608 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003609 case Decl::LinkageSpec:
3610 case Decl::ObjCPropertyImpl:
3611 case Decl::FileScopeAsm:
3612 case Decl::StaticAssert:
3613 case Decl::Block:
3614 return C;
3615
3616 // Declaration kinds that don't make any sense here, but are
3617 // nonetheless harmless.
3618 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003619 break;
3620
3621 // Declaration kinds for which the definition is not resolvable.
3622 case Decl::UnresolvedUsingTypename:
3623 case Decl::UnresolvedUsingValue:
3624 break;
3625
3626 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003627 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003628 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003629
3630 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003631 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003632
3633 case Decl::Enum:
3634 case Decl::Record:
3635 case Decl::CXXRecord:
3636 case Decl::ClassTemplateSpecialization:
3637 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003638 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003639 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003640 return clang_getNullCursor();
3641
3642 case Decl::Function:
3643 case Decl::CXXMethod:
3644 case Decl::CXXConstructor:
3645 case Decl::CXXDestructor:
3646 case Decl::CXXConversion: {
3647 const FunctionDecl *Def = 0;
3648 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003649 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003650 return clang_getNullCursor();
3651 }
3652
3653 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003654 // Ask the variable if it has a definition.
3655 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003656 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003657 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003658 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003659
Douglas Gregorb6998662010-01-19 19:34:47 +00003660 case Decl::FunctionTemplate: {
3661 const FunctionDecl *Def = 0;
3662 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003663 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003664 return clang_getNullCursor();
3665 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003666
Douglas Gregorb6998662010-01-19 19:34:47 +00003667 case Decl::ClassTemplate: {
3668 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003669 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003670 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003671 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003672 return clang_getNullCursor();
3673 }
3674
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003675 case Decl::Using:
3676 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003677 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003678
3679 case Decl::UsingShadow:
3680 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003681 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003682 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003683
3684 case Decl::ObjCMethod: {
3685 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3686 if (Method->isThisDeclarationADefinition())
3687 return C;
3688
3689 // Dig out the method definition in the associated
3690 // @implementation, if we have it.
3691 // FIXME: The ASTs should make finding the definition easier.
3692 if (ObjCInterfaceDecl *Class
3693 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3694 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3695 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3696 Method->isInstanceMethod()))
3697 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003698 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003699
3700 return clang_getNullCursor();
3701 }
3702
3703 case Decl::ObjCCategory:
3704 if (ObjCCategoryImplDecl *Impl
3705 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003706 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003707 return clang_getNullCursor();
3708
3709 case Decl::ObjCProtocol:
3710 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3711 return C;
3712 return clang_getNullCursor();
3713
3714 case Decl::ObjCInterface:
3715 // There are two notions of a "definition" for an Objective-C
3716 // class: the interface and its implementation. When we resolved a
3717 // reference to an Objective-C class, produce the @interface as
3718 // the definition; when we were provided with the interface,
3719 // produce the @implementation as the definition.
3720 if (WasReference) {
3721 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3722 return C;
3723 } else if (ObjCImplementationDecl *Impl
3724 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003725 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003726 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003727
Douglas Gregorb6998662010-01-19 19:34:47 +00003728 case Decl::ObjCProperty:
3729 // FIXME: We don't really know where to find the
3730 // ObjCPropertyImplDecls that implement this property.
3731 return clang_getNullCursor();
3732
3733 case Decl::ObjCCompatibleAlias:
3734 if (ObjCInterfaceDecl *Class
3735 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3736 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003737 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003738
Douglas Gregorb6998662010-01-19 19:34:47 +00003739 return clang_getNullCursor();
3740
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003741 case Decl::ObjCForwardProtocol:
3742 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003743 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003744
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003745 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003746 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003747 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003748
3749 case Decl::Friend:
3750 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003751 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003752 return clang_getNullCursor();
3753
3754 case Decl::FriendTemplate:
3755 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003756 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003757 return clang_getNullCursor();
3758 }
3759
3760 return clang_getNullCursor();
3761}
3762
3763unsigned clang_isCursorDefinition(CXCursor C) {
3764 if (!clang_isDeclaration(C.kind))
3765 return 0;
3766
3767 return clang_getCursorDefinition(C) == C;
3768}
3769
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003770CXCursor clang_getCanonicalCursor(CXCursor C) {
3771 if (!clang_isDeclaration(C.kind))
3772 return C;
3773
3774 if (Decl *D = getCursorDecl(C))
3775 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3776
3777 return C;
3778}
3779
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003780unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003781 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003782 return 0;
3783
3784 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3785 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3786 return E->getNumDecls();
3787
3788 if (OverloadedTemplateStorage *S
3789 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3790 return S->size();
3791
3792 Decl *D = Storage.get<Decl*>();
3793 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003794 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003795 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3796 return Classes->size();
3797 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3798 return Protocols->protocol_size();
3799
3800 return 0;
3801}
3802
3803CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003804 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003805 return clang_getNullCursor();
3806
3807 if (index >= clang_getNumOverloadedDecls(cursor))
3808 return clang_getNullCursor();
3809
Ted Kremeneka60ed472010-11-16 08:15:36 +00003810 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003811 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3812 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003813 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003814
3815 if (OverloadedTemplateStorage *S
3816 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003817 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003818
3819 Decl *D = Storage.get<Decl*>();
3820 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3821 // FIXME: This is, unfortunately, linear time.
3822 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3823 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003824 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003825 }
3826
3827 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003828 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003829
3830 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003831 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003832
3833 return clang_getNullCursor();
3834}
3835
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003836void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003837 const char **startBuf,
3838 const char **endBuf,
3839 unsigned *startLine,
3840 unsigned *startColumn,
3841 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003842 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003843 assert(getCursorDecl(C) && "CXCursor has null decl");
3844 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003845 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3846 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
Steve Naroff4ade6d62009-09-23 17:52:52 +00003848 SourceManager &SM = FD->getASTContext().getSourceManager();
3849 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3850 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3851 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3852 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3853 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3854 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3855}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003856
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003857void clang_enableStackTraces(void) {
3858 llvm::sys::PrintStackTraceOnErrorSignal();
3859}
3860
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003861void clang_executeOnThread(void (*fn)(void*), void *user_data,
3862 unsigned stack_size) {
3863 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3864}
3865
Ted Kremenekfb480492010-01-13 21:46:36 +00003866} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003867
Ted Kremenekfb480492010-01-13 21:46:36 +00003868//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003869// Token-based Operations.
3870//===----------------------------------------------------------------------===//
3871
3872/* CXToken layout:
3873 * int_data[0]: a CXTokenKind
3874 * int_data[1]: starting token location
3875 * int_data[2]: token length
3876 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003877 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 * otherwise unused.
3879 */
3880extern "C" {
3881
3882CXTokenKind clang_getTokenKind(CXToken CXTok) {
3883 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3884}
3885
3886CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3887 switch (clang_getTokenKind(CXTok)) {
3888 case CXToken_Identifier:
3889 case CXToken_Keyword:
3890 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003891 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3892 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893
3894 case CXToken_Literal: {
3895 // We have stashed the starting pointer in the ptr_data field. Use it.
3896 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003897 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003898 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003899
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003900 case CXToken_Punctuation:
3901 case CXToken_Comment:
3902 break;
3903 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003904
3905 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003906 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003907 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003908 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003909 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003910
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003911 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3912 std::pair<FileID, unsigned> LocInfo
3913 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003914 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003915 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003916 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3917 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003918 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003919
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003920 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003921}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003922
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003923CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003924 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003925 if (!CXXUnit)
3926 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003927
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003928 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3929 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3930}
3931
3932CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003933 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003934 if (!CXXUnit)
3935 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003936
3937 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003938 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3939}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003940
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003941void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3942 CXToken **Tokens, unsigned *NumTokens) {
3943 if (Tokens)
3944 *Tokens = 0;
3945 if (NumTokens)
3946 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003947
Ted Kremeneka60ed472010-11-16 08:15:36 +00003948 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003949 if (!CXXUnit || !Tokens || !NumTokens)
3950 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003951
Douglas Gregorbdf60622010-03-05 21:16:25 +00003952 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3953
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003954 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003955 if (R.isInvalid())
3956 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003957
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003958 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3959 std::pair<FileID, unsigned> BeginLocInfo
3960 = SourceMgr.getDecomposedLoc(R.getBegin());
3961 std::pair<FileID, unsigned> EndLocInfo
3962 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003963
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003964 // Cannot tokenize across files.
3965 if (BeginLocInfo.first != EndLocInfo.first)
3966 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003967
3968 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003969 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003970 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003971 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003972 if (Invalid)
3973 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003974
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003975 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3976 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003977 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003978 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003979
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003980 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003981 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003982 llvm::SmallVector<CXToken, 32> CXTokens;
3983 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003984 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003985 do {
3986 // Lex the next token
3987 Lex.LexFromRawLexer(Tok);
3988 if (Tok.is(tok::eof))
3989 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003990
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003991 // Initialize the CXToken.
3992 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003993
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003994 // - Common fields
3995 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3996 CXTok.int_data[2] = Tok.getLength();
3997 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003998
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003999 // - Kind-specific fields
4000 if (Tok.isLiteral()) {
4001 CXTok.int_data[0] = CXToken_Literal;
4002 CXTok.ptr_data = (void *)Tok.getLiteralData();
4003 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004004 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004005 std::pair<FileID, unsigned> LocInfo
4006 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00004007 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004008 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00004009 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4010 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004011 return;
4012
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004013 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004014 IdentifierInfo *II
4015 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004016
David Chisnall096428b2010-10-13 21:44:48 +00004017 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004018 CXTok.int_data[0] = CXToken_Keyword;
4019 }
4020 else {
4021 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
4022 CXToken_Identifier
4023 : CXToken_Keyword;
4024 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004025 CXTok.ptr_data = II;
4026 } else if (Tok.is(tok::comment)) {
4027 CXTok.int_data[0] = CXToken_Comment;
4028 CXTok.ptr_data = 0;
4029 } else {
4030 CXTok.int_data[0] = CXToken_Punctuation;
4031 CXTok.ptr_data = 0;
4032 }
4033 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004034 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004035 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004036
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004037 if (CXTokens.empty())
4038 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004039
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004040 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4041 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4042 *NumTokens = CXTokens.size();
4043}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004044
Ted Kremenek6db61092010-05-05 00:55:15 +00004045void clang_disposeTokens(CXTranslationUnit TU,
4046 CXToken *Tokens, unsigned NumTokens) {
4047 free(Tokens);
4048}
4049
4050} // end: extern "C"
4051
4052//===----------------------------------------------------------------------===//
4053// Token annotation APIs.
4054//===----------------------------------------------------------------------===//
4055
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004056typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004057static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4058 CXCursor parent,
4059 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004060namespace {
4061class AnnotateTokensWorker {
4062 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004063 CXToken *Tokens;
4064 CXCursor *Cursors;
4065 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004066 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004067 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004068 CursorVisitor AnnotateVis;
4069 SourceManager &SrcMgr;
4070
4071 bool MoreTokens() const { return TokIdx < NumTokens; }
4072 unsigned NextToken() const { return TokIdx; }
4073 void AdvanceToken() { ++TokIdx; }
4074 SourceLocation GetTokenLoc(unsigned tokI) {
4075 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4076 }
4077
Ted Kremenek6db61092010-05-05 00:55:15 +00004078public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004079 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004080 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004081 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004082 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004083 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004084 AnnotateVis(tu,
4085 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004086 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004087 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004088
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004089 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004090 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004091 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004092 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004093 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004094 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004095};
4096}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004097
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004098void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4099 // Walk the AST within the region of interest, annotating tokens
4100 // along the way.
4101 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004102
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004103 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4104 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004105 if (Pos != Annotated.end() &&
4106 (clang_isInvalid(Cursors[I].kind) ||
4107 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004108 Cursors[I] = Pos->second;
4109 }
4110
4111 // Finish up annotating any tokens left.
4112 if (!MoreTokens())
4113 return;
4114
4115 const CXCursor &C = clang_getNullCursor();
4116 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4117 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4118 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004119 }
4120}
4121
Ted Kremenek6db61092010-05-05 00:55:15 +00004122enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004123AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004124 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004125 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004126 if (cursorRange.isInvalid())
4127 return CXChildVisit_Recurse;
4128
Douglas Gregor4419b672010-10-21 06:10:04 +00004129 if (clang_isPreprocessing(cursor.kind)) {
4130 // For macro instantiations, just note where the beginning of the macro
4131 // instantiation occurs.
4132 if (cursor.kind == CXCursor_MacroInstantiation) {
4133 Annotated[Loc.int_data] = cursor;
4134 return CXChildVisit_Recurse;
4135 }
4136
Douglas Gregor4419b672010-10-21 06:10:04 +00004137 // Items in the preprocessing record are kept separate from items in
4138 // declarations, so we keep a separate token index.
4139 unsigned SavedTokIdx = TokIdx;
4140 TokIdx = PreprocessingTokIdx;
4141
4142 // Skip tokens up until we catch up to the beginning of the preprocessing
4143 // entry.
4144 while (MoreTokens()) {
4145 const unsigned I = NextToken();
4146 SourceLocation TokLoc = GetTokenLoc(I);
4147 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4148 case RangeBefore:
4149 AdvanceToken();
4150 continue;
4151 case RangeAfter:
4152 case RangeOverlap:
4153 break;
4154 }
4155 break;
4156 }
4157
4158 // Look at all of the tokens within this range.
4159 while (MoreTokens()) {
4160 const unsigned I = NextToken();
4161 SourceLocation TokLoc = GetTokenLoc(I);
4162 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4163 case RangeBefore:
4164 assert(0 && "Infeasible");
4165 case RangeAfter:
4166 break;
4167 case RangeOverlap:
4168 Cursors[I] = cursor;
4169 AdvanceToken();
4170 continue;
4171 }
4172 break;
4173 }
4174
4175 // Save the preprocessing token index; restore the non-preprocessing
4176 // token index.
4177 PreprocessingTokIdx = TokIdx;
4178 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004179 return CXChildVisit_Recurse;
4180 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004181
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004182 if (cursorRange.isInvalid())
4183 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004184
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004185 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4186
Ted Kremeneka333c662010-05-12 05:29:33 +00004187 // Adjust the annotated range based specific declarations.
4188 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4189 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004190 Decl *D = cxcursor::getCursorDecl(cursor);
4191 // Don't visit synthesized ObjC methods, since they have no syntatic
4192 // representation in the source.
4193 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4194 if (MD->isSynthesized())
4195 return CXChildVisit_Continue;
4196 }
4197 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004198 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4199 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004200 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004201 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004202 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004203 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004204 }
4205 }
4206 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004207
Ted Kremenek3f404602010-08-14 01:14:06 +00004208 // If the location of the cursor occurs within a macro instantiation, record
4209 // the spelling location of the cursor in our annotation map. We can then
4210 // paper over the token labelings during a post-processing step to try and
4211 // get cursor mappings for tokens that are the *arguments* of a macro
4212 // instantiation.
4213 if (L.isMacroID()) {
4214 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4215 // Only invalidate the old annotation if it isn't part of a preprocessing
4216 // directive. Here we assume that the default construction of CXCursor
4217 // results in CXCursor.kind being an initialized value (i.e., 0). If
4218 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004219
Ted Kremenek3f404602010-08-14 01:14:06 +00004220 CXCursor &oldC = Annotated[rawEncoding];
4221 if (!clang_isPreprocessing(oldC.kind))
4222 oldC = cursor;
4223 }
4224
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004225 const enum CXCursorKind K = clang_getCursorKind(parent);
4226 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004227 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4228 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229
4230 while (MoreTokens()) {
4231 const unsigned I = NextToken();
4232 SourceLocation TokLoc = GetTokenLoc(I);
4233 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4234 case RangeBefore:
4235 Cursors[I] = updateC;
4236 AdvanceToken();
4237 continue;
4238 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239 case RangeOverlap:
4240 break;
4241 }
4242 break;
4243 }
4244
4245 // Visit children to get their cursor information.
4246 const unsigned BeforeChildren = NextToken();
4247 VisitChildren(cursor);
4248 const unsigned AfterChildren = NextToken();
4249
4250 // Adjust 'Last' to the last token within the extent of the cursor.
4251 while (MoreTokens()) {
4252 const unsigned I = NextToken();
4253 SourceLocation TokLoc = GetTokenLoc(I);
4254 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4255 case RangeBefore:
4256 assert(0 && "Infeasible");
4257 case RangeAfter:
4258 break;
4259 case RangeOverlap:
4260 Cursors[I] = updateC;
4261 AdvanceToken();
4262 continue;
4263 }
4264 break;
4265 }
4266 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004267
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004268 // Scan the tokens that are at the beginning of the cursor, but are not
4269 // capture by the child cursors.
4270
4271 // For AST elements within macros, rely on a post-annotate pass to
4272 // to correctly annotate the tokens with cursors. Otherwise we can
4273 // get confusing results of having tokens that map to cursors that really
4274 // are expanded by an instantiation.
4275 if (L.isMacroID())
4276 cursor = clang_getNullCursor();
4277
4278 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4279 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4280 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004281
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004282 Cursors[I] = cursor;
4283 }
4284 // Scan the tokens that are at the end of the cursor, but are not captured
4285 // but the child cursors.
4286 for (unsigned I = AfterChildren; I != Last; ++I)
4287 Cursors[I] = cursor;
4288
4289 TokIdx = Last;
4290 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004291}
4292
Ted Kremenek6db61092010-05-05 00:55:15 +00004293static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4294 CXCursor parent,
4295 CXClientData client_data) {
4296 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4297}
4298
Ted Kremenekab979612010-11-11 08:05:23 +00004299// This gets run a separate thread to avoid stack blowout.
4300static void runAnnotateTokensWorker(void *UserData) {
4301 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4302}
4303
Ted Kremenek6db61092010-05-05 00:55:15 +00004304extern "C" {
4305
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004306void clang_annotateTokens(CXTranslationUnit TU,
4307 CXToken *Tokens, unsigned NumTokens,
4308 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004309
4310 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004311 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004312
Douglas Gregor4419b672010-10-21 06:10:04 +00004313 // Any token we don't specifically annotate will have a NULL cursor.
4314 CXCursor C = clang_getNullCursor();
4315 for (unsigned I = 0; I != NumTokens; ++I)
4316 Cursors[I] = C;
4317
Ted Kremeneka60ed472010-11-16 08:15:36 +00004318 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004319 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004320 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004321
Douglas Gregorbdf60622010-03-05 21:16:25 +00004322 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004323
Douglas Gregor0396f462010-03-19 05:22:59 +00004324 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004325 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004326 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4327 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004328 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4329 clang_getTokenLocation(TU,
4330 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004331
Douglas Gregor0396f462010-03-19 05:22:59 +00004332 // A mapping from the source locations found when re-lexing or traversing the
4333 // region of interest to the corresponding cursors.
4334 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004335
4336 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004337 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004338 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4339 std::pair<FileID, unsigned> BeginLocInfo
4340 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4341 std::pair<FileID, unsigned> EndLocInfo
4342 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004343
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004344 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004345 bool Invalid = false;
4346 if (BeginLocInfo.first == EndLocInfo.first &&
4347 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4348 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004349 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4350 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004351 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004352 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004353 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004354
4355 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004356 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004357 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004358 Token Tok;
4359 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004360
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004361 reprocess:
4362 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4363 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004364 // don't see it while preprocessing these tokens later, but keep track
4365 // of all of the token locations inside this preprocessing directive so
4366 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004367 //
4368 // FIXME: Some simple tests here could identify macro definitions and
4369 // #undefs, to provide specific cursor kinds for those.
4370 std::vector<SourceLocation> Locations;
4371 do {
4372 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004373 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004374 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004375
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004376 using namespace cxcursor;
4377 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004378 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4379 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004380 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004381 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4382 Annotated[Locations[I].getRawEncoding()] = Cursor;
4383 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004384
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004385 if (Tok.isAtStartOfLine())
4386 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004387
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004388 continue;
4389 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004390
Douglas Gregor48072312010-03-18 15:23:44 +00004391 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004392 break;
4393 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004394 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004395
Douglas Gregor0396f462010-03-19 05:22:59 +00004396 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004397 // a specific cursor.
4398 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004399 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004400
4401 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004402 // FIXME: We use a ridiculous stack size here because the data-recursion
4403 // algorithm uses a large stack frame than the non-data recursive version,
4404 // and AnnotationTokensWorker currently transforms the data-recursion
4405 // algorithm back into a traditional recursion by explicitly calling
4406 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004407 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004408 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4409 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004410 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4411 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004412}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004413} // end: extern "C"
4414
4415//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004416// Operations for querying linkage of a cursor.
4417//===----------------------------------------------------------------------===//
4418
4419extern "C" {
4420CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004421 if (!clang_isDeclaration(cursor.kind))
4422 return CXLinkage_Invalid;
4423
Ted Kremenek16b42592010-03-03 06:36:57 +00004424 Decl *D = cxcursor::getCursorDecl(cursor);
4425 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4426 switch (ND->getLinkage()) {
4427 case NoLinkage: return CXLinkage_NoLinkage;
4428 case InternalLinkage: return CXLinkage_Internal;
4429 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4430 case ExternalLinkage: return CXLinkage_External;
4431 };
4432
4433 return CXLinkage_Invalid;
4434}
4435} // end: extern "C"
4436
4437//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004438// Operations for querying language of a cursor.
4439//===----------------------------------------------------------------------===//
4440
4441static CXLanguageKind getDeclLanguage(const Decl *D) {
4442 switch (D->getKind()) {
4443 default:
4444 break;
4445 case Decl::ImplicitParam:
4446 case Decl::ObjCAtDefsField:
4447 case Decl::ObjCCategory:
4448 case Decl::ObjCCategoryImpl:
4449 case Decl::ObjCClass:
4450 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004451 case Decl::ObjCForwardProtocol:
4452 case Decl::ObjCImplementation:
4453 case Decl::ObjCInterface:
4454 case Decl::ObjCIvar:
4455 case Decl::ObjCMethod:
4456 case Decl::ObjCProperty:
4457 case Decl::ObjCPropertyImpl:
4458 case Decl::ObjCProtocol:
4459 return CXLanguage_ObjC;
4460 case Decl::CXXConstructor:
4461 case Decl::CXXConversion:
4462 case Decl::CXXDestructor:
4463 case Decl::CXXMethod:
4464 case Decl::CXXRecord:
4465 case Decl::ClassTemplate:
4466 case Decl::ClassTemplatePartialSpecialization:
4467 case Decl::ClassTemplateSpecialization:
4468 case Decl::Friend:
4469 case Decl::FriendTemplate:
4470 case Decl::FunctionTemplate:
4471 case Decl::LinkageSpec:
4472 case Decl::Namespace:
4473 case Decl::NamespaceAlias:
4474 case Decl::NonTypeTemplateParm:
4475 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004476 case Decl::TemplateTemplateParm:
4477 case Decl::TemplateTypeParm:
4478 case Decl::UnresolvedUsingTypename:
4479 case Decl::UnresolvedUsingValue:
4480 case Decl::Using:
4481 case Decl::UsingDirective:
4482 case Decl::UsingShadow:
4483 return CXLanguage_CPlusPlus;
4484 }
4485
4486 return CXLanguage_C;
4487}
4488
4489extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004490
4491enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4492 if (clang_isDeclaration(cursor.kind))
4493 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4494 if (D->hasAttr<UnavailableAttr>() ||
4495 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4496 return CXAvailability_Available;
4497
4498 if (D->hasAttr<DeprecatedAttr>())
4499 return CXAvailability_Deprecated;
4500 }
4501
4502 return CXAvailability_Available;
4503}
4504
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004505CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4506 if (clang_isDeclaration(cursor.kind))
4507 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4508
4509 return CXLanguage_Invalid;
4510}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004511
4512CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4513 if (clang_isDeclaration(cursor.kind)) {
4514 if (Decl *D = getCursorDecl(cursor)) {
4515 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004516 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004517 }
4518 }
4519
4520 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4521 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004522 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004523 }
4524
4525 return clang_getNullCursor();
4526}
4527
4528CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4529 if (clang_isDeclaration(cursor.kind)) {
4530 if (Decl *D = getCursorDecl(cursor)) {
4531 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004532 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004533 }
4534 }
4535
4536 // FIXME: Note that we can't easily compute the lexical context of a
4537 // statement or expression, so we return nothing.
4538 return clang_getNullCursor();
4539}
4540
Douglas Gregor9f592342010-10-01 20:25:15 +00004541static void CollectOverriddenMethods(DeclContext *Ctx,
4542 ObjCMethodDecl *Method,
4543 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4544 if (!Ctx)
4545 return;
4546
4547 // If we have a class or category implementation, jump straight to the
4548 // interface.
4549 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4550 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4551
4552 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4553 if (!Container)
4554 return;
4555
4556 // Check whether we have a matching method at this level.
4557 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4558 Method->isInstanceMethod()))
4559 if (Method != Overridden) {
4560 // We found an override at this level; there is no need to look
4561 // into other protocols or categories.
4562 Methods.push_back(Overridden);
4563 return;
4564 }
4565
4566 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4567 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4568 PEnd = Protocol->protocol_end();
4569 P != PEnd; ++P)
4570 CollectOverriddenMethods(*P, Method, Methods);
4571 }
4572
4573 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4574 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4575 PEnd = Category->protocol_end();
4576 P != PEnd; ++P)
4577 CollectOverriddenMethods(*P, Method, Methods);
4578 }
4579
4580 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4581 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4582 PEnd = Interface->protocol_end();
4583 P != PEnd; ++P)
4584 CollectOverriddenMethods(*P, Method, Methods);
4585
4586 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4587 Category; Category = Category->getNextClassCategory())
4588 CollectOverriddenMethods(Category, Method, Methods);
4589
4590 // We only look into the superclass if we haven't found anything yet.
4591 if (Methods.empty())
4592 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4593 return CollectOverriddenMethods(Super, Method, Methods);
4594 }
4595}
4596
4597void clang_getOverriddenCursors(CXCursor cursor,
4598 CXCursor **overridden,
4599 unsigned *num_overridden) {
4600 if (overridden)
4601 *overridden = 0;
4602 if (num_overridden)
4603 *num_overridden = 0;
4604 if (!overridden || !num_overridden)
4605 return;
4606
4607 if (!clang_isDeclaration(cursor.kind))
4608 return;
4609
4610 Decl *D = getCursorDecl(cursor);
4611 if (!D)
4612 return;
4613
4614 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004615 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004616 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4617 *num_overridden = CXXMethod->size_overridden_methods();
4618 if (!*num_overridden)
4619 return;
4620
4621 *overridden = new CXCursor [*num_overridden];
4622 unsigned I = 0;
4623 for (CXXMethodDecl::method_iterator
4624 M = CXXMethod->begin_overridden_methods(),
4625 MEnd = CXXMethod->end_overridden_methods();
4626 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004627 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004628 return;
4629 }
4630
4631 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4632 if (!Method)
4633 return;
4634
4635 // Handle Objective-C methods.
4636 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4637 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4638
4639 if (Methods.empty())
4640 return;
4641
4642 *num_overridden = Methods.size();
4643 *overridden = new CXCursor [Methods.size()];
4644 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004645 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004646}
4647
4648void clang_disposeOverriddenCursors(CXCursor *overridden) {
4649 delete [] overridden;
4650}
4651
Douglas Gregorecdcb882010-10-20 22:00:55 +00004652CXFile clang_getIncludedFile(CXCursor cursor) {
4653 if (cursor.kind != CXCursor_InclusionDirective)
4654 return 0;
4655
4656 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4657 return (void *)ID->getFile();
4658}
4659
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004660} // end: extern "C"
4661
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004662
4663//===----------------------------------------------------------------------===//
4664// C++ AST instrospection.
4665//===----------------------------------------------------------------------===//
4666
4667extern "C" {
4668unsigned clang_CXXMethod_isStatic(CXCursor C) {
4669 if (!clang_isDeclaration(C.kind))
4670 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004671
4672 CXXMethodDecl *Method = 0;
4673 Decl *D = cxcursor::getCursorDecl(C);
4674 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4675 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4676 else
4677 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4678 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004679}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004680
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004681} // end: extern "C"
4682
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004683//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004684// Attribute introspection.
4685//===----------------------------------------------------------------------===//
4686
4687extern "C" {
4688CXType clang_getIBOutletCollectionType(CXCursor C) {
4689 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004690 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004691
4692 IBOutletCollectionAttr *A =
4693 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4694
Ted Kremeneka60ed472010-11-16 08:15:36 +00004695 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004696}
4697} // end: extern "C"
4698
4699//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004700// Misc. utility functions.
4701//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004702
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004703/// Default to using an 8 MB stack size on "safety" threads.
4704static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004705
4706namespace clang {
4707
4708bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004709 void (*Fn)(void*), void *UserData,
4710 unsigned Size) {
4711 if (!Size)
4712 Size = GetSafetyThreadStackSize();
4713 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004714 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4715 return CRC.RunSafely(Fn, UserData);
4716}
4717
4718unsigned GetSafetyThreadStackSize() {
4719 return SafetyStackThreadSize;
4720}
4721
4722void SetSafetyThreadStackSize(unsigned Value) {
4723 SafetyStackThreadSize = Value;
4724}
4725
4726}
4727
Ted Kremenek04bb7162010-01-22 22:44:15 +00004728extern "C" {
4729
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004730CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004731 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004732}
4733
4734} // end: extern "C"