blob: eecaafabdc3166ed89c339060f56fa681dd7f248 [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 Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
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
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000126
127class VisitorJob {
128public:
129 enum Kind { StmtVisitKind, MemberExprPartsKind };
130protected:
131 void *data;
132 CXCursor parent;
133 Kind K;
134 VisitorJob(void *d, CXCursor C, Kind k) : data(d), parent(C), K(k) {}
135public:
136 Kind getKind() const { return K; }
137 const CXCursor &getParent() const { return parent; }
138 static bool classof(VisitorJob *VJ) { return true; }
139};
140
141typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
142
143#define DEF_JOB(NAME, DATA, KIND)\
144class NAME : public VisitorJob {\
145public:\
146 NAME(DATA *d, CXCursor parent) : VisitorJob(d, parent, VisitorJob::KIND) {}\
147 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
148 DATA *get() const { return static_cast<DATA*>(data); }\
149};
150
151DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
152DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
153
154#undef DEF_JOB
155
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000156
Douglas Gregorb1373d02010-01-20 20:59:29 +0000157// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000158class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000159 public TypeLocVisitor<CursorVisitor, bool>,
160 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000161{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000162 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000163 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000167
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 /// \brief The declaration that serves at the parent of any statement or
169 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000170 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000171
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000176 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000178 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
179 // to the visitor. Declarations with a PCH level greater than this value will
180 // be suppressed.
181 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182
183 /// \brief When valid, a source range to which the cursor should restrict
184 /// its search.
185 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000186
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000187 // FIXME: Eventually remove. This part of a hack to support proper
188 // iteration over all Decls contained lexically within an ObjC container.
189 DeclContext::decl_iterator *DI_current;
190 DeclContext::decl_iterator DE_current;
191
Douglas Gregorb1373d02010-01-20 20:59:29 +0000192 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000193 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000194 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000195
196 /// \brief Determine whether this particular source range comes before, comes
197 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000198 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000199 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000200 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
201
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000202 class SetParentRAII {
203 CXCursor &Parent;
204 Decl *&StmtParent;
205 CXCursor OldParent;
206
207 public:
208 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
209 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
210 {
211 Parent = NewParent;
212 if (clang_isDeclaration(Parent.kind))
213 StmtParent = getCursorDecl(Parent);
214 }
215
216 ~SetParentRAII() {
217 Parent = OldParent;
218 if (clang_isDeclaration(Parent.kind))
219 StmtParent = getCursorDecl(Parent);
220 }
221 };
222
Steve Naroff89922f82009-08-31 00:59:03 +0000223public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000224 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
225 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000226 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000227 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000228 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
229 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000230 {
231 Parent.kind = CXCursor_NoDeclFound;
232 Parent.data[0] = 0;
233 Parent.data[1] = 0;
234 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000235 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000236 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000237
Ted Kremenekab979612010-11-11 08:05:23 +0000238 ASTUnit *getASTUnit() const { return TU; }
239
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000240 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000241
242 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
243 getPreprocessedEntities();
244
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000246
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000247 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000248 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000249 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000250 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000251 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000252 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000253 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
254 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000255 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000256 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000257 bool VisitClassTemplatePartialSpecializationDecl(
258 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000259 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000260 bool VisitEnumConstantDecl(EnumConstantDecl *D);
261 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
262 bool VisitFunctionDecl(FunctionDecl *ND);
263 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000264 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000265 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000266 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000267 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000268 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
270 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
271 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
272 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000273 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000274 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
275 bool VisitObjCImplDecl(ObjCImplDecl *D);
276 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
277 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000278 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
279 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
280 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000281 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000282 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000283 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000284 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000285 bool VisitUsingDecl(UsingDecl *D);
286 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
287 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000288
Douglas Gregor01829d32010-08-31 14:41:23 +0000289 // Name visitor
290 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000291 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000292
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000293 // Template visitors
294 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000295 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000296 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
297
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000298 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000299 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000300 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000301 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000302 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
303 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000304 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000305 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000306 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000307 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
308 bool VisitPointerTypeLoc(PointerTypeLoc TL);
309 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
310 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
311 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
312 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000313 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000315 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000316 // FIXME: Implement visitors here when the unimplemented TypeLocs get
317 // implemented
318 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
319 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000320
Douglas Gregora59e3902010-01-21 23:27:09 +0000321 // Statement visitors
322 bool VisitStmt(Stmt *S);
323 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000324 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000325 bool VisitIfStmt(IfStmt *S);
326 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000327 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000328 bool VisitWhileStmt(WhileStmt *S);
329 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000330
Douglas Gregor336fd812010-01-23 00:40:08 +0000331 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000332 bool VisitDeclRefExpr(DeclRefExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000333 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000334 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000335 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000336 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000337 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000338 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000339 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000340 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000341 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
342 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000343 bool VisitInitListExpr(InitListExpr *E);
344 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000345 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000346 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000347 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000348 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
349 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000350 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000351 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000352 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000353 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000354 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000355 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000356 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000357 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000358
359#define DATA_RECURSIVE_VISIT(NAME)\
360bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
361 DATA_RECURSIVE_VISIT(BinaryOperator)
362 DATA_RECURSIVE_VISIT(MemberExpr)
363 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000364 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000365
366 // Data-recursive visitor functions.
367 bool IsInRegionOfInterest(CXCursor C);
368 bool RunVisitorWorkList(VisitorWorkList &WL);
369 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
370 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000371};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000372
Ted Kremenekab188932010-01-05 19:32:54 +0000373} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000374
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000375static SourceRange getRawCursorExtent(CXCursor C);
376
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000377RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000378 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
379}
380
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381/// \brief Visit the given cursor and, if requested by the visitor,
382/// its children.
383///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000384/// \param Cursor the cursor to visit.
385///
386/// \param CheckRegionOfInterest if true, then the caller already checked that
387/// this cursor is within the region of interest.
388///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389/// \returns true if the visitation should be aborted, false if it
390/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392 if (clang_isInvalid(Cursor.kind))
393 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000394
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 if (clang_isDeclaration(Cursor.kind)) {
396 Decl *D = getCursorDecl(Cursor);
397 assert(D && "Invalid declaration cursor");
398 if (D->getPCHLevel() > MaxPCHLevel)
399 return false;
400
401 if (D->isImplicit())
402 return false;
403 }
404
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000405 // If we have a range of interest, and this cursor doesn't intersect with it,
406 // we're done.
407 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000408 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000409 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000410 return false;
411 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000412
Douglas Gregorb1373d02010-01-20 20:59:29 +0000413 switch (Visitor(Cursor, Parent, ClientData)) {
414 case CXChildVisit_Break:
415 return true;
416
417 case CXChildVisit_Continue:
418 return false;
419
420 case CXChildVisit_Recurse:
421 return VisitChildren(Cursor);
422 }
423
Douglas Gregorfd643772010-01-25 16:45:46 +0000424 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425}
426
Douglas Gregor788f5a12010-03-20 00:41:21 +0000427std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
428CursorVisitor::getPreprocessedEntities() {
429 PreprocessingRecord &PPRec
430 = *TU->getPreprocessor().getPreprocessingRecord();
431
432 bool OnlyLocalDecls
433 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
434
435 // There is no region of interest; we have to walk everything.
436 if (RegionOfInterest.isInvalid())
437 return std::make_pair(PPRec.begin(OnlyLocalDecls),
438 PPRec.end(OnlyLocalDecls));
439
440 // Find the file in which the region of interest lands.
441 SourceManager &SM = TU->getSourceManager();
442 std::pair<FileID, unsigned> Begin
443 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
444 std::pair<FileID, unsigned> End
445 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
446
447 // The region of interest spans files; we have to walk everything.
448 if (Begin.first != End.first)
449 return std::make_pair(PPRec.begin(OnlyLocalDecls),
450 PPRec.end(OnlyLocalDecls));
451
452 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
453 = TU->getPreprocessedEntitiesByFile();
454 if (ByFileMap.empty()) {
455 // Build the mapping from files to sets of preprocessed entities.
456 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
457 EEnd = PPRec.end(OnlyLocalDecls);
458 E != EEnd; ++E) {
459 std::pair<FileID, unsigned> P
460 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
461 ByFileMap[P.first].push_back(*E);
462 }
463 }
464
465 return std::make_pair(ByFileMap[Begin.first].begin(),
466 ByFileMap[Begin.first].end());
467}
468
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469/// \brief Visit the children of the given cursor.
470///
471/// \returns true if the visitation should be aborted, false if it
472/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000473bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000474 if (clang_isReference(Cursor.kind)) {
475 // By definition, references have no children.
476 return false;
477 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478
479 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000481 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 if (clang_isDeclaration(Cursor.kind)) {
484 Decl *D = getCursorDecl(Cursor);
485 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000486 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000488
Douglas Gregora59e3902010-01-21 23:27:09 +0000489 if (clang_isStatement(Cursor.kind))
490 return Visit(getCursorStmt(Cursor));
491 if (clang_isExpression(Cursor.kind))
492 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000493
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000495 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000496 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
497 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000498 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
499 TLEnd = CXXUnit->top_level_end();
500 TL != TLEnd; ++TL) {
501 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000502 return true;
503 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 } else if (VisitDeclContext(
505 CXXUnit->getASTContext().getTranslationUnitDecl()))
506 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000507
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000509 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 // FIXME: Once we have the ability to deserialize a preprocessing record,
511 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000512 PreprocessingRecord::iterator E, EEnd;
513 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000514 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
515 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
516 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000517
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 continue;
519 }
520
521 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
522 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
523 return true;
524
525 continue;
526 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000527
528 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
529 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
530 return true;
531
532 continue;
533 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000534 }
535 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000536 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000537 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000538
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 return false;
541}
542
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000543bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000544 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
545 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000546
Ted Kremenek664cffd2010-07-22 11:30:19 +0000547 if (Stmt *Body = B->getBody())
548 return Visit(MakeCXCursor(Body, StmtParent, TU));
549
550 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000551}
552
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000553llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
554 if (RegionOfInterest.isValid()) {
555 SourceRange Range = getRawCursorExtent(Cursor);
556 if (Range.isInvalid())
557 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000558
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000559 switch (CompareRegionOfInterest(Range)) {
560 case RangeBefore:
561 // This declaration comes before the region of interest; skip it.
562 return llvm::Optional<bool>();
563
564 case RangeAfter:
565 // This declaration comes after the region of interest; we're done.
566 return false;
567
568 case RangeOverlap:
569 // This declaration overlaps the region of interest; visit it.
570 break;
571 }
572 }
573 return true;
574}
575
576bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
577 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
578
579 // FIXME: Eventually remove. This part of a hack to support proper
580 // iteration over all Decls contained lexically within an ObjC container.
581 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
582 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
583
584 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000585 Decl *D = *I;
586 if (D->getLexicalDeclContext() != DC)
587 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000588 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000589 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
590 if (!V.hasValue())
591 continue;
592 if (!V.getValue())
593 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000594 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595 return true;
596 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000598}
599
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000600bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
601 llvm_unreachable("Translation units are visited directly by Visit()");
602 return false;
603}
604
605bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
606 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
607 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609 return false;
610}
611
612bool CursorVisitor::VisitTagDecl(TagDecl *D) {
613 return VisitDeclContext(D);
614}
615
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000616bool CursorVisitor::VisitClassTemplateSpecializationDecl(
617 ClassTemplateSpecializationDecl *D) {
618 bool ShouldVisitBody = false;
619 switch (D->getSpecializationKind()) {
620 case TSK_Undeclared:
621 case TSK_ImplicitInstantiation:
622 // Nothing to visit
623 return false;
624
625 case TSK_ExplicitInstantiationDeclaration:
626 case TSK_ExplicitInstantiationDefinition:
627 break;
628
629 case TSK_ExplicitSpecialization:
630 ShouldVisitBody = true;
631 break;
632 }
633
634 // Visit the template arguments used in the specialization.
635 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
636 TypeLoc TL = SpecType->getTypeLoc();
637 if (TemplateSpecializationTypeLoc *TSTLoc
638 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
639 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
640 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
641 return true;
642 }
643 }
644
645 if (ShouldVisitBody && VisitCXXRecordDecl(D))
646 return true;
647
648 return false;
649}
650
Douglas Gregor74dbe642010-08-31 19:31:58 +0000651bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
652 ClassTemplatePartialSpecializationDecl *D) {
653 // FIXME: Visit the "outer" template parameter lists on the TagDecl
654 // before visiting these template parameters.
655 if (VisitTemplateParameters(D->getTemplateParameters()))
656 return true;
657
658 // Visit the partial specialization arguments.
659 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
660 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
661 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
662 return true;
663
664 return VisitCXXRecordDecl(D);
665}
666
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000667bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000668 // Visit the default argument.
669 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
670 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
671 if (Visit(DefArg->getTypeLoc()))
672 return true;
673
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000674 return false;
675}
676
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000677bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
678 if (Expr *Init = D->getInitExpr())
679 return Visit(MakeCXCursor(Init, StmtParent, TU));
680 return false;
681}
682
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000683bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
684 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
685 if (Visit(TSInfo->getTypeLoc()))
686 return true;
687
688 return false;
689}
690
Douglas Gregora67e03f2010-09-09 21:42:20 +0000691/// \brief Compare two base or member initializers based on their source order.
692static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
693 CXXBaseOrMemberInitializer const * const *X
694 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
695 CXXBaseOrMemberInitializer const * const *Y
696 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
697
698 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
699 return -1;
700 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
701 return 1;
702 else
703 return 0;
704}
705
Douglas Gregorb1373d02010-01-20 20:59:29 +0000706bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000707 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
708 // Visit the function declaration's syntactic components in the order
709 // written. This requires a bit of work.
710 TypeLoc TL = TSInfo->getTypeLoc();
711 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
712
713 // If we have a function declared directly (without the use of a typedef),
714 // visit just the return type. Otherwise, just visit the function's type
715 // now.
716 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
717 (!FTL && Visit(TL)))
718 return true;
719
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000720 // Visit the nested-name-specifier, if present.
721 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
722 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
723 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000724
725 // Visit the declaration name.
726 if (VisitDeclarationNameInfo(ND->getNameInfo()))
727 return true;
728
729 // FIXME: Visit explicitly-specified template arguments!
730
731 // Visit the function parameters, if we have a function type.
732 if (FTL && VisitFunctionTypeLoc(*FTL, true))
733 return true;
734
735 // FIXME: Attributes?
736 }
737
Douglas Gregora67e03f2010-09-09 21:42:20 +0000738 if (ND->isThisDeclarationADefinition()) {
739 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
740 // Find the initializers that were written in the source.
741 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
742 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
743 IEnd = Constructor->init_end();
744 I != IEnd; ++I) {
745 if (!(*I)->isWritten())
746 continue;
747
748 WrittenInits.push_back(*I);
749 }
750
751 // Sort the initializers in source order
752 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
753 &CompareCXXBaseOrMemberInitializers);
754
755 // Visit the initializers in source order
756 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
757 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
758 if (Init->isMemberInitializer()) {
759 if (Visit(MakeCursorMemberRef(Init->getMember(),
760 Init->getMemberLocation(), TU)))
761 return true;
762 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
763 if (Visit(BaseInfo->getTypeLoc()))
764 return true;
765 }
766
767 // Visit the initializer value.
768 if (Expr *Initializer = Init->getInit())
769 if (Visit(MakeCXCursor(Initializer, ND, TU)))
770 return true;
771 }
772 }
773
774 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
775 return true;
776 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregorb1373d02010-01-20 20:59:29 +0000778 return false;
779}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
782 if (VisitDeclaratorDecl(D))
783 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785 if (Expr *BitWidth = D->getBitWidth())
786 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788 return false;
789}
790
791bool CursorVisitor::VisitVarDecl(VarDecl *D) {
792 if (VisitDeclaratorDecl(D))
793 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 if (Expr *Init = D->getInit())
796 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798 return false;
799}
800
Douglas Gregor84b51d72010-09-01 20:16:53 +0000801bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
802 if (VisitDeclaratorDecl(D))
803 return true;
804
805 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
806 if (Expr *DefArg = D->getDefaultArgument())
807 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
808
809 return false;
810}
811
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000812bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
813 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
814 // before visiting these template parameters.
815 if (VisitTemplateParameters(D->getTemplateParameters()))
816 return true;
817
818 return VisitFunctionDecl(D->getTemplatedDecl());
819}
820
Douglas Gregor39d6f072010-08-31 19:02:00 +0000821bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
822 // FIXME: Visit the "outer" template parameter lists on the TagDecl
823 // before visiting these template parameters.
824 if (VisitTemplateParameters(D->getTemplateParameters()))
825 return true;
826
827 return VisitCXXRecordDecl(D->getTemplatedDecl());
828}
829
Douglas Gregor84b51d72010-09-01 20:16:53 +0000830bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
831 if (VisitTemplateParameters(D->getTemplateParameters()))
832 return true;
833
834 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
835 VisitTemplateArgumentLoc(D->getDefaultArgument()))
836 return true;
837
838 return false;
839}
840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000842 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
843 if (Visit(TSInfo->getTypeLoc()))
844 return true;
845
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000846 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000847 PEnd = ND->param_end();
848 P != PEnd; ++P) {
849 if (Visit(MakeCXCursor(*P, TU)))
850 return true;
851 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853 if (ND->isThisDeclarationADefinition() &&
854 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
855 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 return false;
858}
859
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000860namespace {
861 struct ContainerDeclsSort {
862 SourceManager &SM;
863 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
864 bool operator()(Decl *A, Decl *B) {
865 SourceLocation L_A = A->getLocStart();
866 SourceLocation L_B = B->getLocStart();
867 assert(L_A.isValid() && L_B.isValid());
868 return SM.isBeforeInTranslationUnit(L_A, L_B);
869 }
870 };
871}
872
Douglas Gregora59e3902010-01-21 23:27:09 +0000873bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000874 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
875 // an @implementation can lexically contain Decls that are not properly
876 // nested in the AST. When we identify such cases, we need to retrofit
877 // this nesting here.
878 if (!DI_current)
879 return VisitDeclContext(D);
880
881 // Scan the Decls that immediately come after the container
882 // in the current DeclContext. If any fall within the
883 // container's lexical region, stash them into a vector
884 // for later processing.
885 llvm::SmallVector<Decl *, 24> DeclsInContainer;
886 SourceLocation EndLoc = D->getSourceRange().getEnd();
887 SourceManager &SM = TU->getSourceManager();
888 if (EndLoc.isValid()) {
889 DeclContext::decl_iterator next = *DI_current;
890 while (++next != DE_current) {
891 Decl *D_next = *next;
892 if (!D_next)
893 break;
894 SourceLocation L = D_next->getLocStart();
895 if (!L.isValid())
896 break;
897 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
898 *DI_current = next;
899 DeclsInContainer.push_back(D_next);
900 continue;
901 }
902 break;
903 }
904 }
905
906 // The common case.
907 if (DeclsInContainer.empty())
908 return VisitDeclContext(D);
909
910 // Get all the Decls in the DeclContext, and sort them with the
911 // additional ones we've collected. Then visit them.
912 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
913 I!=E; ++I) {
914 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000915 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
916 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000917 continue;
918 DeclsInContainer.push_back(subDecl);
919 }
920
921 // Now sort the Decls so that they appear in lexical order.
922 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
923 ContainerDeclsSort(SM));
924
925 // Now visit the decls.
926 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
927 E = DeclsInContainer.end(); I != E; ++I) {
928 CXCursor Cursor = MakeCXCursor(*I, TU);
929 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
930 if (!V.hasValue())
931 continue;
932 if (!V.getValue())
933 return false;
934 if (Visit(Cursor, true))
935 return true;
936 }
937 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000938}
939
Douglas Gregorb1373d02010-01-20 20:59:29 +0000940bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000941 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
942 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000943 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000944
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000945 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
946 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
947 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000948 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregora59e3902010-01-21 23:27:09 +0000951 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000952}
953
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000954bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
955 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
956 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
957 E = PID->protocol_end(); I != E; ++I, ++PL)
958 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
959 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000960
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000961 return VisitObjCContainerDecl(PID);
962}
963
Ted Kremenek23173d72010-05-18 21:09:07 +0000964bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000965 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000966 return true;
967
Ted Kremenek23173d72010-05-18 21:09:07 +0000968 // FIXME: This implements a workaround with @property declarations also being
969 // installed in the DeclContext for the @interface. Eventually this code
970 // should be removed.
971 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
972 if (!CDecl || !CDecl->IsClassExtension())
973 return false;
974
975 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
976 if (!ID)
977 return false;
978
979 IdentifierInfo *PropertyId = PD->getIdentifier();
980 ObjCPropertyDecl *prevDecl =
981 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
982
983 if (!prevDecl)
984 return false;
985
986 // Visit synthesized methods since they will be skipped when visiting
987 // the @interface.
988 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000989 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000990 if (Visit(MakeCXCursor(MD, TU)))
991 return true;
992
993 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000994 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000995 if (Visit(MakeCXCursor(MD, TU)))
996 return true;
997
998 return false;
999}
1000
Douglas Gregorb1373d02010-01-20 20:59:29 +00001001bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001002 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003 if (D->getSuperClass() &&
1004 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001005 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001006 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001007 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001008
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001009 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1010 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1011 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001012 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregora59e3902010-01-21 23:27:09 +00001015 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001016}
1017
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1019 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001023 // 'ID' could be null when dealing with invalid code.
1024 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1025 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1026 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028 return VisitObjCImplDecl(D);
1029}
1030
1031bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1032#if 0
1033 // Issue callbacks for super class.
1034 // FIXME: No source location information!
1035 if (D->getSuperClass() &&
1036 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001038 TU)))
1039 return true;
1040#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042 return VisitObjCImplDecl(D);
1043}
1044
1045bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1046 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1047 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1048 E = D->protocol_end();
1049 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001050 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001051 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
1053 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001054}
1055
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001056bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1057 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1058 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1059 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001062}
1063
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001064bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1065 return VisitDeclContext(D);
1066}
1067
Douglas Gregor69319002010-08-31 23:48:11 +00001068bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001069 // Visit nested-name-specifier.
1070 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1071 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1072 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001073
1074 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1075 D->getTargetNameLoc(), TU));
1076}
1077
Douglas Gregor7e242562010-09-01 19:52:22 +00001078bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001079 // Visit nested-name-specifier.
1080 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1081 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1082 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001083
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001084 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1085 return true;
1086
Douglas Gregor7e242562010-09-01 19:52:22 +00001087 return VisitDeclarationNameInfo(D->getNameInfo());
1088}
1089
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001090bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001091 // Visit nested-name-specifier.
1092 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1093 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1094 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001095
1096 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1097 D->getIdentLocation(), TU));
1098}
1099
Douglas Gregor7e242562010-09-01 19:52:22 +00001100bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001101 // Visit nested-name-specifier.
1102 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1103 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1104 return true;
1105
Douglas Gregor7e242562010-09-01 19:52:22 +00001106 return VisitDeclarationNameInfo(D->getNameInfo());
1107}
1108
1109bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1110 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001111 // Visit nested-name-specifier.
1112 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1113 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1114 return true;
1115
Douglas Gregor7e242562010-09-01 19:52:22 +00001116 return false;
1117}
1118
Douglas Gregor01829d32010-08-31 14:41:23 +00001119bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1120 switch (Name.getName().getNameKind()) {
1121 case clang::DeclarationName::Identifier:
1122 case clang::DeclarationName::CXXLiteralOperatorName:
1123 case clang::DeclarationName::CXXOperatorName:
1124 case clang::DeclarationName::CXXUsingDirective:
1125 return false;
1126
1127 case clang::DeclarationName::CXXConstructorName:
1128 case clang::DeclarationName::CXXDestructorName:
1129 case clang::DeclarationName::CXXConversionFunctionName:
1130 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1131 return Visit(TSInfo->getTypeLoc());
1132 return false;
1133
1134 case clang::DeclarationName::ObjCZeroArgSelector:
1135 case clang::DeclarationName::ObjCOneArgSelector:
1136 case clang::DeclarationName::ObjCMultiArgSelector:
1137 // FIXME: Per-identifier location info?
1138 return false;
1139 }
1140
1141 return false;
1142}
1143
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001144bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1145 SourceRange Range) {
1146 // FIXME: This whole routine is a hack to work around the lack of proper
1147 // source information in nested-name-specifiers (PR5791). Since we do have
1148 // a beginning source location, we can visit the first component of the
1149 // nested-name-specifier, if it's a single-token component.
1150 if (!NNS)
1151 return false;
1152
1153 // Get the first component in the nested-name-specifier.
1154 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1155 NNS = Prefix;
1156
1157 switch (NNS->getKind()) {
1158 case NestedNameSpecifier::Namespace:
1159 // FIXME: The token at this source location might actually have been a
1160 // namespace alias, but we don't model that. Lame!
1161 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1162 TU));
1163
1164 case NestedNameSpecifier::TypeSpec: {
1165 // If the type has a form where we know that the beginning of the source
1166 // range matches up with a reference cursor. Visit the appropriate reference
1167 // cursor.
1168 Type *T = NNS->getAsType();
1169 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1170 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1171 if (const TagType *Tag = dyn_cast<TagType>(T))
1172 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1173 if (const TemplateSpecializationType *TST
1174 = dyn_cast<TemplateSpecializationType>(T))
1175 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1176 break;
1177 }
1178
1179 case NestedNameSpecifier::TypeSpecWithTemplate:
1180 case NestedNameSpecifier::Global:
1181 case NestedNameSpecifier::Identifier:
1182 break;
1183 }
1184
1185 return false;
1186}
1187
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001188bool CursorVisitor::VisitTemplateParameters(
1189 const TemplateParameterList *Params) {
1190 if (!Params)
1191 return false;
1192
1193 for (TemplateParameterList::const_iterator P = Params->begin(),
1194 PEnd = Params->end();
1195 P != PEnd; ++P) {
1196 if (Visit(MakeCXCursor(*P, TU)))
1197 return true;
1198 }
1199
1200 return false;
1201}
1202
Douglas Gregor0b36e612010-08-31 20:37:03 +00001203bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1204 switch (Name.getKind()) {
1205 case TemplateName::Template:
1206 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1207
1208 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001209 // Visit the overloaded template set.
1210 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1211 return true;
1212
Douglas Gregor0b36e612010-08-31 20:37:03 +00001213 return false;
1214
1215 case TemplateName::DependentTemplate:
1216 // FIXME: Visit nested-name-specifier.
1217 return false;
1218
1219 case TemplateName::QualifiedTemplate:
1220 // FIXME: Visit nested-name-specifier.
1221 return Visit(MakeCursorTemplateRef(
1222 Name.getAsQualifiedTemplateName()->getDecl(),
1223 Loc, TU));
1224 }
1225
1226 return false;
1227}
1228
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001229bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1230 switch (TAL.getArgument().getKind()) {
1231 case TemplateArgument::Null:
1232 case TemplateArgument::Integral:
1233 return false;
1234
1235 case TemplateArgument::Pack:
1236 // FIXME: Implement when variadic templates come along.
1237 return false;
1238
1239 case TemplateArgument::Type:
1240 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1241 return Visit(TSInfo->getTypeLoc());
1242 return false;
1243
1244 case TemplateArgument::Declaration:
1245 if (Expr *E = TAL.getSourceDeclExpression())
1246 return Visit(MakeCXCursor(E, StmtParent, TU));
1247 return false;
1248
1249 case TemplateArgument::Expression:
1250 if (Expr *E = TAL.getSourceExpression())
1251 return Visit(MakeCXCursor(E, StmtParent, TU));
1252 return false;
1253
1254 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001255 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1256 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001257 }
1258
1259 return false;
1260}
1261
Ted Kremeneka0536d82010-05-07 01:04:29 +00001262bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1263 return VisitDeclContext(D);
1264}
1265
Douglas Gregor01829d32010-08-31 14:41:23 +00001266bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1267 return Visit(TL.getUnqualifiedLoc());
1268}
1269
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1271 ASTContext &Context = TU->getASTContext();
1272
1273 // Some builtin types (such as Objective-C's "id", "sel", and
1274 // "Class") have associated declarations. Create cursors for those.
1275 QualType VisitType;
1276 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001279 case BuiltinType::Char_U:
1280 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001281 case BuiltinType::Char16:
1282 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001283 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001284 case BuiltinType::UInt:
1285 case BuiltinType::ULong:
1286 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001287 case BuiltinType::UInt128:
1288 case BuiltinType::Char_S:
1289 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001290 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001291 case BuiltinType::Short:
1292 case BuiltinType::Int:
1293 case BuiltinType::Long:
1294 case BuiltinType::LongLong:
1295 case BuiltinType::Int128:
1296 case BuiltinType::Float:
1297 case BuiltinType::Double:
1298 case BuiltinType::LongDouble:
1299 case BuiltinType::NullPtr:
1300 case BuiltinType::Overload:
1301 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001302 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001303
1304 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001305 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001306
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001307 case BuiltinType::ObjCId:
1308 VisitType = Context.getObjCIdType();
1309 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001310
1311 case BuiltinType::ObjCClass:
1312 VisitType = Context.getObjCClassType();
1313 break;
1314
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001315 case BuiltinType::ObjCSel:
1316 VisitType = Context.getObjCSelType();
1317 break;
1318 }
1319
1320 if (!VisitType.isNull()) {
1321 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001322 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323 TU));
1324 }
1325
1326 return false;
1327}
1328
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001329bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1330 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1331}
1332
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1334 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1335}
1336
1337bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1338 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1339}
1340
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001341bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001342 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001343 // no context information with which we can match up the depth/index in the
1344 // type to the appropriate
1345 return false;
1346}
1347
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1349 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1350 return true;
1351
John McCallc12c5bb2010-05-15 11:32:37 +00001352 return false;
1353}
1354
1355bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1356 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1357 return true;
1358
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1360 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1361 TU)))
1362 return true;
1363 }
1364
1365 return false;
1366}
1367
1368bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001369 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370}
1371
1372bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1373 return Visit(TL.getPointeeLoc());
1374}
1375
1376bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1377 return Visit(TL.getPointeeLoc());
1378}
1379
1380bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1381 return Visit(TL.getPointeeLoc());
1382}
1383
1384bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386}
1387
1388bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001389 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390}
1391
Douglas Gregor01829d32010-08-31 14:41:23 +00001392bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1393 bool SkipResultType) {
1394 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001395 return true;
1396
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001397 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001398 if (Decl *D = TL.getArg(I))
1399 if (Visit(MakeCXCursor(D, TU)))
1400 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001401
1402 return false;
1403}
1404
1405bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1406 if (Visit(TL.getElementLoc()))
1407 return true;
1408
1409 if (Expr *Size = TL.getSizeExpr())
1410 return Visit(MakeCXCursor(Size, StmtParent, TU));
1411
1412 return false;
1413}
1414
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001415bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1416 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001417 // Visit the template name.
1418 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1419 TL.getTemplateNameLoc()))
1420 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001421
1422 // Visit the template arguments.
1423 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1424 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1425 return true;
1426
1427 return false;
1428}
1429
Douglas Gregor2332c112010-01-21 20:48:56 +00001430bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1431 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1432}
1433
1434bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1435 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1436 return Visit(TSInfo->getTypeLoc());
1437
1438 return false;
1439}
1440
Douglas Gregora59e3902010-01-21 23:27:09 +00001441bool CursorVisitor::VisitStmt(Stmt *S) {
1442 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1443 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001444 if (Stmt *C = *Child)
1445 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1446 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001447 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001448
Douglas Gregora59e3902010-01-21 23:27:09 +00001449 return false;
1450}
1451
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001452bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1453 // Specially handle CaseStmts because they can be nested, e.g.:
1454 //
1455 // case 1:
1456 // case 2:
1457 //
1458 // In this case the second CaseStmt is the child of the first. Walking
1459 // these recursively can blow out the stack.
1460 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1461 while (true) {
1462 // Set the Parent field to Cursor, then back to its old value once we're
1463 // done.
1464 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1465
1466 if (Stmt *LHS = S->getLHS())
1467 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1468 return true;
1469 if (Stmt *RHS = S->getRHS())
1470 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1471 return true;
1472 if (Stmt *SubStmt = S->getSubStmt()) {
1473 if (!isa<CaseStmt>(SubStmt))
1474 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1475
1476 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1477 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1478 Cursor = MakeCXCursor(CS, StmtParent, TU);
1479 if (RegionOfInterest.isValid()) {
1480 SourceRange Range = CS->getSourceRange();
1481 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1482 return false;
1483 }
1484
1485 switch (Visitor(Cursor, Parent, ClientData)) {
1486 case CXChildVisit_Break: return true;
1487 case CXChildVisit_Continue: return false;
1488 case CXChildVisit_Recurse:
1489 // Perform tail-recursion manually.
1490 S = CS;
1491 continue;
1492 }
1493 }
1494 return false;
1495 }
1496}
1497
Douglas Gregora59e3902010-01-21 23:27:09 +00001498bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001499 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001500 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1501 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001502 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001503 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001504 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001505 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001506
Douglas Gregora59e3902010-01-21 23:27:09 +00001507 return false;
1508}
1509
Douglas Gregor36897b02010-09-10 00:22:18 +00001510bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1511 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1512}
1513
Douglas Gregorf5bab412010-01-22 01:00:11 +00001514bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1515 if (VarDecl *Var = S->getConditionVariable()) {
1516 if (Visit(MakeCXCursor(Var, TU)))
1517 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001518 }
1519
Douglas Gregor263b47b2010-01-25 16:12:32 +00001520 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1521 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001522 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1523 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001524 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1525 return true;
1526
1527 return false;
1528}
1529
1530bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1531 if (VarDecl *Var = S->getConditionVariable()) {
1532 if (Visit(MakeCXCursor(Var, TU)))
1533 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001534 }
1535
Douglas Gregor263b47b2010-01-25 16:12:32 +00001536 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1537 return true;
1538 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1539 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001540
Douglas Gregor263b47b2010-01-25 16:12:32 +00001541 return false;
1542}
1543
1544bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1545 if (VarDecl *Var = S->getConditionVariable()) {
1546 if (Visit(MakeCXCursor(Var, TU)))
1547 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001548 }
1549
Douglas Gregor263b47b2010-01-25 16:12:32 +00001550 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1551 return true;
1552 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001553 return true;
1554
Douglas Gregor263b47b2010-01-25 16:12:32 +00001555 return false;
1556}
1557
1558bool CursorVisitor::VisitForStmt(ForStmt *S) {
1559 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1560 return true;
1561 if (VarDecl *Var = S->getConditionVariable()) {
1562 if (Visit(MakeCXCursor(Var, TU)))
1563 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001564 }
1565
Douglas Gregor263b47b2010-01-25 16:12:32 +00001566 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1567 return true;
1568 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1569 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001570 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1571 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001572
Douglas Gregorf5bab412010-01-22 01:00:11 +00001573 return false;
1574}
1575
Douglas Gregor8947a752010-09-02 20:35:02 +00001576bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1577 // Visit nested-name-specifier, if present.
1578 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1579 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1580 return true;
1581
1582 // Visit declaration name.
1583 if (VisitDeclarationNameInfo(E->getNameInfo()))
1584 return true;
1585
1586 // Visit explicitly-specified template arguments.
1587 if (E->hasExplicitTemplateArgs()) {
1588 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1589 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1590 *ArgEnd = Arg + Args.NumTemplateArgs;
1591 Arg != ArgEnd; ++Arg)
1592 if (VisitTemplateArgumentLoc(*Arg))
1593 return true;
1594 }
1595
1596 return false;
1597}
1598
Ted Kremenek3064ef92010-08-27 21:34:58 +00001599bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1600 if (D->isDefinition()) {
1601 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1602 E = D->bases_end(); I != E; ++I) {
1603 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1604 return true;
1605 }
1606 }
1607
1608 return VisitTagDecl(D);
1609}
1610
1611
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001612bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1613 return Visit(B->getBlockDecl());
1614}
1615
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001616bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001617 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001618 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1619 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001620
1621 // Visit the components of the offsetof expression.
1622 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1623 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1624 const OffsetOfNode &Node = E->getComponent(I);
1625 switch (Node.getKind()) {
1626 case OffsetOfNode::Array:
1627 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1628 StmtParent, TU)))
1629 return true;
1630 break;
1631
1632 case OffsetOfNode::Field:
1633 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1634 TU)))
1635 return true;
1636 break;
1637
1638 case OffsetOfNode::Identifier:
1639 case OffsetOfNode::Base:
1640 continue;
1641 }
1642 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001643
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001644 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001645}
1646
Douglas Gregor336fd812010-01-23 00:40:08 +00001647bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1648 if (E->isArgumentType()) {
1649 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1650 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001651
Douglas Gregor336fd812010-01-23 00:40:08 +00001652 return false;
1653 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001654
Douglas Gregor336fd812010-01-23 00:40:08 +00001655 return VisitExpr(E);
1656}
1657
1658bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1659 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1660 if (Visit(TSInfo->getTypeLoc()))
1661 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001662
Douglas Gregor336fd812010-01-23 00:40:08 +00001663 return VisitCastExpr(E);
1664}
1665
1666bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1667 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1668 if (Visit(TSInfo->getTypeLoc()))
1669 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001670
Douglas Gregor336fd812010-01-23 00:40:08 +00001671 return VisitExpr(E);
1672}
1673
Douglas Gregor36897b02010-09-10 00:22:18 +00001674bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1675 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1676}
1677
Douglas Gregor648220e2010-08-10 15:02:34 +00001678bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1679 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1680 Visit(E->getArgTInfo2()->getTypeLoc());
1681}
1682
1683bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1684 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1685 return true;
1686
1687 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1688}
1689
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001690bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1691 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001692 if (InitListExpr *Syntactic = E->getSyntacticForm())
1693 return VisitExpr(Syntactic);
1694
1695 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001696}
1697
1698bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1699 // Visit the designators.
1700 typedef DesignatedInitExpr::Designator Designator;
1701 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1702 DEnd = E->designators_end();
1703 D != DEnd; ++D) {
1704 if (D->isFieldDesignator()) {
1705 if (FieldDecl *Field = D->getField())
1706 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1707 return true;
1708
1709 continue;
1710 }
1711
1712 if (D->isArrayDesignator()) {
1713 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1714 return true;
1715
1716 continue;
1717 }
1718
1719 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1720 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1721 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1722 return true;
1723 }
1724
1725 // Visit the initializer value itself.
1726 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1727}
1728
Douglas Gregor94802292010-09-02 21:20:16 +00001729bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1730 if (E->isTypeOperand()) {
1731 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1732 return Visit(TSInfo->getTypeLoc());
1733
1734 return false;
1735 }
1736
1737 return VisitExpr(E);
1738}
1739
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001740bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1741 if (E->isTypeOperand()) {
1742 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1743 return Visit(TSInfo->getTypeLoc());
1744
1745 return false;
1746 }
1747
1748 return VisitExpr(E);
1749}
1750
Douglas Gregorab6677e2010-09-08 00:15:04 +00001751bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1752 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001753 if (Visit(TSInfo->getTypeLoc()))
1754 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001755
1756 return VisitExpr(E);
1757}
1758
1759bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1760 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1761 return Visit(TSInfo->getTypeLoc());
1762
1763 return false;
1764}
1765
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001766bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1767 // Visit placement arguments.
1768 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1769 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1770 return true;
1771
1772 // Visit the allocated type.
1773 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1774 if (Visit(TSInfo->getTypeLoc()))
1775 return true;
1776
1777 // Visit the array size, if any.
1778 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1779 return true;
1780
1781 // Visit the initializer or constructor arguments.
1782 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1783 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1784 return true;
1785
1786 return false;
1787}
1788
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001789bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1790 // Visit base expression.
1791 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1792 return true;
1793
1794 // Visit the nested-name-specifier.
1795 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1796 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1797 return true;
1798
1799 // Visit the scope type that looks disturbingly like the nested-name-specifier
1800 // but isn't.
1801 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1802 if (Visit(TSInfo->getTypeLoc()))
1803 return true;
1804
1805 // Visit the name of the type being destroyed.
1806 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1807 if (Visit(TSInfo->getTypeLoc()))
1808 return true;
1809
1810 return false;
1811}
1812
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001813bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1814 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1815}
1816
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001817bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001818 // Visit the nested-name-specifier.
1819 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1820 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1821 return true;
1822
1823 // Visit the declaration name.
1824 if (VisitDeclarationNameInfo(E->getNameInfo()))
1825 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001826
1827 // Visit the overloaded declaration reference.
1828 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1829 return true;
1830
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001831 // Visit the explicitly-specified template arguments.
1832 if (const ExplicitTemplateArgumentList *ArgList
1833 = E->getOptionalExplicitTemplateArgs()) {
1834 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1835 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1836 Arg != ArgEnd; ++Arg) {
1837 if (VisitTemplateArgumentLoc(*Arg))
1838 return true;
1839 }
1840 }
1841
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001842 return false;
1843}
1844
Douglas Gregorbfebed22010-09-03 17:24:10 +00001845bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1846 DependentScopeDeclRefExpr *E) {
1847 // Visit the nested-name-specifier.
1848 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1849 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1850 return true;
1851
1852 // Visit the declaration name.
1853 if (VisitDeclarationNameInfo(E->getNameInfo()))
1854 return true;
1855
1856 // Visit the explicitly-specified template arguments.
1857 if (const ExplicitTemplateArgumentList *ArgList
1858 = E->getOptionalExplicitTemplateArgs()) {
1859 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1860 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1861 Arg != ArgEnd; ++Arg) {
1862 if (VisitTemplateArgumentLoc(*Arg))
1863 return true;
1864 }
1865 }
1866
1867 return false;
1868}
1869
Douglas Gregorab6677e2010-09-08 00:15:04 +00001870bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1871 CXXUnresolvedConstructExpr *E) {
1872 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1873 if (Visit(TSInfo->getTypeLoc()))
1874 return true;
1875
1876 return VisitExpr(E);
1877}
1878
Douglas Gregor25d63622010-09-03 17:35:34 +00001879bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1880 CXXDependentScopeMemberExpr *E) {
1881 // Visit the base expression, if there is one.
1882 if (!E->isImplicitAccess() &&
1883 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1884 return true;
1885
1886 // Visit the nested-name-specifier.
1887 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1888 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1889 return true;
1890
1891 // Visit the declaration name.
1892 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1893 return true;
1894
1895 // Visit the explicitly-specified template arguments.
1896 if (const ExplicitTemplateArgumentList *ArgList
1897 = E->getOptionalExplicitTemplateArgs()) {
1898 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1899 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1900 Arg != ArgEnd; ++Arg) {
1901 if (VisitTemplateArgumentLoc(*Arg))
1902 return true;
1903 }
1904 }
1905
1906 return false;
1907}
1908
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001909bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1910 // Visit the base expression, if there is one.
1911 if (!E->isImplicitAccess() &&
1912 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1913 return true;
1914
1915 return VisitOverloadExpr(E);
1916}
Douglas Gregor25d63622010-09-03 17:35:34 +00001917
Douglas Gregorc2350e52010-03-08 16:40:19 +00001918bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001919 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1920 if (Visit(TSInfo->getTypeLoc()))
1921 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001922
1923 return VisitExpr(E);
1924}
1925
Douglas Gregor81d34662010-04-20 15:39:42 +00001926bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1927 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1928}
1929
1930
Ted Kremenek09dfa372010-02-18 05:46:33 +00001931bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001932 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1933 i != e; ++i)
1934 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001935 return true;
1936
1937 return false;
1938}
1939
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001940//===----------------------------------------------------------------------===//
1941// Data-recursive visitor methods.
1942//===----------------------------------------------------------------------===//
1943
1944void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1945 CXCursor C = MakeCXCursor(S, StmtParent, TU);
1946 switch (S->getStmtClass()) {
1947 default: {
1948 unsigned size = WL.size();
1949 for (Stmt::child_iterator Child = S->child_begin(),
1950 ChildEnd = S->child_end(); Child != ChildEnd; ++Child) {
1951 if (Stmt *child = *Child) {
1952 WL.push_back(StmtVisit(child, C));
1953 }
1954 }
1955
1956 if (size == WL.size())
1957 return;
1958
1959 // Now reverse the entries we just added. This will match the DFS
1960 // ordering performed by the worklist.
1961 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1962 std::reverse(I, E);
1963 break;
1964 }
1965 case Stmt::ParenExprClass: {
1966 WL.push_back(StmtVisit(cast<ParenExpr>(S)->getSubExpr(), C));
1967 break;
1968 }
1969 case Stmt::BinaryOperatorClass: {
1970 BinaryOperator *B = cast<BinaryOperator>(S);
1971 WL.push_back(StmtVisit(B->getRHS(), C));
1972 WL.push_back(StmtVisit(B->getLHS(), C));
1973 break;
1974 }
1975 case Stmt::MemberExprClass: {
1976 MemberExpr *M = cast<MemberExpr>(S);
1977 WL.push_back(MemberExprParts(M, C));
1978 WL.push_back(StmtVisit(M->getBase(), C));
1979 break;
1980 }
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001981 case Stmt::CXXOperatorCallExprClass: {
1982 CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(S);
1983 // Note that we enqueue things in reverse order so that
1984 // they are visited correctly by the DFS.
1985
1986 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
1987 WL.push_back(StmtVisit(CE->getArg(N-I), C));
1988
1989 WL.push_back(StmtVisit(CE->getCallee(), C));
1990 WL.push_back(StmtVisit(CE->getArg(0), C));
1991 break;
1992 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001993 }
1994}
1995
1996bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1997 if (RegionOfInterest.isValid()) {
1998 SourceRange Range = getRawCursorExtent(C);
1999 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2000 return false;
2001 }
2002 return true;
2003}
2004
2005bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2006 while (!WL.empty()) {
2007 // Dequeue the worklist item.
2008 VisitorJob LI = WL.back(); WL.pop_back();
2009
2010 // Set the Parent field, then back to its old value once we're done.
2011 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2012
2013 switch (LI.getKind()) {
2014 case VisitorJob::StmtVisitKind: {
2015 // Update the current cursor.
2016 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002017 if (!S)
2018 continue;
2019
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002020 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
2021
2022 switch (S->getStmtClass()) {
2023 default: {
2024 // Perform default visitation for other cases.
2025 if (Visit(Cursor))
2026 return true;
2027 continue;
2028 }
2029 case Stmt::CallExprClass:
2030 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002031 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002032 case Stmt::ParenExprClass:
2033 case Stmt::MemberExprClass:
2034 case Stmt::BinaryOperatorClass: {
2035 if (!IsInRegionOfInterest(Cursor))
2036 continue;
2037 switch (Visitor(Cursor, Parent, ClientData)) {
2038 case CXChildVisit_Break:
2039 return true;
2040 case CXChildVisit_Continue:
2041 break;
2042 case CXChildVisit_Recurse:
2043 EnqueueWorkList(WL, S);
2044 break;
2045 }
2046 }
2047 }
2048 continue;
2049 }
2050 case VisitorJob::MemberExprPartsKind: {
2051 // Handle the other pieces in the MemberExpr besides the base.
2052 MemberExpr *M = cast<MemberExprParts>(LI).get();
2053
2054 // Visit the nested-name-specifier
2055 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2056 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2057 return true;
2058
2059 // Visit the declaration name.
2060 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2061 return true;
2062
2063 // Visit the explicitly-specified template arguments, if any.
2064 if (M->hasExplicitTemplateArgs()) {
2065 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2066 *ArgEnd = Arg + M->getNumTemplateArgs();
2067 Arg != ArgEnd; ++Arg) {
2068 if (VisitTemplateArgumentLoc(*Arg))
2069 return true;
2070 }
2071 }
2072 continue;
2073 }
2074 }
2075 }
2076 return false;
2077}
2078
2079bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2080 VisitorWorkList WL;
2081 EnqueueWorkList(WL, S);
2082 return RunVisitorWorkList(WL);
2083}
2084
2085//===----------------------------------------------------------------------===//
2086// Misc. API hooks.
2087//===----------------------------------------------------------------------===//
2088
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002089static llvm::sys::Mutex EnableMultithreadingMutex;
2090static bool EnabledMultithreading;
2091
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002092extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002093CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2094 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002095 // Disable pretty stack trace functionality, which will otherwise be a very
2096 // poor citizen of the world and set up all sorts of signal handlers.
2097 llvm::DisablePrettyStackTrace = true;
2098
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002099 // We use crash recovery to make some of our APIs more reliable, implicitly
2100 // enable it.
2101 llvm::CrashRecoveryContext::Enable();
2102
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002103 // Enable support for multithreading in LLVM.
2104 {
2105 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2106 if (!EnabledMultithreading) {
2107 llvm::llvm_start_multithreaded();
2108 EnabledMultithreading = true;
2109 }
2110 }
2111
Douglas Gregora030b7c2010-01-22 20:35:53 +00002112 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002113 if (excludeDeclarationsFromPCH)
2114 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002115 if (displayDiagnostics)
2116 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002117 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002118}
2119
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002120void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002121 if (CIdx)
2122 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002123}
2124
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002125CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002126 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002127 if (!CIdx)
2128 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002129
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002130 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002131 FileSystemOptions FileSystemOpts;
2132 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002133
Douglas Gregor28019772010-04-05 23:52:57 +00002134 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002135 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002136 CXXIdx->getOnlyLocalDecls(),
2137 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002138}
2139
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002140unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002141 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002142 CXTranslationUnit_CacheCompletionResults |
2143 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002144}
2145
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002146CXTranslationUnit
2147clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2148 const char *source_filename,
2149 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002150 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002151 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002152 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002153 return clang_parseTranslationUnit(CIdx, source_filename,
2154 command_line_args, num_command_line_args,
2155 unsaved_files, num_unsaved_files,
2156 CXTranslationUnit_DetailedPreprocessingRecord);
2157}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002158
2159struct ParseTranslationUnitInfo {
2160 CXIndex CIdx;
2161 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002162 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002163 int num_command_line_args;
2164 struct CXUnsavedFile *unsaved_files;
2165 unsigned num_unsaved_files;
2166 unsigned options;
2167 CXTranslationUnit result;
2168};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002169static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002170 ParseTranslationUnitInfo *PTUI =
2171 static_cast<ParseTranslationUnitInfo*>(UserData);
2172 CXIndex CIdx = PTUI->CIdx;
2173 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002174 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002175 int num_command_line_args = PTUI->num_command_line_args;
2176 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2177 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2178 unsigned options = PTUI->options;
2179 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002180
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002181 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002182 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002183
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002184 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2185
Douglas Gregor44c181a2010-07-23 00:33:23 +00002186 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002187 bool CompleteTranslationUnit
2188 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002189 bool CacheCodeCompetionResults
2190 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002191 bool CXXPrecompilePreamble
2192 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2193 bool CXXChainedPCH
2194 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002195
Douglas Gregor5352ac02010-01-28 00:27:43 +00002196 // Configure the diagnostics.
2197 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002198 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2199 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002200
Douglas Gregor4db64a42010-01-23 00:14:00 +00002201 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2202 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002203 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002204 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002205 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002206 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2207 Buffer));
2208 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002209
Douglas Gregorb10daed2010-10-11 16:52:23 +00002210 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002211
Ted Kremenek139ba862009-10-22 00:03:57 +00002212 // The 'source_filename' argument is optional. If the caller does not
2213 // specify it then it is assumed that the source file is specified
2214 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002215 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002217
2218 // Since the Clang C library is primarily used by batch tools dealing with
2219 // (often very broken) source code, where spell-checking can have a
2220 // significant negative impact on performance (particularly when
2221 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002222 // Only do this if we haven't found a spell-checking-related argument.
2223 bool FoundSpellCheckingArgument = false;
2224 for (int I = 0; I != num_command_line_args; ++I) {
2225 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2226 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2227 FoundSpellCheckingArgument = true;
2228 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002229 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002230 }
2231 if (!FoundSpellCheckingArgument)
2232 Args.push_back("-fno-spell-checking");
2233
2234 Args.insert(Args.end(), command_line_args,
2235 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002236
Douglas Gregor44c181a2010-07-23 00:33:23 +00002237 // Do we need the detailed preprocessing record?
2238 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002239 Args.push_back("-Xclang");
2240 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002241 }
2242
Douglas Gregorb10daed2010-10-11 16:52:23 +00002243 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002244 llvm::OwningPtr<ASTUnit> Unit(
2245 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2246 Diags,
2247 CXXIdx->getClangResourcesPath(),
2248 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002249 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002250 RemappedFiles.data(),
2251 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002252 PrecompilePreamble,
2253 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002254 CacheCodeCompetionResults,
2255 CXXPrecompilePreamble,
2256 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002257
Douglas Gregorb10daed2010-10-11 16:52:23 +00002258 if (NumErrors != Diags->getNumErrors()) {
2259 // Make sure to check that 'Unit' is non-NULL.
2260 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2261 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2262 DEnd = Unit->stored_diag_end();
2263 D != DEnd; ++D) {
2264 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2265 CXString Msg = clang_formatDiagnostic(&Diag,
2266 clang_defaultDiagnosticDisplayOptions());
2267 fprintf(stderr, "%s\n", clang_getCString(Msg));
2268 clang_disposeString(Msg);
2269 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002270#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002271 // On Windows, force a flush, since there may be multiple copies of
2272 // stderr and stdout in the file system, all with different buffers
2273 // but writing to the same device.
2274 fflush(stderr);
2275#endif
2276 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002277 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002278
Douglas Gregorb10daed2010-10-11 16:52:23 +00002279 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002280}
2281CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2282 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002283 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002284 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002285 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002286 unsigned num_unsaved_files,
2287 unsigned options) {
2288 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002289 num_command_line_args, unsaved_files,
2290 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002291 llvm::CrashRecoveryContext CRC;
2292
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002293 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002294 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2295 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2296 fprintf(stderr, " 'command_line_args' : [");
2297 for (int i = 0; i != num_command_line_args; ++i) {
2298 if (i)
2299 fprintf(stderr, ", ");
2300 fprintf(stderr, "'%s'", command_line_args[i]);
2301 }
2302 fprintf(stderr, "],\n");
2303 fprintf(stderr, " 'unsaved_files' : [");
2304 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2305 if (i)
2306 fprintf(stderr, ", ");
2307 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2308 unsaved_files[i].Length);
2309 }
2310 fprintf(stderr, "],\n");
2311 fprintf(stderr, " 'options' : %d,\n", options);
2312 fprintf(stderr, "}\n");
2313
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002314 return 0;
2315 }
2316
2317 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002318}
2319
Douglas Gregor19998442010-08-13 15:35:05 +00002320unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2321 return CXSaveTranslationUnit_None;
2322}
2323
2324int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2325 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002326 if (!TU)
2327 return 1;
2328
2329 return static_cast<ASTUnit *>(TU)->Save(FileName);
2330}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002331
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002332void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002333 if (CTUnit) {
2334 // If the translation unit has been marked as unsafe to free, just discard
2335 // it.
2336 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2337 return;
2338
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002339 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002340 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002341}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002342
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002343unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2344 return CXReparse_None;
2345}
2346
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002347struct ReparseTranslationUnitInfo {
2348 CXTranslationUnit TU;
2349 unsigned num_unsaved_files;
2350 struct CXUnsavedFile *unsaved_files;
2351 unsigned options;
2352 int result;
2353};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002354
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002355static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002356 ReparseTranslationUnitInfo *RTUI =
2357 static_cast<ReparseTranslationUnitInfo*>(UserData);
2358 CXTranslationUnit TU = RTUI->TU;
2359 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2360 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2361 unsigned options = RTUI->options;
2362 (void) options;
2363 RTUI->result = 1;
2364
Douglas Gregorabc563f2010-07-19 21:46:24 +00002365 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002366 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002367
2368 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2369 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002370
2371 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2372 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2373 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2374 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002375 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002376 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2377 Buffer));
2378 }
2379
Douglas Gregor593b0c12010-09-23 18:47:53 +00002380 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2381 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002382}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002383
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002384int clang_reparseTranslationUnit(CXTranslationUnit TU,
2385 unsigned num_unsaved_files,
2386 struct CXUnsavedFile *unsaved_files,
2387 unsigned options) {
2388 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2389 options, 0 };
2390 llvm::CrashRecoveryContext CRC;
2391
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002392 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002393 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002394 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2395 return 1;
2396 }
2397
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002398
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002399 return RTUI.result;
2400}
2401
Douglas Gregordf95a132010-08-09 20:45:32 +00002402
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002403CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002404 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002405 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002406
Steve Naroff77accc12009-09-03 18:19:54 +00002407 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002408 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002409}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002410
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002411CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002412 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002413 return Result;
2414}
2415
Ted Kremenekfb480492010-01-13 21:46:36 +00002416} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002417
Ted Kremenekfb480492010-01-13 21:46:36 +00002418//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002419// CXSourceLocation and CXSourceRange Operations.
2420//===----------------------------------------------------------------------===//
2421
Douglas Gregorb9790342010-01-22 21:44:22 +00002422extern "C" {
2423CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002424 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002425 return Result;
2426}
2427
2428unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002429 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2430 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2431 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002432}
2433
2434CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2435 CXFile file,
2436 unsigned line,
2437 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002438 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002439 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002440
Douglas Gregorb9790342010-01-22 21:44:22 +00002441 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2442 SourceLocation SLoc
2443 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002444 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002445 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002446 if (SLoc.isInvalid()) return clang_getNullLocation();
2447
2448 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2449}
2450
2451CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2452 CXFile file,
2453 unsigned offset) {
2454 if (!tu || !file)
2455 return clang_getNullLocation();
2456
2457 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2458 SourceLocation Start
2459 = CXXUnit->getSourceManager().getLocation(
2460 static_cast<const FileEntry *>(file),
2461 1, 1);
2462 if (Start.isInvalid()) return clang_getNullLocation();
2463
2464 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2465
2466 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002467
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002468 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002469}
2470
Douglas Gregor5352ac02010-01-28 00:27:43 +00002471CXSourceRange clang_getNullRange() {
2472 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2473 return Result;
2474}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002475
Douglas Gregor5352ac02010-01-28 00:27:43 +00002476CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2477 if (begin.ptr_data[0] != end.ptr_data[0] ||
2478 begin.ptr_data[1] != end.ptr_data[1])
2479 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002480
2481 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002482 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002483 return Result;
2484}
2485
Douglas Gregor46766dc2010-01-26 19:19:08 +00002486void clang_getInstantiationLocation(CXSourceLocation location,
2487 CXFile *file,
2488 unsigned *line,
2489 unsigned *column,
2490 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002491 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2492
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002493 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002494 if (file)
2495 *file = 0;
2496 if (line)
2497 *line = 0;
2498 if (column)
2499 *column = 0;
2500 if (offset)
2501 *offset = 0;
2502 return;
2503 }
2504
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002505 const SourceManager &SM =
2506 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002507 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002508
2509 if (file)
2510 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2511 if (line)
2512 *line = SM.getInstantiationLineNumber(InstLoc);
2513 if (column)
2514 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002515 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002516 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002517}
2518
Douglas Gregora9b06d42010-11-09 06:24:54 +00002519void clang_getSpellingLocation(CXSourceLocation location,
2520 CXFile *file,
2521 unsigned *line,
2522 unsigned *column,
2523 unsigned *offset) {
2524 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2525
2526 if (!location.ptr_data[0] || Loc.isInvalid()) {
2527 if (file)
2528 *file = 0;
2529 if (line)
2530 *line = 0;
2531 if (column)
2532 *column = 0;
2533 if (offset)
2534 *offset = 0;
2535 return;
2536 }
2537
2538 const SourceManager &SM =
2539 *static_cast<const SourceManager*>(location.ptr_data[0]);
2540 SourceLocation SpellLoc = Loc;
2541 if (SpellLoc.isMacroID()) {
2542 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2543 if (SimpleSpellingLoc.isFileID() &&
2544 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2545 SpellLoc = SimpleSpellingLoc;
2546 else
2547 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2548 }
2549
2550 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2551 FileID FID = LocInfo.first;
2552 unsigned FileOffset = LocInfo.second;
2553
2554 if (file)
2555 *file = (void *)SM.getFileEntryForID(FID);
2556 if (line)
2557 *line = SM.getLineNumber(FID, FileOffset);
2558 if (column)
2559 *column = SM.getColumnNumber(FID, FileOffset);
2560 if (offset)
2561 *offset = FileOffset;
2562}
2563
Douglas Gregor1db19de2010-01-19 21:36:55 +00002564CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002565 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002566 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002567 return Result;
2568}
2569
2570CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002571 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002572 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002573 return Result;
2574}
2575
Douglas Gregorb9790342010-01-22 21:44:22 +00002576} // end: extern "C"
2577
Douglas Gregor1db19de2010-01-19 21:36:55 +00002578//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002579// CXFile Operations.
2580//===----------------------------------------------------------------------===//
2581
2582extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002583CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002584 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002585 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002586
Steve Naroff88145032009-10-27 14:35:18 +00002587 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002588 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002589}
2590
2591time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002592 if (!SFile)
2593 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002594
Steve Naroff88145032009-10-27 14:35:18 +00002595 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2596 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002597}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Douglas Gregorb9790342010-01-22 21:44:22 +00002599CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2600 if (!tu)
2601 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002602
Douglas Gregorb9790342010-01-22 21:44:22 +00002603 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002604
Douglas Gregorb9790342010-01-22 21:44:22 +00002605 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002606 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2607 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002608 return const_cast<FileEntry *>(File);
2609}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002610
Ted Kremenekfb480492010-01-13 21:46:36 +00002611} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002612
Ted Kremenekfb480492010-01-13 21:46:36 +00002613//===----------------------------------------------------------------------===//
2614// CXCursor Operations.
2615//===----------------------------------------------------------------------===//
2616
Ted Kremenekfb480492010-01-13 21:46:36 +00002617static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002618 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2619 return getDeclFromExpr(CE->getSubExpr());
2620
Ted Kremenekfb480492010-01-13 21:46:36 +00002621 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2622 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002623 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2624 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002625 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2626 return ME->getMemberDecl();
2627 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2628 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002629 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2630 return PRE->getProperty();
2631
Ted Kremenekfb480492010-01-13 21:46:36 +00002632 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2633 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002634 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2635 if (!CE->isElidable())
2636 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002637 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2638 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002639
Douglas Gregordb1314e2010-10-01 21:11:22 +00002640 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2641 return PE->getProtocol();
2642
Ted Kremenekfb480492010-01-13 21:46:36 +00002643 return 0;
2644}
2645
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002646static SourceLocation getLocationFromExpr(Expr *E) {
2647 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2648 return /*FIXME:*/Msg->getLeftLoc();
2649 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2650 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002651 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2652 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002653 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2654 return Member->getMemberLoc();
2655 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2656 return Ivar->getLocation();
2657 return E->getLocStart();
2658}
2659
Ted Kremenekfb480492010-01-13 21:46:36 +00002660extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002661
2662unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002663 CXCursorVisitor visitor,
2664 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002665 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002666
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002667 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2668 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002669 return CursorVis.VisitChildren(parent);
2670}
2671
David Chisnall3387c652010-11-03 14:12:26 +00002672#ifndef __has_feature
2673#define __has_feature(x) 0
2674#endif
2675#if __has_feature(blocks)
2676typedef enum CXChildVisitResult
2677 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2678
2679static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2680 CXClientData client_data) {
2681 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2682 return block(cursor, parent);
2683}
2684#else
2685// If we are compiled with a compiler that doesn't have native blocks support,
2686// define and call the block manually, so the
2687typedef struct _CXChildVisitResult
2688{
2689 void *isa;
2690 int flags;
2691 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002692 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2693 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002694} *CXCursorVisitorBlock;
2695
2696static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2697 CXClientData client_data) {
2698 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2699 return block->invoke(block, cursor, parent);
2700}
2701#endif
2702
2703
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002704unsigned clang_visitChildrenWithBlock(CXCursor parent,
2705 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002706 return clang_visitChildren(parent, visitWithBlock, block);
2707}
2708
Douglas Gregor78205d42010-01-20 21:45:58 +00002709static CXString getDeclSpelling(Decl *D) {
2710 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2711 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002712 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002713
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))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002735 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002736
Steve Narofff334b4e2009-09-02 18:26:48 +00002737 if (clang_isReference(C.kind)) {
2738 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002739 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002740 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002741 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002742 }
2743 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002744 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002745 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002746 }
2747 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002748 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002749 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002750 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002751 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002752 case CXCursor_CXXBaseSpecifier: {
2753 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2754 return createCXString(B->getType().getAsString());
2755 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002756 case CXCursor_TypeRef: {
2757 TypeDecl *Type = getCursorTypeRef(C).first;
2758 assert(Type && "Missing type decl");
2759
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002760 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2761 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002762 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002763 case CXCursor_TemplateRef: {
2764 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002765 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002766
2767 return createCXString(Template->getNameAsString());
2768 }
Douglas Gregor69319002010-08-31 23:48:11 +00002769
2770 case CXCursor_NamespaceRef: {
2771 NamedDecl *NS = getCursorNamespaceRef(C).first;
2772 assert(NS && "Missing namespace decl");
2773
2774 return createCXString(NS->getNameAsString());
2775 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002776
Douglas Gregora67e03f2010-09-09 21:42:20 +00002777 case CXCursor_MemberRef: {
2778 FieldDecl *Field = getCursorMemberRef(C).first;
2779 assert(Field && "Missing member decl");
2780
2781 return createCXString(Field->getNameAsString());
2782 }
2783
Douglas Gregor36897b02010-09-10 00:22:18 +00002784 case CXCursor_LabelRef: {
2785 LabelStmt *Label = getCursorLabelRef(C).first;
2786 assert(Label && "Missing label");
2787
2788 return createCXString(Label->getID()->getName());
2789 }
2790
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002791 case CXCursor_OverloadedDeclRef: {
2792 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2793 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2794 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2795 return createCXString(ND->getNameAsString());
2796 return createCXString("");
2797 }
2798 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2799 return createCXString(E->getName().getAsString());
2800 OverloadedTemplateStorage *Ovl
2801 = Storage.get<OverloadedTemplateStorage*>();
2802 if (Ovl->size() == 0)
2803 return createCXString("");
2804 return createCXString((*Ovl->begin())->getNameAsString());
2805 }
2806
Daniel Dunbaracca7252009-11-30 20:42:49 +00002807 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002808 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002809 }
2810 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002811
2812 if (clang_isExpression(C.kind)) {
2813 Decl *D = getDeclFromExpr(getCursorExpr(C));
2814 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002815 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002816 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002817 }
2818
Douglas Gregor36897b02010-09-10 00:22:18 +00002819 if (clang_isStatement(C.kind)) {
2820 Stmt *S = getCursorStmt(C);
2821 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2822 return createCXString(Label->getID()->getName());
2823
2824 return createCXString("");
2825 }
2826
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002827 if (C.kind == CXCursor_MacroInstantiation)
2828 return createCXString(getCursorMacroInstantiation(C)->getName()
2829 ->getNameStart());
2830
Douglas Gregor572feb22010-03-18 18:04:21 +00002831 if (C.kind == CXCursor_MacroDefinition)
2832 return createCXString(getCursorMacroDefinition(C)->getName()
2833 ->getNameStart());
2834
Douglas Gregorecdcb882010-10-20 22:00:55 +00002835 if (C.kind == CXCursor_InclusionDirective)
2836 return createCXString(getCursorInclusionDirective(C)->getFileName());
2837
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002838 if (clang_isDeclaration(C.kind))
2839 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002840
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002841 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002842}
2843
Douglas Gregor358559d2010-10-02 22:49:11 +00002844CXString clang_getCursorDisplayName(CXCursor C) {
2845 if (!clang_isDeclaration(C.kind))
2846 return clang_getCursorSpelling(C);
2847
2848 Decl *D = getCursorDecl(C);
2849 if (!D)
2850 return createCXString("");
2851
2852 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2853 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2854 D = FunTmpl->getTemplatedDecl();
2855
2856 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2857 llvm::SmallString<64> Str;
2858 llvm::raw_svector_ostream OS(Str);
2859 OS << Function->getNameAsString();
2860 if (Function->getPrimaryTemplate())
2861 OS << "<>";
2862 OS << "(";
2863 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2864 if (I)
2865 OS << ", ";
2866 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2867 }
2868
2869 if (Function->isVariadic()) {
2870 if (Function->getNumParams())
2871 OS << ", ";
2872 OS << "...";
2873 }
2874 OS << ")";
2875 return createCXString(OS.str());
2876 }
2877
2878 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2879 llvm::SmallString<64> Str;
2880 llvm::raw_svector_ostream OS(Str);
2881 OS << ClassTemplate->getNameAsString();
2882 OS << "<";
2883 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2884 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2885 if (I)
2886 OS << ", ";
2887
2888 NamedDecl *Param = Params->getParam(I);
2889 if (Param->getIdentifier()) {
2890 OS << Param->getIdentifier()->getName();
2891 continue;
2892 }
2893
2894 // There is no parameter name, which makes this tricky. Try to come up
2895 // with something useful that isn't too long.
2896 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2897 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2898 else if (NonTypeTemplateParmDecl *NTTP
2899 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2900 OS << NTTP->getType().getAsString(Policy);
2901 else
2902 OS << "template<...> class";
2903 }
2904
2905 OS << ">";
2906 return createCXString(OS.str());
2907 }
2908
2909 if (ClassTemplateSpecializationDecl *ClassSpec
2910 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2911 // If the type was explicitly written, use that.
2912 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2913 return createCXString(TSInfo->getType().getAsString(Policy));
2914
2915 llvm::SmallString<64> Str;
2916 llvm::raw_svector_ostream OS(Str);
2917 OS << ClassSpec->getNameAsString();
2918 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002919 ClassSpec->getTemplateArgs().data(),
2920 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002921 Policy);
2922 return createCXString(OS.str());
2923 }
2924
2925 return clang_getCursorSpelling(C);
2926}
2927
Ted Kremeneke68fff62010-02-17 00:41:32 +00002928CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002929 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002930 case CXCursor_FunctionDecl:
2931 return createCXString("FunctionDecl");
2932 case CXCursor_TypedefDecl:
2933 return createCXString("TypedefDecl");
2934 case CXCursor_EnumDecl:
2935 return createCXString("EnumDecl");
2936 case CXCursor_EnumConstantDecl:
2937 return createCXString("EnumConstantDecl");
2938 case CXCursor_StructDecl:
2939 return createCXString("StructDecl");
2940 case CXCursor_UnionDecl:
2941 return createCXString("UnionDecl");
2942 case CXCursor_ClassDecl:
2943 return createCXString("ClassDecl");
2944 case CXCursor_FieldDecl:
2945 return createCXString("FieldDecl");
2946 case CXCursor_VarDecl:
2947 return createCXString("VarDecl");
2948 case CXCursor_ParmDecl:
2949 return createCXString("ParmDecl");
2950 case CXCursor_ObjCInterfaceDecl:
2951 return createCXString("ObjCInterfaceDecl");
2952 case CXCursor_ObjCCategoryDecl:
2953 return createCXString("ObjCCategoryDecl");
2954 case CXCursor_ObjCProtocolDecl:
2955 return createCXString("ObjCProtocolDecl");
2956 case CXCursor_ObjCPropertyDecl:
2957 return createCXString("ObjCPropertyDecl");
2958 case CXCursor_ObjCIvarDecl:
2959 return createCXString("ObjCIvarDecl");
2960 case CXCursor_ObjCInstanceMethodDecl:
2961 return createCXString("ObjCInstanceMethodDecl");
2962 case CXCursor_ObjCClassMethodDecl:
2963 return createCXString("ObjCClassMethodDecl");
2964 case CXCursor_ObjCImplementationDecl:
2965 return createCXString("ObjCImplementationDecl");
2966 case CXCursor_ObjCCategoryImplDecl:
2967 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002968 case CXCursor_CXXMethod:
2969 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002970 case CXCursor_UnexposedDecl:
2971 return createCXString("UnexposedDecl");
2972 case CXCursor_ObjCSuperClassRef:
2973 return createCXString("ObjCSuperClassRef");
2974 case CXCursor_ObjCProtocolRef:
2975 return createCXString("ObjCProtocolRef");
2976 case CXCursor_ObjCClassRef:
2977 return createCXString("ObjCClassRef");
2978 case CXCursor_TypeRef:
2979 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002980 case CXCursor_TemplateRef:
2981 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002982 case CXCursor_NamespaceRef:
2983 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002984 case CXCursor_MemberRef:
2985 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002986 case CXCursor_LabelRef:
2987 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002988 case CXCursor_OverloadedDeclRef:
2989 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002990 case CXCursor_UnexposedExpr:
2991 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002992 case CXCursor_BlockExpr:
2993 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002994 case CXCursor_DeclRefExpr:
2995 return createCXString("DeclRefExpr");
2996 case CXCursor_MemberRefExpr:
2997 return createCXString("MemberRefExpr");
2998 case CXCursor_CallExpr:
2999 return createCXString("CallExpr");
3000 case CXCursor_ObjCMessageExpr:
3001 return createCXString("ObjCMessageExpr");
3002 case CXCursor_UnexposedStmt:
3003 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003004 case CXCursor_LabelStmt:
3005 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003006 case CXCursor_InvalidFile:
3007 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003008 case CXCursor_InvalidCode:
3009 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003010 case CXCursor_NoDeclFound:
3011 return createCXString("NoDeclFound");
3012 case CXCursor_NotImplemented:
3013 return createCXString("NotImplemented");
3014 case CXCursor_TranslationUnit:
3015 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003016 case CXCursor_UnexposedAttr:
3017 return createCXString("UnexposedAttr");
3018 case CXCursor_IBActionAttr:
3019 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003020 case CXCursor_IBOutletAttr:
3021 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003022 case CXCursor_IBOutletCollectionAttr:
3023 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003024 case CXCursor_PreprocessingDirective:
3025 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003026 case CXCursor_MacroDefinition:
3027 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003028 case CXCursor_MacroInstantiation:
3029 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003030 case CXCursor_InclusionDirective:
3031 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003032 case CXCursor_Namespace:
3033 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003034 case CXCursor_LinkageSpec:
3035 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003036 case CXCursor_CXXBaseSpecifier:
3037 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003038 case CXCursor_Constructor:
3039 return createCXString("CXXConstructor");
3040 case CXCursor_Destructor:
3041 return createCXString("CXXDestructor");
3042 case CXCursor_ConversionFunction:
3043 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003044 case CXCursor_TemplateTypeParameter:
3045 return createCXString("TemplateTypeParameter");
3046 case CXCursor_NonTypeTemplateParameter:
3047 return createCXString("NonTypeTemplateParameter");
3048 case CXCursor_TemplateTemplateParameter:
3049 return createCXString("TemplateTemplateParameter");
3050 case CXCursor_FunctionTemplate:
3051 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003052 case CXCursor_ClassTemplate:
3053 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003054 case CXCursor_ClassTemplatePartialSpecialization:
3055 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003056 case CXCursor_NamespaceAlias:
3057 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003058 case CXCursor_UsingDirective:
3059 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003060 case CXCursor_UsingDeclaration:
3061 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003062 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003063
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003064 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003065 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003066}
Steve Naroff89922f82009-08-31 00:59:03 +00003067
Ted Kremeneke68fff62010-02-17 00:41:32 +00003068enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3069 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003070 CXClientData client_data) {
3071 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003072
3073 // If our current best cursor is the construction of a temporary object,
3074 // don't replace that cursor with a type reference, because we want
3075 // clang_getCursor() to point at the constructor.
3076 if (clang_isExpression(BestCursor->kind) &&
3077 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3078 cursor.kind == CXCursor_TypeRef)
3079 return CXChildVisit_Recurse;
3080
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003081 *BestCursor = cursor;
3082 return CXChildVisit_Recurse;
3083}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003084
Douglas Gregorb9790342010-01-22 21:44:22 +00003085CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3086 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003087 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003088
Douglas Gregorb9790342010-01-22 21:44:22 +00003089 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003090 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3091
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003092 // Translate the given source location to make it point at the beginning of
3093 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003094 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003095
3096 // Guard against an invalid SourceLocation, or we may assert in one
3097 // of the following calls.
3098 if (SLoc.isInvalid())
3099 return clang_getNullCursor();
3100
Douglas Gregor40749ee2010-11-03 00:35:38 +00003101 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003102 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3103 CXXUnit->getASTContext().getLangOptions());
3104
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003105 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3106 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003107 // FIXME: Would be great to have a "hint" cursor, then walk from that
3108 // hint cursor upward until we find a cursor whose source range encloses
3109 // the region of interest, rather than starting from the translation unit.
3110 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003111 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003112 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003113 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003114 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003115
3116 if (Logging) {
3117 CXFile SearchFile;
3118 unsigned SearchLine, SearchColumn;
3119 CXFile ResultFile;
3120 unsigned ResultLine, ResultColumn;
3121 CXString SearchFileName, ResultFileName, KindSpelling;
3122 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3123
3124 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3125 0);
3126 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3127 &ResultColumn, 0);
3128 SearchFileName = clang_getFileName(SearchFile);
3129 ResultFileName = clang_getFileName(ResultFile);
3130 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3131 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3132 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3133 clang_getCString(KindSpelling),
3134 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3135 clang_disposeString(SearchFileName);
3136 clang_disposeString(ResultFileName);
3137 clang_disposeString(KindSpelling);
3138 }
3139
Ted Kremeneke68fff62010-02-17 00:41:32 +00003140 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003141}
3142
Ted Kremenek73885552009-11-17 19:28:59 +00003143CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003144 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003145}
3146
3147unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003148 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003149}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003150
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003151unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003152 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3153}
3154
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003155unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003156 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3157}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003158
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003159unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003160 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3161}
3162
Douglas Gregor97b98722010-01-19 23:20:36 +00003163unsigned clang_isExpression(enum CXCursorKind K) {
3164 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3165}
3166
3167unsigned clang_isStatement(enum CXCursorKind K) {
3168 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3169}
3170
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003171unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3172 return K == CXCursor_TranslationUnit;
3173}
3174
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003175unsigned clang_isPreprocessing(enum CXCursorKind K) {
3176 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3177}
3178
Ted Kremenekad6eff62010-03-08 21:17:29 +00003179unsigned clang_isUnexposed(enum CXCursorKind K) {
3180 switch (K) {
3181 case CXCursor_UnexposedDecl:
3182 case CXCursor_UnexposedExpr:
3183 case CXCursor_UnexposedStmt:
3184 case CXCursor_UnexposedAttr:
3185 return true;
3186 default:
3187 return false;
3188 }
3189}
3190
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003191CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003192 return C.kind;
3193}
3194
Douglas Gregor98258af2010-01-18 22:46:11 +00003195CXSourceLocation clang_getCursorLocation(CXCursor C) {
3196 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003197 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003198 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003199 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3200 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003201 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003202 }
3203
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003204 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003205 std::pair<ObjCProtocolDecl *, SourceLocation> P
3206 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003207 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003208 }
3209
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003210 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003211 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3212 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003213 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003214 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003215
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003216 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003217 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003218 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003219 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003220
3221 case CXCursor_TemplateRef: {
3222 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3223 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3224 }
3225
Douglas Gregor69319002010-08-31 23:48:11 +00003226 case CXCursor_NamespaceRef: {
3227 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3228 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3229 }
3230
Douglas Gregora67e03f2010-09-09 21:42:20 +00003231 case CXCursor_MemberRef: {
3232 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3233 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3234 }
3235
Ted Kremenek3064ef92010-08-27 21:34:58 +00003236 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003237 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3238 if (!BaseSpec)
3239 return clang_getNullLocation();
3240
3241 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3242 return cxloc::translateSourceLocation(getCursorContext(C),
3243 TSInfo->getTypeLoc().getBeginLoc());
3244
3245 return cxloc::translateSourceLocation(getCursorContext(C),
3246 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003247 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003248
Douglas Gregor36897b02010-09-10 00:22:18 +00003249 case CXCursor_LabelRef: {
3250 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3251 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3252 }
3253
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003254 case CXCursor_OverloadedDeclRef:
3255 return cxloc::translateSourceLocation(getCursorContext(C),
3256 getCursorOverloadedDeclRef(C).second);
3257
Douglas Gregorf46034a2010-01-18 23:41:10 +00003258 default:
3259 // FIXME: Need a way to enumerate all non-reference cases.
3260 llvm_unreachable("Missed a reference kind");
3261 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003262 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003263
3264 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003265 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003266 getLocationFromExpr(getCursorExpr(C)));
3267
Douglas Gregor36897b02010-09-10 00:22:18 +00003268 if (clang_isStatement(C.kind))
3269 return cxloc::translateSourceLocation(getCursorContext(C),
3270 getCursorStmt(C)->getLocStart());
3271
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003272 if (C.kind == CXCursor_PreprocessingDirective) {
3273 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3274 return cxloc::translateSourceLocation(getCursorContext(C), L);
3275 }
Douglas Gregor48072312010-03-18 15:23:44 +00003276
3277 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003278 SourceLocation L
3279 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003280 return cxloc::translateSourceLocation(getCursorContext(C), L);
3281 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003282
3283 if (C.kind == CXCursor_MacroDefinition) {
3284 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3285 return cxloc::translateSourceLocation(getCursorContext(C), L);
3286 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003287
3288 if (C.kind == CXCursor_InclusionDirective) {
3289 SourceLocation L
3290 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3291 return cxloc::translateSourceLocation(getCursorContext(C), L);
3292 }
3293
Ted Kremenek9a700d22010-05-12 06:16:13 +00003294 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003295 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003296
Douglas Gregorf46034a2010-01-18 23:41:10 +00003297 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003298 SourceLocation Loc = D->getLocation();
3299 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3300 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003301 // FIXME: Multiple variables declared in a single declaration
3302 // currently lack the information needed to correctly determine their
3303 // ranges when accounting for the type-specifier. We use context
3304 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3305 // and if so, whether it is the first decl.
3306 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3307 if (!cxcursor::isFirstInDeclGroup(C))
3308 Loc = VD->getLocation();
3309 }
3310
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003311 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003312}
Douglas Gregora7bde202010-01-19 00:34:46 +00003313
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003314} // end extern "C"
3315
3316static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003317 if (clang_isReference(C.kind)) {
3318 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003319 case CXCursor_ObjCSuperClassRef:
3320 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003321
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003322 case CXCursor_ObjCProtocolRef:
3323 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003324
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003325 case CXCursor_ObjCClassRef:
3326 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003327
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003328 case CXCursor_TypeRef:
3329 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003330
3331 case CXCursor_TemplateRef:
3332 return getCursorTemplateRef(C).second;
3333
Douglas Gregor69319002010-08-31 23:48:11 +00003334 case CXCursor_NamespaceRef:
3335 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003336
3337 case CXCursor_MemberRef:
3338 return getCursorMemberRef(C).second;
3339
Ted Kremenek3064ef92010-08-27 21:34:58 +00003340 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003341 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003342
Douglas Gregor36897b02010-09-10 00:22:18 +00003343 case CXCursor_LabelRef:
3344 return getCursorLabelRef(C).second;
3345
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003346 case CXCursor_OverloadedDeclRef:
3347 return getCursorOverloadedDeclRef(C).second;
3348
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003349 default:
3350 // FIXME: Need a way to enumerate all non-reference cases.
3351 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003352 }
3353 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003354
3355 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003356 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003357
3358 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003359 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003360
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003361 if (C.kind == CXCursor_PreprocessingDirective)
3362 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003363
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003364 if (C.kind == CXCursor_MacroInstantiation)
3365 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003366
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003367 if (C.kind == CXCursor_MacroDefinition)
3368 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003369
3370 if (C.kind == CXCursor_InclusionDirective)
3371 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3372
Ted Kremenek007a7c92010-11-01 23:26:51 +00003373 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3374 Decl *D = cxcursor::getCursorDecl(C);
3375 SourceRange R = D->getSourceRange();
3376 // FIXME: Multiple variables declared in a single declaration
3377 // currently lack the information needed to correctly determine their
3378 // ranges when accounting for the type-specifier. We use context
3379 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3380 // and if so, whether it is the first decl.
3381 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3382 if (!cxcursor::isFirstInDeclGroup(C))
3383 R.setBegin(VD->getLocation());
3384 }
3385 return R;
3386 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003387 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003388
3389extern "C" {
3390
3391CXSourceRange clang_getCursorExtent(CXCursor C) {
3392 SourceRange R = getRawCursorExtent(C);
3393 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003394 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003395
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003396 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003397}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003398
3399CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003400 if (clang_isInvalid(C.kind))
3401 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003402
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003403 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003404 if (clang_isDeclaration(C.kind)) {
3405 Decl *D = getCursorDecl(C);
3406 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3407 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3408 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3409 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3410 if (ObjCForwardProtocolDecl *Protocols
3411 = dyn_cast<ObjCForwardProtocolDecl>(D))
3412 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3413
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003414 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003415 }
3416
Douglas Gregor97b98722010-01-19 23:20:36 +00003417 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003418 Expr *E = getCursorExpr(C);
3419 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003420 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003421 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003422
3423 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3424 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3425
Douglas Gregor97b98722010-01-19 23:20:36 +00003426 return clang_getNullCursor();
3427 }
3428
Douglas Gregor36897b02010-09-10 00:22:18 +00003429 if (clang_isStatement(C.kind)) {
3430 Stmt *S = getCursorStmt(C);
3431 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3432 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3433 getCursorASTUnit(C));
3434
3435 return clang_getNullCursor();
3436 }
3437
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003438 if (C.kind == CXCursor_MacroInstantiation) {
3439 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3440 return MakeMacroDefinitionCursor(Def, CXXUnit);
3441 }
3442
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003443 if (!clang_isReference(C.kind))
3444 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003445
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003446 switch (C.kind) {
3447 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003448 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003449
3450 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003451 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003452
3453 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003454 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003455
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003457 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003458
3459 case CXCursor_TemplateRef:
3460 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3461
Douglas Gregor69319002010-08-31 23:48:11 +00003462 case CXCursor_NamespaceRef:
3463 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3464
Douglas Gregora67e03f2010-09-09 21:42:20 +00003465 case CXCursor_MemberRef:
3466 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3467
Ted Kremenek3064ef92010-08-27 21:34:58 +00003468 case CXCursor_CXXBaseSpecifier: {
3469 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3470 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3471 CXXUnit));
3472 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003473
Douglas Gregor36897b02010-09-10 00:22:18 +00003474 case CXCursor_LabelRef:
3475 // FIXME: We end up faking the "parent" declaration here because we
3476 // don't want to make CXCursor larger.
3477 return MakeCXCursor(getCursorLabelRef(C).first,
3478 CXXUnit->getASTContext().getTranslationUnitDecl(),
3479 CXXUnit);
3480
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003481 case CXCursor_OverloadedDeclRef:
3482 return C;
3483
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003484 default:
3485 // We would prefer to enumerate all non-reference cursor kinds here.
3486 llvm_unreachable("Unhandled reference cursor kind");
3487 break;
3488 }
3489 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003490
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003491 return clang_getNullCursor();
3492}
3493
Douglas Gregorb6998662010-01-19 19:34:47 +00003494CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003495 if (clang_isInvalid(C.kind))
3496 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003497
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003498 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003499
Douglas Gregorb6998662010-01-19 19:34:47 +00003500 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003501 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003502 C = clang_getCursorReferenced(C);
3503 WasReference = true;
3504 }
3505
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003506 if (C.kind == CXCursor_MacroInstantiation)
3507 return clang_getCursorReferenced(C);
3508
Douglas Gregorb6998662010-01-19 19:34:47 +00003509 if (!clang_isDeclaration(C.kind))
3510 return clang_getNullCursor();
3511
3512 Decl *D = getCursorDecl(C);
3513 if (!D)
3514 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003515
Douglas Gregorb6998662010-01-19 19:34:47 +00003516 switch (D->getKind()) {
3517 // Declaration kinds that don't really separate the notions of
3518 // declaration and definition.
3519 case Decl::Namespace:
3520 case Decl::Typedef:
3521 case Decl::TemplateTypeParm:
3522 case Decl::EnumConstant:
3523 case Decl::Field:
3524 case Decl::ObjCIvar:
3525 case Decl::ObjCAtDefsField:
3526 case Decl::ImplicitParam:
3527 case Decl::ParmVar:
3528 case Decl::NonTypeTemplateParm:
3529 case Decl::TemplateTemplateParm:
3530 case Decl::ObjCCategoryImpl:
3531 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003532 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003533 case Decl::LinkageSpec:
3534 case Decl::ObjCPropertyImpl:
3535 case Decl::FileScopeAsm:
3536 case Decl::StaticAssert:
3537 case Decl::Block:
3538 return C;
3539
3540 // Declaration kinds that don't make any sense here, but are
3541 // nonetheless harmless.
3542 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003543 break;
3544
3545 // Declaration kinds for which the definition is not resolvable.
3546 case Decl::UnresolvedUsingTypename:
3547 case Decl::UnresolvedUsingValue:
3548 break;
3549
3550 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003551 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3552 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003553
3554 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003555 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003556
3557 case Decl::Enum:
3558 case Decl::Record:
3559 case Decl::CXXRecord:
3560 case Decl::ClassTemplateSpecialization:
3561 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003562 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003563 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003564 return clang_getNullCursor();
3565
3566 case Decl::Function:
3567 case Decl::CXXMethod:
3568 case Decl::CXXConstructor:
3569 case Decl::CXXDestructor:
3570 case Decl::CXXConversion: {
3571 const FunctionDecl *Def = 0;
3572 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003573 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003574 return clang_getNullCursor();
3575 }
3576
3577 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003578 // Ask the variable if it has a definition.
3579 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3580 return MakeCXCursor(Def, CXXUnit);
3581 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003582 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003583
Douglas Gregorb6998662010-01-19 19:34:47 +00003584 case Decl::FunctionTemplate: {
3585 const FunctionDecl *Def = 0;
3586 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003587 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003588 return clang_getNullCursor();
3589 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003590
Douglas Gregorb6998662010-01-19 19:34:47 +00003591 case Decl::ClassTemplate: {
3592 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003593 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003594 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003595 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003596 return clang_getNullCursor();
3597 }
3598
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003599 case Decl::Using:
3600 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3601 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003602
3603 case Decl::UsingShadow:
3604 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003605 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003606 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003607
3608 case Decl::ObjCMethod: {
3609 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3610 if (Method->isThisDeclarationADefinition())
3611 return C;
3612
3613 // Dig out the method definition in the associated
3614 // @implementation, if we have it.
3615 // FIXME: The ASTs should make finding the definition easier.
3616 if (ObjCInterfaceDecl *Class
3617 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3618 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3619 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3620 Method->isInstanceMethod()))
3621 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003622 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003623
3624 return clang_getNullCursor();
3625 }
3626
3627 case Decl::ObjCCategory:
3628 if (ObjCCategoryImplDecl *Impl
3629 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003630 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003631 return clang_getNullCursor();
3632
3633 case Decl::ObjCProtocol:
3634 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3635 return C;
3636 return clang_getNullCursor();
3637
3638 case Decl::ObjCInterface:
3639 // There are two notions of a "definition" for an Objective-C
3640 // class: the interface and its implementation. When we resolved a
3641 // reference to an Objective-C class, produce the @interface as
3642 // the definition; when we were provided with the interface,
3643 // produce the @implementation as the definition.
3644 if (WasReference) {
3645 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3646 return C;
3647 } else if (ObjCImplementationDecl *Impl
3648 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003649 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003650 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003651
Douglas Gregorb6998662010-01-19 19:34:47 +00003652 case Decl::ObjCProperty:
3653 // FIXME: We don't really know where to find the
3654 // ObjCPropertyImplDecls that implement this property.
3655 return clang_getNullCursor();
3656
3657 case Decl::ObjCCompatibleAlias:
3658 if (ObjCInterfaceDecl *Class
3659 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3660 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003661 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003662
Douglas Gregorb6998662010-01-19 19:34:47 +00003663 return clang_getNullCursor();
3664
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003665 case Decl::ObjCForwardProtocol:
3666 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3667 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003668
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003669 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003670 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003671 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003672
3673 case Decl::Friend:
3674 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003675 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003676 return clang_getNullCursor();
3677
3678 case Decl::FriendTemplate:
3679 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003680 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003681 return clang_getNullCursor();
3682 }
3683
3684 return clang_getNullCursor();
3685}
3686
3687unsigned clang_isCursorDefinition(CXCursor C) {
3688 if (!clang_isDeclaration(C.kind))
3689 return 0;
3690
3691 return clang_getCursorDefinition(C) == C;
3692}
3693
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003694unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003695 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003696 return 0;
3697
3698 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3699 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3700 return E->getNumDecls();
3701
3702 if (OverloadedTemplateStorage *S
3703 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3704 return S->size();
3705
3706 Decl *D = Storage.get<Decl*>();
3707 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003708 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003709 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3710 return Classes->size();
3711 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3712 return Protocols->protocol_size();
3713
3714 return 0;
3715}
3716
3717CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003718 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003719 return clang_getNullCursor();
3720
3721 if (index >= clang_getNumOverloadedDecls(cursor))
3722 return clang_getNullCursor();
3723
3724 ASTUnit *Unit = getCursorASTUnit(cursor);
3725 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3726 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3727 return MakeCXCursor(E->decls_begin()[index], Unit);
3728
3729 if (OverloadedTemplateStorage *S
3730 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3731 return MakeCXCursor(S->begin()[index], Unit);
3732
3733 Decl *D = Storage.get<Decl*>();
3734 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3735 // FIXME: This is, unfortunately, linear time.
3736 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3737 std::advance(Pos, index);
3738 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3739 }
3740
3741 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3742 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3743
3744 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3745 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3746
3747 return clang_getNullCursor();
3748}
3749
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003750void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003751 const char **startBuf,
3752 const char **endBuf,
3753 unsigned *startLine,
3754 unsigned *startColumn,
3755 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003756 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003757 assert(getCursorDecl(C) && "CXCursor has null decl");
3758 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003759 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3760 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003761
Steve Naroff4ade6d62009-09-23 17:52:52 +00003762 SourceManager &SM = FD->getASTContext().getSourceManager();
3763 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3764 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3765 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3766 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3767 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3768 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3769}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003770
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003771void clang_enableStackTraces(void) {
3772 llvm::sys::PrintStackTraceOnErrorSignal();
3773}
3774
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003775void clang_executeOnThread(void (*fn)(void*), void *user_data,
3776 unsigned stack_size) {
3777 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3778}
3779
Ted Kremenekfb480492010-01-13 21:46:36 +00003780} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003781
Ted Kremenekfb480492010-01-13 21:46:36 +00003782//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003783// Token-based Operations.
3784//===----------------------------------------------------------------------===//
3785
3786/* CXToken layout:
3787 * int_data[0]: a CXTokenKind
3788 * int_data[1]: starting token location
3789 * int_data[2]: token length
3790 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003791 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003792 * otherwise unused.
3793 */
3794extern "C" {
3795
3796CXTokenKind clang_getTokenKind(CXToken CXTok) {
3797 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3798}
3799
3800CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3801 switch (clang_getTokenKind(CXTok)) {
3802 case CXToken_Identifier:
3803 case CXToken_Keyword:
3804 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003805 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3806 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807
3808 case CXToken_Literal: {
3809 // We have stashed the starting pointer in the ptr_data field. Use it.
3810 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003811 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003812 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003813
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003814 case CXToken_Punctuation:
3815 case CXToken_Comment:
3816 break;
3817 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003818
3819 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820 // deconstructing the source location.
3821 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3822 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003823 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003824
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003825 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3826 std::pair<FileID, unsigned> LocInfo
3827 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003828 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003829 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003830 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3831 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003832 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003833
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003834 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003835}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3838 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3839 if (!CXXUnit)
3840 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003841
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003842 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3843 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3844}
3845
3846CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3847 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003848 if (!CXXUnit)
3849 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003850
3851 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003852 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3853}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003854
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3856 CXToken **Tokens, unsigned *NumTokens) {
3857 if (Tokens)
3858 *Tokens = 0;
3859 if (NumTokens)
3860 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003861
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003862 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3863 if (!CXXUnit || !Tokens || !NumTokens)
3864 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003865
Douglas Gregorbdf60622010-03-05 21:16:25 +00003866 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3867
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003868 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003869 if (R.isInvalid())
3870 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003871
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003872 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3873 std::pair<FileID, unsigned> BeginLocInfo
3874 = SourceMgr.getDecomposedLoc(R.getBegin());
3875 std::pair<FileID, unsigned> EndLocInfo
3876 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003877
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 // Cannot tokenize across files.
3879 if (BeginLocInfo.first != EndLocInfo.first)
3880 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003881
3882 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003883 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003884 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003885 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003886 if (Invalid)
3887 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003888
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003889 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3890 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003891 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003892 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003893
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003895 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003896 llvm::SmallVector<CXToken, 32> CXTokens;
3897 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003898 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003899 do {
3900 // Lex the next token
3901 Lex.LexFromRawLexer(Tok);
3902 if (Tok.is(tok::eof))
3903 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003904
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003905 // Initialize the CXToken.
3906 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003907
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003908 // - Common fields
3909 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3910 CXTok.int_data[2] = Tok.getLength();
3911 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003912
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003913 // - Kind-specific fields
3914 if (Tok.isLiteral()) {
3915 CXTok.int_data[0] = CXToken_Literal;
3916 CXTok.ptr_data = (void *)Tok.getLiteralData();
3917 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003918 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003919 std::pair<FileID, unsigned> LocInfo
3920 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003921 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003922 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003923 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3924 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003925 return;
3926
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003927 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003928 IdentifierInfo *II
3929 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003930
David Chisnall096428b2010-10-13 21:44:48 +00003931 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003932 CXTok.int_data[0] = CXToken_Keyword;
3933 }
3934 else {
3935 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3936 CXToken_Identifier
3937 : CXToken_Keyword;
3938 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003939 CXTok.ptr_data = II;
3940 } else if (Tok.is(tok::comment)) {
3941 CXTok.int_data[0] = CXToken_Comment;
3942 CXTok.ptr_data = 0;
3943 } else {
3944 CXTok.int_data[0] = CXToken_Punctuation;
3945 CXTok.ptr_data = 0;
3946 }
3947 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003948 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003949 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003950
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003951 if (CXTokens.empty())
3952 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003953
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003954 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3955 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3956 *NumTokens = CXTokens.size();
3957}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003958
Ted Kremenek6db61092010-05-05 00:55:15 +00003959void clang_disposeTokens(CXTranslationUnit TU,
3960 CXToken *Tokens, unsigned NumTokens) {
3961 free(Tokens);
3962}
3963
3964} // end: extern "C"
3965
3966//===----------------------------------------------------------------------===//
3967// Token annotation APIs.
3968//===----------------------------------------------------------------------===//
3969
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003970typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003971static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3972 CXCursor parent,
3973 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003974namespace {
3975class AnnotateTokensWorker {
3976 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003977 CXToken *Tokens;
3978 CXCursor *Cursors;
3979 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003980 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003981 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003982 CursorVisitor AnnotateVis;
3983 SourceManager &SrcMgr;
3984
3985 bool MoreTokens() const { return TokIdx < NumTokens; }
3986 unsigned NextToken() const { return TokIdx; }
3987 void AdvanceToken() { ++TokIdx; }
3988 SourceLocation GetTokenLoc(unsigned tokI) {
3989 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3990 }
3991
Ted Kremenek6db61092010-05-05 00:55:15 +00003992public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003993 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003994 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3995 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003996 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003997 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003998 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3999 Decl::MaxPCHLevel, RegionOfInterest),
4000 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004001
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004002 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004003 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004005 void AnnotateTokens() {
4006 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
4007 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004008};
4009}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004010
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004011void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4012 // Walk the AST within the region of interest, annotating tokens
4013 // along the way.
4014 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004015
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004016 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4017 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004018 if (Pos != Annotated.end() &&
4019 (clang_isInvalid(Cursors[I].kind) ||
4020 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004021 Cursors[I] = Pos->second;
4022 }
4023
4024 // Finish up annotating any tokens left.
4025 if (!MoreTokens())
4026 return;
4027
4028 const CXCursor &C = clang_getNullCursor();
4029 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4030 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4031 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004032 }
4033}
4034
Ted Kremenek6db61092010-05-05 00:55:15 +00004035enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004036AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004037 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004038 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004039 if (cursorRange.isInvalid())
4040 return CXChildVisit_Recurse;
4041
Douglas Gregor4419b672010-10-21 06:10:04 +00004042 if (clang_isPreprocessing(cursor.kind)) {
4043 // For macro instantiations, just note where the beginning of the macro
4044 // instantiation occurs.
4045 if (cursor.kind == CXCursor_MacroInstantiation) {
4046 Annotated[Loc.int_data] = cursor;
4047 return CXChildVisit_Recurse;
4048 }
4049
Douglas Gregor4419b672010-10-21 06:10:04 +00004050 // Items in the preprocessing record are kept separate from items in
4051 // declarations, so we keep a separate token index.
4052 unsigned SavedTokIdx = TokIdx;
4053 TokIdx = PreprocessingTokIdx;
4054
4055 // Skip tokens up until we catch up to the beginning of the preprocessing
4056 // entry.
4057 while (MoreTokens()) {
4058 const unsigned I = NextToken();
4059 SourceLocation TokLoc = GetTokenLoc(I);
4060 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4061 case RangeBefore:
4062 AdvanceToken();
4063 continue;
4064 case RangeAfter:
4065 case RangeOverlap:
4066 break;
4067 }
4068 break;
4069 }
4070
4071 // Look at all of the tokens within this range.
4072 while (MoreTokens()) {
4073 const unsigned I = NextToken();
4074 SourceLocation TokLoc = GetTokenLoc(I);
4075 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4076 case RangeBefore:
4077 assert(0 && "Infeasible");
4078 case RangeAfter:
4079 break;
4080 case RangeOverlap:
4081 Cursors[I] = cursor;
4082 AdvanceToken();
4083 continue;
4084 }
4085 break;
4086 }
4087
4088 // Save the preprocessing token index; restore the non-preprocessing
4089 // token index.
4090 PreprocessingTokIdx = TokIdx;
4091 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004092 return CXChildVisit_Recurse;
4093 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004094
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004095 if (cursorRange.isInvalid())
4096 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004097
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004098 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4099
Ted Kremeneka333c662010-05-12 05:29:33 +00004100 // Adjust the annotated range based specific declarations.
4101 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4102 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004103 Decl *D = cxcursor::getCursorDecl(cursor);
4104 // Don't visit synthesized ObjC methods, since they have no syntatic
4105 // representation in the source.
4106 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4107 if (MD->isSynthesized())
4108 return CXChildVisit_Continue;
4109 }
4110 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004111 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4112 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004113 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004114 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004115 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004116 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004117 }
4118 }
4119 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004120
Ted Kremenek3f404602010-08-14 01:14:06 +00004121 // If the location of the cursor occurs within a macro instantiation, record
4122 // the spelling location of the cursor in our annotation map. We can then
4123 // paper over the token labelings during a post-processing step to try and
4124 // get cursor mappings for tokens that are the *arguments* of a macro
4125 // instantiation.
4126 if (L.isMacroID()) {
4127 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4128 // Only invalidate the old annotation if it isn't part of a preprocessing
4129 // directive. Here we assume that the default construction of CXCursor
4130 // results in CXCursor.kind being an initialized value (i.e., 0). If
4131 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004132
Ted Kremenek3f404602010-08-14 01:14:06 +00004133 CXCursor &oldC = Annotated[rawEncoding];
4134 if (!clang_isPreprocessing(oldC.kind))
4135 oldC = cursor;
4136 }
4137
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004138 const enum CXCursorKind K = clang_getCursorKind(parent);
4139 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004140 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4141 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004142
4143 while (MoreTokens()) {
4144 const unsigned I = NextToken();
4145 SourceLocation TokLoc = GetTokenLoc(I);
4146 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4147 case RangeBefore:
4148 Cursors[I] = updateC;
4149 AdvanceToken();
4150 continue;
4151 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004152 case RangeOverlap:
4153 break;
4154 }
4155 break;
4156 }
4157
4158 // Visit children to get their cursor information.
4159 const unsigned BeforeChildren = NextToken();
4160 VisitChildren(cursor);
4161 const unsigned AfterChildren = NextToken();
4162
4163 // Adjust 'Last' to the last token within the extent of the cursor.
4164 while (MoreTokens()) {
4165 const unsigned I = NextToken();
4166 SourceLocation TokLoc = GetTokenLoc(I);
4167 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4168 case RangeBefore:
4169 assert(0 && "Infeasible");
4170 case RangeAfter:
4171 break;
4172 case RangeOverlap:
4173 Cursors[I] = updateC;
4174 AdvanceToken();
4175 continue;
4176 }
4177 break;
4178 }
4179 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004180
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004181 // Scan the tokens that are at the beginning of the cursor, but are not
4182 // capture by the child cursors.
4183
4184 // For AST elements within macros, rely on a post-annotate pass to
4185 // to correctly annotate the tokens with cursors. Otherwise we can
4186 // get confusing results of having tokens that map to cursors that really
4187 // are expanded by an instantiation.
4188 if (L.isMacroID())
4189 cursor = clang_getNullCursor();
4190
4191 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4192 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4193 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004194
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004195 Cursors[I] = cursor;
4196 }
4197 // Scan the tokens that are at the end of the cursor, but are not captured
4198 // but the child cursors.
4199 for (unsigned I = AfterChildren; I != Last; ++I)
4200 Cursors[I] = cursor;
4201
4202 TokIdx = Last;
4203 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004204}
4205
Ted Kremenek6db61092010-05-05 00:55:15 +00004206static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4207 CXCursor parent,
4208 CXClientData client_data) {
4209 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4210}
4211
Ted Kremenekab979612010-11-11 08:05:23 +00004212// This gets run a separate thread to avoid stack blowout.
4213static void runAnnotateTokensWorker(void *UserData) {
4214 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4215}
4216
Ted Kremenek6db61092010-05-05 00:55:15 +00004217extern "C" {
4218
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004219void clang_annotateTokens(CXTranslationUnit TU,
4220 CXToken *Tokens, unsigned NumTokens,
4221 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004222
4223 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004224 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004225
Douglas Gregor4419b672010-10-21 06:10:04 +00004226 // Any token we don't specifically annotate will have a NULL cursor.
4227 CXCursor C = clang_getNullCursor();
4228 for (unsigned I = 0; I != NumTokens; ++I)
4229 Cursors[I] = C;
4230
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004231 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004232 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004233 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004234
Douglas Gregorbdf60622010-03-05 21:16:25 +00004235 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004236
Douglas Gregor0396f462010-03-19 05:22:59 +00004237 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004238 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4240 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004241 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4242 clang_getTokenLocation(TU,
4243 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004244
Douglas Gregor0396f462010-03-19 05:22:59 +00004245 // A mapping from the source locations found when re-lexing or traversing the
4246 // region of interest to the corresponding cursors.
4247 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004248
4249 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004250 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004251 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4252 std::pair<FileID, unsigned> BeginLocInfo
4253 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4254 std::pair<FileID, unsigned> EndLocInfo
4255 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004256
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004257 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004258 bool Invalid = false;
4259 if (BeginLocInfo.first == EndLocInfo.first &&
4260 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4261 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004262 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4263 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004264 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004265 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004266 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004267
4268 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004269 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004270 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004271 Token Tok;
4272 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004273
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004274 reprocess:
4275 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4276 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004277 // don't see it while preprocessing these tokens later, but keep track
4278 // of all of the token locations inside this preprocessing directive so
4279 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004280 //
4281 // FIXME: Some simple tests here could identify macro definitions and
4282 // #undefs, to provide specific cursor kinds for those.
4283 std::vector<SourceLocation> Locations;
4284 do {
4285 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004286 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004287 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004288
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004289 using namespace cxcursor;
4290 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004291 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4292 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004293 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004294 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4295 Annotated[Locations[I].getRawEncoding()] = Cursor;
4296 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004297
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004298 if (Tok.isAtStartOfLine())
4299 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004300
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004301 continue;
4302 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004303
Douglas Gregor48072312010-03-18 15:23:44 +00004304 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004305 break;
4306 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004307 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004308
Douglas Gregor0396f462010-03-19 05:22:59 +00004309 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004310 // a specific cursor.
4311 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4312 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004313
4314 // Run the worker within a CrashRecoveryContext.
4315 llvm::CrashRecoveryContext CRC;
4316 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4317 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4318 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004319}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004320} // end: extern "C"
4321
4322//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004323// Operations for querying linkage of a cursor.
4324//===----------------------------------------------------------------------===//
4325
4326extern "C" {
4327CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004328 if (!clang_isDeclaration(cursor.kind))
4329 return CXLinkage_Invalid;
4330
Ted Kremenek16b42592010-03-03 06:36:57 +00004331 Decl *D = cxcursor::getCursorDecl(cursor);
4332 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4333 switch (ND->getLinkage()) {
4334 case NoLinkage: return CXLinkage_NoLinkage;
4335 case InternalLinkage: return CXLinkage_Internal;
4336 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4337 case ExternalLinkage: return CXLinkage_External;
4338 };
4339
4340 return CXLinkage_Invalid;
4341}
4342} // end: extern "C"
4343
4344//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004345// Operations for querying language of a cursor.
4346//===----------------------------------------------------------------------===//
4347
4348static CXLanguageKind getDeclLanguage(const Decl *D) {
4349 switch (D->getKind()) {
4350 default:
4351 break;
4352 case Decl::ImplicitParam:
4353 case Decl::ObjCAtDefsField:
4354 case Decl::ObjCCategory:
4355 case Decl::ObjCCategoryImpl:
4356 case Decl::ObjCClass:
4357 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004358 case Decl::ObjCForwardProtocol:
4359 case Decl::ObjCImplementation:
4360 case Decl::ObjCInterface:
4361 case Decl::ObjCIvar:
4362 case Decl::ObjCMethod:
4363 case Decl::ObjCProperty:
4364 case Decl::ObjCPropertyImpl:
4365 case Decl::ObjCProtocol:
4366 return CXLanguage_ObjC;
4367 case Decl::CXXConstructor:
4368 case Decl::CXXConversion:
4369 case Decl::CXXDestructor:
4370 case Decl::CXXMethod:
4371 case Decl::CXXRecord:
4372 case Decl::ClassTemplate:
4373 case Decl::ClassTemplatePartialSpecialization:
4374 case Decl::ClassTemplateSpecialization:
4375 case Decl::Friend:
4376 case Decl::FriendTemplate:
4377 case Decl::FunctionTemplate:
4378 case Decl::LinkageSpec:
4379 case Decl::Namespace:
4380 case Decl::NamespaceAlias:
4381 case Decl::NonTypeTemplateParm:
4382 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004383 case Decl::TemplateTemplateParm:
4384 case Decl::TemplateTypeParm:
4385 case Decl::UnresolvedUsingTypename:
4386 case Decl::UnresolvedUsingValue:
4387 case Decl::Using:
4388 case Decl::UsingDirective:
4389 case Decl::UsingShadow:
4390 return CXLanguage_CPlusPlus;
4391 }
4392
4393 return CXLanguage_C;
4394}
4395
4396extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004397
4398enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4399 if (clang_isDeclaration(cursor.kind))
4400 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4401 if (D->hasAttr<UnavailableAttr>() ||
4402 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4403 return CXAvailability_Available;
4404
4405 if (D->hasAttr<DeprecatedAttr>())
4406 return CXAvailability_Deprecated;
4407 }
4408
4409 return CXAvailability_Available;
4410}
4411
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004412CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4413 if (clang_isDeclaration(cursor.kind))
4414 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4415
4416 return CXLanguage_Invalid;
4417}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004418
4419CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4420 if (clang_isDeclaration(cursor.kind)) {
4421 if (Decl *D = getCursorDecl(cursor)) {
4422 DeclContext *DC = D->getDeclContext();
4423 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4424 }
4425 }
4426
4427 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4428 if (Decl *D = getCursorDecl(cursor))
4429 return MakeCXCursor(D, getCursorASTUnit(cursor));
4430 }
4431
4432 return clang_getNullCursor();
4433}
4434
4435CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4436 if (clang_isDeclaration(cursor.kind)) {
4437 if (Decl *D = getCursorDecl(cursor)) {
4438 DeclContext *DC = D->getLexicalDeclContext();
4439 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4440 }
4441 }
4442
4443 // FIXME: Note that we can't easily compute the lexical context of a
4444 // statement or expression, so we return nothing.
4445 return clang_getNullCursor();
4446}
4447
Douglas Gregor9f592342010-10-01 20:25:15 +00004448static void CollectOverriddenMethods(DeclContext *Ctx,
4449 ObjCMethodDecl *Method,
4450 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4451 if (!Ctx)
4452 return;
4453
4454 // If we have a class or category implementation, jump straight to the
4455 // interface.
4456 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4457 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4458
4459 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4460 if (!Container)
4461 return;
4462
4463 // Check whether we have a matching method at this level.
4464 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4465 Method->isInstanceMethod()))
4466 if (Method != Overridden) {
4467 // We found an override at this level; there is no need to look
4468 // into other protocols or categories.
4469 Methods.push_back(Overridden);
4470 return;
4471 }
4472
4473 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4474 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4475 PEnd = Protocol->protocol_end();
4476 P != PEnd; ++P)
4477 CollectOverriddenMethods(*P, Method, Methods);
4478 }
4479
4480 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4481 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4482 PEnd = Category->protocol_end();
4483 P != PEnd; ++P)
4484 CollectOverriddenMethods(*P, Method, Methods);
4485 }
4486
4487 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4488 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4489 PEnd = Interface->protocol_end();
4490 P != PEnd; ++P)
4491 CollectOverriddenMethods(*P, Method, Methods);
4492
4493 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4494 Category; Category = Category->getNextClassCategory())
4495 CollectOverriddenMethods(Category, Method, Methods);
4496
4497 // We only look into the superclass if we haven't found anything yet.
4498 if (Methods.empty())
4499 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4500 return CollectOverriddenMethods(Super, Method, Methods);
4501 }
4502}
4503
4504void clang_getOverriddenCursors(CXCursor cursor,
4505 CXCursor **overridden,
4506 unsigned *num_overridden) {
4507 if (overridden)
4508 *overridden = 0;
4509 if (num_overridden)
4510 *num_overridden = 0;
4511 if (!overridden || !num_overridden)
4512 return;
4513
4514 if (!clang_isDeclaration(cursor.kind))
4515 return;
4516
4517 Decl *D = getCursorDecl(cursor);
4518 if (!D)
4519 return;
4520
4521 // Handle C++ member functions.
4522 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4523 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4524 *num_overridden = CXXMethod->size_overridden_methods();
4525 if (!*num_overridden)
4526 return;
4527
4528 *overridden = new CXCursor [*num_overridden];
4529 unsigned I = 0;
4530 for (CXXMethodDecl::method_iterator
4531 M = CXXMethod->begin_overridden_methods(),
4532 MEnd = CXXMethod->end_overridden_methods();
4533 M != MEnd; (void)++M, ++I)
4534 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4535 return;
4536 }
4537
4538 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4539 if (!Method)
4540 return;
4541
4542 // Handle Objective-C methods.
4543 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4544 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4545
4546 if (Methods.empty())
4547 return;
4548
4549 *num_overridden = Methods.size();
4550 *overridden = new CXCursor [Methods.size()];
4551 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4552 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4553}
4554
4555void clang_disposeOverriddenCursors(CXCursor *overridden) {
4556 delete [] overridden;
4557}
4558
Douglas Gregorecdcb882010-10-20 22:00:55 +00004559CXFile clang_getIncludedFile(CXCursor cursor) {
4560 if (cursor.kind != CXCursor_InclusionDirective)
4561 return 0;
4562
4563 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4564 return (void *)ID->getFile();
4565}
4566
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004567} // end: extern "C"
4568
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004569
4570//===----------------------------------------------------------------------===//
4571// C++ AST instrospection.
4572//===----------------------------------------------------------------------===//
4573
4574extern "C" {
4575unsigned clang_CXXMethod_isStatic(CXCursor C) {
4576 if (!clang_isDeclaration(C.kind))
4577 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004578
4579 CXXMethodDecl *Method = 0;
4580 Decl *D = cxcursor::getCursorDecl(C);
4581 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4582 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4583 else
4584 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4585 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004586}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004587
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004588} // end: extern "C"
4589
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004590//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004591// Attribute introspection.
4592//===----------------------------------------------------------------------===//
4593
4594extern "C" {
4595CXType clang_getIBOutletCollectionType(CXCursor C) {
4596 if (C.kind != CXCursor_IBOutletCollectionAttr)
4597 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4598
4599 IBOutletCollectionAttr *A =
4600 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4601
4602 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4603}
4604} // end: extern "C"
4605
4606//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004607// CXString Operations.
4608//===----------------------------------------------------------------------===//
4609
4610extern "C" {
4611const char *clang_getCString(CXString string) {
4612 return string.Spelling;
4613}
4614
4615void clang_disposeString(CXString string) {
4616 if (string.MustFreeString && string.Spelling)
4617 free((void*)string.Spelling);
4618}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004619
Ted Kremenekfb480492010-01-13 21:46:36 +00004620} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004621
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004622namespace clang { namespace cxstring {
4623CXString createCXString(const char *String, bool DupString){
4624 CXString Str;
4625 if (DupString) {
4626 Str.Spelling = strdup(String);
4627 Str.MustFreeString = 1;
4628 } else {
4629 Str.Spelling = String;
4630 Str.MustFreeString = 0;
4631 }
4632 return Str;
4633}
4634
4635CXString createCXString(llvm::StringRef String, bool DupString) {
4636 CXString Result;
4637 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4638 char *Spelling = (char *)malloc(String.size() + 1);
4639 memmove(Spelling, String.data(), String.size());
4640 Spelling[String.size()] = 0;
4641 Result.Spelling = Spelling;
4642 Result.MustFreeString = 1;
4643 } else {
4644 Result.Spelling = String.data();
4645 Result.MustFreeString = 0;
4646 }
4647 return Result;
4648}
4649}}
4650
Ted Kremenek04bb7162010-01-22 22:44:15 +00004651//===----------------------------------------------------------------------===//
4652// Misc. utility functions.
4653//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004654
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004655/// Default to using an 8 MB stack size on "safety" threads.
4656static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004657
4658namespace clang {
4659
4660bool RunSafely(llvm::CrashRecoveryContext &CRC,
4661 void (*Fn)(void*), void *UserData) {
4662 if (unsigned Size = GetSafetyThreadStackSize())
4663 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4664 return CRC.RunSafely(Fn, UserData);
4665}
4666
4667unsigned GetSafetyThreadStackSize() {
4668 return SafetyStackThreadSize;
4669}
4670
4671void SetSafetyThreadStackSize(unsigned Value) {
4672 SafetyStackThreadSize = Value;
4673}
4674
4675}
4676
Ted Kremenek04bb7162010-01-22 22:44:15 +00004677extern "C" {
4678
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004679CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004680 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004681}
4682
4683} // end: extern "C"