blob: bbceea945fba76a388658d833c1769b9c389bd58 [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:
Ted Kremenekf1107452010-11-12 18:26:56 +0000129 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000130protected:
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
Ted Kremenekf1107452010-11-12 18:26:56 +0000151DEF_JOB(DeclVisit, Decl, DeclVisitKind)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000152DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
153DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000154#undef DEF_JOB
155
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000156static inline void WLAddStmt(VisitorWorkList &WL, CXCursor Parent, Stmt *S) {
157 if (S)
158 WL.push_back(StmtVisit(S, Parent));
159}
160static inline void WLAddDecl(VisitorWorkList &WL, CXCursor Parent, Decl *D) {
161 if (D)
162 WL.push_back(DeclVisit(D, Parent));
163}
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000167 public TypeLocVisitor<CursorVisitor, bool>,
168 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000169{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000171 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176 /// \brief The declaration that serves at the parent of any statement or
177 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000178 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000183 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000186 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
187 // to the visitor. Declarations with a PCH level greater than this value will
188 // be suppressed.
189 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190
191 /// \brief When valid, a source range to which the cursor should restrict
192 /// its search.
193 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000194
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000195 // FIXME: Eventually remove. This part of a hack to support proper
196 // iteration over all Decls contained lexically within an ObjC container.
197 DeclContext::decl_iterator *DI_current;
198 DeclContext::decl_iterator DE_current;
199
Douglas Gregorb1373d02010-01-20 20:59:29 +0000200 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000201 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000202 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000203
204 /// \brief Determine whether this particular source range comes before, comes
205 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000206 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000207 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000208 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
209
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000210 class SetParentRAII {
211 CXCursor &Parent;
212 Decl *&StmtParent;
213 CXCursor OldParent;
214
215 public:
216 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
217 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
218 {
219 Parent = NewParent;
220 if (clang_isDeclaration(Parent.kind))
221 StmtParent = getCursorDecl(Parent);
222 }
223
224 ~SetParentRAII() {
225 Parent = OldParent;
226 if (clang_isDeclaration(Parent.kind))
227 StmtParent = getCursorDecl(Parent);
228 }
229 };
230
Steve Naroff89922f82009-08-31 00:59:03 +0000231public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000232 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
233 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000234 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000236 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
237 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000238 {
239 Parent.kind = CXCursor_NoDeclFound;
240 Parent.data[0] = 0;
241 Parent.data[1] = 0;
242 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000243 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000244 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000245
Ted Kremenekab979612010-11-11 08:05:23 +0000246 ASTUnit *getASTUnit() const { return TU; }
247
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000248 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000249
250 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
251 getPreprocessedEntities();
252
Douglas Gregorb1373d02010-01-20 20:59:29 +0000253 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000254
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000255 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000256 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000257 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000258 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000259 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000260 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000261 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
262 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000263 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000264 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000265 bool VisitClassTemplatePartialSpecializationDecl(
266 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000267 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000268 bool VisitEnumConstantDecl(EnumConstantDecl *D);
269 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
270 bool VisitFunctionDecl(FunctionDecl *ND);
271 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000272 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000273 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000274 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000275 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000276 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000277 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
278 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
279 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
280 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000281 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000282 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
283 bool VisitObjCImplDecl(ObjCImplDecl *D);
284 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
285 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000286 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
287 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
288 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000289 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000290 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000291 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000292 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000293 bool VisitUsingDecl(UsingDecl *D);
294 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
295 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000296
Douglas Gregor01829d32010-08-31 14:41:23 +0000297 // Name visitor
298 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000299 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000300
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000301 // Template visitors
302 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000303 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000304 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
305
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000306 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000307 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000308 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000309 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000310 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
311 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000312 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000313 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000314 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000315 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
316 bool VisitPointerTypeLoc(PointerTypeLoc TL);
317 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
318 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
319 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
320 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000321 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000323 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000324 // FIXME: Implement visitors here when the unimplemented TypeLocs get
325 // implemented
326 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
327 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000328
Douglas Gregora59e3902010-01-21 23:27:09 +0000329 // Statement visitors
330 bool VisitStmt(Stmt *S);
331 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000332 bool VisitGotoStmt(GotoStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000333
Douglas Gregor336fd812010-01-23 00:40:08 +0000334 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000335 bool VisitDeclRefExpr(DeclRefExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000336 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000337 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000338 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000339 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000340 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000341 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000342 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000343 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000344 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
345 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000346 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000347 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000348 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000349 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000350 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
351 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000352 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000353 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000354 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000355 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000356 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000357 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000358 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000359 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000360
361#define DATA_RECURSIVE_VISIT(NAME)\
362bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
363 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000364 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000365 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000366 DATA_RECURSIVE_VISIT(DoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000367 DATA_RECURSIVE_VISIT(IfStmt)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000368 DATA_RECURSIVE_VISIT(InitListExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000369 DATA_RECURSIVE_VISIT(ForStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000370 DATA_RECURSIVE_VISIT(MemberExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000371 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekbb677132010-11-12 18:27:04 +0000372 DATA_RECURSIVE_VISIT(WhileStmt)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000373
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000374 // Data-recursive visitor functions.
375 bool IsInRegionOfInterest(CXCursor C);
376 bool RunVisitorWorkList(VisitorWorkList &WL);
377 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
378 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000379};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000380
Ted Kremenekab188932010-01-05 19:32:54 +0000381} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000382
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000383static SourceRange getRawCursorExtent(CXCursor C);
384
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000386 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
387}
388
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389/// \brief Visit the given cursor and, if requested by the visitor,
390/// its children.
391///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392/// \param Cursor the cursor to visit.
393///
394/// \param CheckRegionOfInterest if true, then the caller already checked that
395/// this cursor is within the region of interest.
396///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397/// \returns true if the visitation should be aborted, false if it
398/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000399bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 if (clang_isInvalid(Cursor.kind))
401 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403 if (clang_isDeclaration(Cursor.kind)) {
404 Decl *D = getCursorDecl(Cursor);
405 assert(D && "Invalid declaration cursor");
406 if (D->getPCHLevel() > MaxPCHLevel)
407 return false;
408
409 if (D->isImplicit())
410 return false;
411 }
412
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000413 // If we have a range of interest, and this cursor doesn't intersect with it,
414 // we're done.
415 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000416 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000417 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000418 return false;
419 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000420
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 switch (Visitor(Cursor, Parent, ClientData)) {
422 case CXChildVisit_Break:
423 return true;
424
425 case CXChildVisit_Continue:
426 return false;
427
428 case CXChildVisit_Recurse:
429 return VisitChildren(Cursor);
430 }
431
Douglas Gregorfd643772010-01-25 16:45:46 +0000432 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000433}
434
Douglas Gregor788f5a12010-03-20 00:41:21 +0000435std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
436CursorVisitor::getPreprocessedEntities() {
437 PreprocessingRecord &PPRec
438 = *TU->getPreprocessor().getPreprocessingRecord();
439
440 bool OnlyLocalDecls
441 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
442
443 // There is no region of interest; we have to walk everything.
444 if (RegionOfInterest.isInvalid())
445 return std::make_pair(PPRec.begin(OnlyLocalDecls),
446 PPRec.end(OnlyLocalDecls));
447
448 // Find the file in which the region of interest lands.
449 SourceManager &SM = TU->getSourceManager();
450 std::pair<FileID, unsigned> Begin
451 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
452 std::pair<FileID, unsigned> End
453 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
454
455 // The region of interest spans files; we have to walk everything.
456 if (Begin.first != End.first)
457 return std::make_pair(PPRec.begin(OnlyLocalDecls),
458 PPRec.end(OnlyLocalDecls));
459
460 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
461 = TU->getPreprocessedEntitiesByFile();
462 if (ByFileMap.empty()) {
463 // Build the mapping from files to sets of preprocessed entities.
464 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
465 EEnd = PPRec.end(OnlyLocalDecls);
466 E != EEnd; ++E) {
467 std::pair<FileID, unsigned> P
468 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
469 ByFileMap[P.first].push_back(*E);
470 }
471 }
472
473 return std::make_pair(ByFileMap[Begin.first].begin(),
474 ByFileMap[Begin.first].end());
475}
476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477/// \brief Visit the children of the given cursor.
478///
479/// \returns true if the visitation should be aborted, false if it
480/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000482 if (clang_isReference(Cursor.kind)) {
483 // By definition, references have no children.
484 return false;
485 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000486
487 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000489 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000490
Douglas Gregorb1373d02010-01-20 20:59:29 +0000491 if (clang_isDeclaration(Cursor.kind)) {
492 Decl *D = getCursorDecl(Cursor);
493 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000494 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000496
Douglas Gregora59e3902010-01-21 23:27:09 +0000497 if (clang_isStatement(Cursor.kind))
498 return Visit(getCursorStmt(Cursor));
499 if (clang_isExpression(Cursor.kind))
500 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000501
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000503 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000504 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
505 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000506 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
507 TLEnd = CXXUnit->top_level_end();
508 TL != TLEnd; ++TL) {
509 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000510 return true;
511 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 } else if (VisitDeclContext(
513 CXXUnit->getASTContext().getTranslationUnitDecl()))
514 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000515
Douglas Gregor0396f462010-03-19 05:22:59 +0000516 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000517 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 // FIXME: Once we have the ability to deserialize a preprocessing record,
519 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000520 PreprocessingRecord::iterator E, EEnd;
521 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000522 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
523 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
524 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000525
Douglas Gregor0396f462010-03-19 05:22:59 +0000526 continue;
527 }
528
529 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
530 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
531 return true;
532
533 continue;
534 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000535
536 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
537 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
538 return true;
539
540 continue;
541 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000542 }
543 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000544 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000545 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546
Douglas Gregorb1373d02010-01-20 20:59:29 +0000547 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000548 return false;
549}
550
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000551bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000552 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
553 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000554
Ted Kremenek664cffd2010-07-22 11:30:19 +0000555 if (Stmt *Body = B->getBody())
556 return Visit(MakeCXCursor(Body, StmtParent, TU));
557
558 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000559}
560
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000561llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
562 if (RegionOfInterest.isValid()) {
563 SourceRange Range = getRawCursorExtent(Cursor);
564 if (Range.isInvalid())
565 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000566
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000567 switch (CompareRegionOfInterest(Range)) {
568 case RangeBefore:
569 // This declaration comes before the region of interest; skip it.
570 return llvm::Optional<bool>();
571
572 case RangeAfter:
573 // This declaration comes after the region of interest; we're done.
574 return false;
575
576 case RangeOverlap:
577 // This declaration overlaps the region of interest; visit it.
578 break;
579 }
580 }
581 return true;
582}
583
584bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
585 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
586
587 // FIXME: Eventually remove. This part of a hack to support proper
588 // iteration over all Decls contained lexically within an ObjC container.
589 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
590 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
591
592 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000593 Decl *D = *I;
594 if (D->getLexicalDeclContext() != DC)
595 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000596 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000597 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
598 if (!V.hasValue())
599 continue;
600 if (!V.getValue())
601 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000602 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000603 return true;
604 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000606}
607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
609 llvm_unreachable("Translation units are visited directly by Visit()");
610 return false;
611}
612
613bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
614 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
615 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000616
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000617 return false;
618}
619
620bool CursorVisitor::VisitTagDecl(TagDecl *D) {
621 return VisitDeclContext(D);
622}
623
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000624bool CursorVisitor::VisitClassTemplateSpecializationDecl(
625 ClassTemplateSpecializationDecl *D) {
626 bool ShouldVisitBody = false;
627 switch (D->getSpecializationKind()) {
628 case TSK_Undeclared:
629 case TSK_ImplicitInstantiation:
630 // Nothing to visit
631 return false;
632
633 case TSK_ExplicitInstantiationDeclaration:
634 case TSK_ExplicitInstantiationDefinition:
635 break;
636
637 case TSK_ExplicitSpecialization:
638 ShouldVisitBody = true;
639 break;
640 }
641
642 // Visit the template arguments used in the specialization.
643 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
644 TypeLoc TL = SpecType->getTypeLoc();
645 if (TemplateSpecializationTypeLoc *TSTLoc
646 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
647 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
648 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
649 return true;
650 }
651 }
652
653 if (ShouldVisitBody && VisitCXXRecordDecl(D))
654 return true;
655
656 return false;
657}
658
Douglas Gregor74dbe642010-08-31 19:31:58 +0000659bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
660 ClassTemplatePartialSpecializationDecl *D) {
661 // FIXME: Visit the "outer" template parameter lists on the TagDecl
662 // before visiting these template parameters.
663 if (VisitTemplateParameters(D->getTemplateParameters()))
664 return true;
665
666 // Visit the partial specialization arguments.
667 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
668 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
669 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
670 return true;
671
672 return VisitCXXRecordDecl(D);
673}
674
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000675bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000676 // Visit the default argument.
677 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
678 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
679 if (Visit(DefArg->getTypeLoc()))
680 return true;
681
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000682 return false;
683}
684
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000685bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
686 if (Expr *Init = D->getInitExpr())
687 return Visit(MakeCXCursor(Init, StmtParent, TU));
688 return false;
689}
690
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000691bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
692 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
693 if (Visit(TSInfo->getTypeLoc()))
694 return true;
695
696 return false;
697}
698
Douglas Gregora67e03f2010-09-09 21:42:20 +0000699/// \brief Compare two base or member initializers based on their source order.
700static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
701 CXXBaseOrMemberInitializer const * const *X
702 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
703 CXXBaseOrMemberInitializer const * const *Y
704 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
705
706 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
707 return -1;
708 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
709 return 1;
710 else
711 return 0;
712}
713
Douglas Gregorb1373d02010-01-20 20:59:29 +0000714bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000715 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
716 // Visit the function declaration's syntactic components in the order
717 // written. This requires a bit of work.
718 TypeLoc TL = TSInfo->getTypeLoc();
719 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
720
721 // If we have a function declared directly (without the use of a typedef),
722 // visit just the return type. Otherwise, just visit the function's type
723 // now.
724 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
725 (!FTL && Visit(TL)))
726 return true;
727
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000728 // Visit the nested-name-specifier, if present.
729 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
730 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
731 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000732
733 // Visit the declaration name.
734 if (VisitDeclarationNameInfo(ND->getNameInfo()))
735 return true;
736
737 // FIXME: Visit explicitly-specified template arguments!
738
739 // Visit the function parameters, if we have a function type.
740 if (FTL && VisitFunctionTypeLoc(*FTL, true))
741 return true;
742
743 // FIXME: Attributes?
744 }
745
Douglas Gregora67e03f2010-09-09 21:42:20 +0000746 if (ND->isThisDeclarationADefinition()) {
747 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
748 // Find the initializers that were written in the source.
749 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
750 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
751 IEnd = Constructor->init_end();
752 I != IEnd; ++I) {
753 if (!(*I)->isWritten())
754 continue;
755
756 WrittenInits.push_back(*I);
757 }
758
759 // Sort the initializers in source order
760 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
761 &CompareCXXBaseOrMemberInitializers);
762
763 // Visit the initializers in source order
764 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
765 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
766 if (Init->isMemberInitializer()) {
767 if (Visit(MakeCursorMemberRef(Init->getMember(),
768 Init->getMemberLocation(), TU)))
769 return true;
770 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
771 if (Visit(BaseInfo->getTypeLoc()))
772 return true;
773 }
774
775 // Visit the initializer value.
776 if (Expr *Initializer = Init->getInit())
777 if (Visit(MakeCXCursor(Initializer, ND, TU)))
778 return true;
779 }
780 }
781
782 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
783 return true;
784 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregorb1373d02010-01-20 20:59:29 +0000786 return false;
787}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000788
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000789bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
790 if (VisitDeclaratorDecl(D))
791 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000792
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000793 if (Expr *BitWidth = D->getBitWidth())
794 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000795
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796 return false;
797}
798
799bool CursorVisitor::VisitVarDecl(VarDecl *D) {
800 if (VisitDeclaratorDecl(D))
801 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000803 if (Expr *Init = D->getInit())
804 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000806 return false;
807}
808
Douglas Gregor84b51d72010-09-01 20:16:53 +0000809bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
810 if (VisitDeclaratorDecl(D))
811 return true;
812
813 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
814 if (Expr *DefArg = D->getDefaultArgument())
815 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
816
817 return false;
818}
819
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000820bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
821 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
822 // before visiting these template parameters.
823 if (VisitTemplateParameters(D->getTemplateParameters()))
824 return true;
825
826 return VisitFunctionDecl(D->getTemplatedDecl());
827}
828
Douglas Gregor39d6f072010-08-31 19:02:00 +0000829bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
830 // FIXME: Visit the "outer" template parameter lists on the TagDecl
831 // before visiting these template parameters.
832 if (VisitTemplateParameters(D->getTemplateParameters()))
833 return true;
834
835 return VisitCXXRecordDecl(D->getTemplatedDecl());
836}
837
Douglas Gregor84b51d72010-09-01 20:16:53 +0000838bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
839 if (VisitTemplateParameters(D->getTemplateParameters()))
840 return true;
841
842 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
843 VisitTemplateArgumentLoc(D->getDefaultArgument()))
844 return true;
845
846 return false;
847}
848
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000850 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
851 if (Visit(TSInfo->getTypeLoc()))
852 return true;
853
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000854 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855 PEnd = ND->param_end();
856 P != PEnd; ++P) {
857 if (Visit(MakeCXCursor(*P, TU)))
858 return true;
859 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000860
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000861 if (ND->isThisDeclarationADefinition() &&
862 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
863 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000864
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000865 return false;
866}
867
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000868namespace {
869 struct ContainerDeclsSort {
870 SourceManager &SM;
871 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
872 bool operator()(Decl *A, Decl *B) {
873 SourceLocation L_A = A->getLocStart();
874 SourceLocation L_B = B->getLocStart();
875 assert(L_A.isValid() && L_B.isValid());
876 return SM.isBeforeInTranslationUnit(L_A, L_B);
877 }
878 };
879}
880
Douglas Gregora59e3902010-01-21 23:27:09 +0000881bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000882 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
883 // an @implementation can lexically contain Decls that are not properly
884 // nested in the AST. When we identify such cases, we need to retrofit
885 // this nesting here.
886 if (!DI_current)
887 return VisitDeclContext(D);
888
889 // Scan the Decls that immediately come after the container
890 // in the current DeclContext. If any fall within the
891 // container's lexical region, stash them into a vector
892 // for later processing.
893 llvm::SmallVector<Decl *, 24> DeclsInContainer;
894 SourceLocation EndLoc = D->getSourceRange().getEnd();
895 SourceManager &SM = TU->getSourceManager();
896 if (EndLoc.isValid()) {
897 DeclContext::decl_iterator next = *DI_current;
898 while (++next != DE_current) {
899 Decl *D_next = *next;
900 if (!D_next)
901 break;
902 SourceLocation L = D_next->getLocStart();
903 if (!L.isValid())
904 break;
905 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
906 *DI_current = next;
907 DeclsInContainer.push_back(D_next);
908 continue;
909 }
910 break;
911 }
912 }
913
914 // The common case.
915 if (DeclsInContainer.empty())
916 return VisitDeclContext(D);
917
918 // Get all the Decls in the DeclContext, and sort them with the
919 // additional ones we've collected. Then visit them.
920 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
921 I!=E; ++I) {
922 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000923 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
924 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000925 continue;
926 DeclsInContainer.push_back(subDecl);
927 }
928
929 // Now sort the Decls so that they appear in lexical order.
930 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
931 ContainerDeclsSort(SM));
932
933 // Now visit the decls.
934 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
935 E = DeclsInContainer.end(); I != E; ++I) {
936 CXCursor Cursor = MakeCXCursor(*I, TU);
937 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
938 if (!V.hasValue())
939 continue;
940 if (!V.getValue())
941 return false;
942 if (Visit(Cursor, true))
943 return true;
944 }
945 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000946}
947
Douglas Gregorb1373d02010-01-20 20:59:29 +0000948bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000949 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
950 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000951 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000952
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000953 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
954 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
955 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000956 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000957 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000958
Douglas Gregora59e3902010-01-21 23:27:09 +0000959 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000960}
961
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000962bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
963 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
964 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
965 E = PID->protocol_end(); I != E; ++I, ++PL)
966 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
967 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000968
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000969 return VisitObjCContainerDecl(PID);
970}
971
Ted Kremenek23173d72010-05-18 21:09:07 +0000972bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000973 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000974 return true;
975
Ted Kremenek23173d72010-05-18 21:09:07 +0000976 // FIXME: This implements a workaround with @property declarations also being
977 // installed in the DeclContext for the @interface. Eventually this code
978 // should be removed.
979 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
980 if (!CDecl || !CDecl->IsClassExtension())
981 return false;
982
983 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
984 if (!ID)
985 return false;
986
987 IdentifierInfo *PropertyId = PD->getIdentifier();
988 ObjCPropertyDecl *prevDecl =
989 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
990
991 if (!prevDecl)
992 return false;
993
994 // Visit synthesized methods since they will be skipped when visiting
995 // the @interface.
996 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000997 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000998 if (Visit(MakeCXCursor(MD, TU)))
999 return true;
1000
1001 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001002 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001003 if (Visit(MakeCXCursor(MD, TU)))
1004 return true;
1005
1006 return false;
1007}
1008
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001010 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001011 if (D->getSuperClass() &&
1012 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001014 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001017 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1018 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1019 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001020 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001021 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022
Douglas Gregora59e3902010-01-21 23:27:09 +00001023 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001024}
1025
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1027 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001028}
1029
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001030bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001031 // 'ID' could be null when dealing with invalid code.
1032 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1033 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1034 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001035
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001036 return VisitObjCImplDecl(D);
1037}
1038
1039bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1040#if 0
1041 // Issue callbacks for super class.
1042 // FIXME: No source location information!
1043 if (D->getSuperClass() &&
1044 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046 TU)))
1047 return true;
1048#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001050 return VisitObjCImplDecl(D);
1051}
1052
1053bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1054 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1055 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1056 E = D->protocol_end();
1057 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001058 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001059 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
1061 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001062}
1063
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001064bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1065 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1066 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1067 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001068
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001069 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001070}
1071
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001072bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1073 return VisitDeclContext(D);
1074}
1075
Douglas Gregor69319002010-08-31 23:48:11 +00001076bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
1078 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1079 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1080 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001081
1082 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1083 D->getTargetNameLoc(), TU));
1084}
1085
Douglas Gregor7e242562010-09-01 19:52:22 +00001086bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 // Visit nested-name-specifier.
1088 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1089 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1090 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001091
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001092 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1093 return true;
1094
Douglas Gregor7e242562010-09-01 19:52:22 +00001095 return VisitDeclarationNameInfo(D->getNameInfo());
1096}
1097
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001098bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001099 // Visit nested-name-specifier.
1100 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1101 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1102 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001103
1104 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1105 D->getIdentLocation(), TU));
1106}
1107
Douglas Gregor7e242562010-09-01 19:52:22 +00001108bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001109 // Visit nested-name-specifier.
1110 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1111 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1112 return true;
1113
Douglas Gregor7e242562010-09-01 19:52:22 +00001114 return VisitDeclarationNameInfo(D->getNameInfo());
1115}
1116
1117bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1118 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119 // Visit nested-name-specifier.
1120 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1121 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1122 return true;
1123
Douglas Gregor7e242562010-09-01 19:52:22 +00001124 return false;
1125}
1126
Douglas Gregor01829d32010-08-31 14:41:23 +00001127bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1128 switch (Name.getName().getNameKind()) {
1129 case clang::DeclarationName::Identifier:
1130 case clang::DeclarationName::CXXLiteralOperatorName:
1131 case clang::DeclarationName::CXXOperatorName:
1132 case clang::DeclarationName::CXXUsingDirective:
1133 return false;
1134
1135 case clang::DeclarationName::CXXConstructorName:
1136 case clang::DeclarationName::CXXDestructorName:
1137 case clang::DeclarationName::CXXConversionFunctionName:
1138 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1139 return Visit(TSInfo->getTypeLoc());
1140 return false;
1141
1142 case clang::DeclarationName::ObjCZeroArgSelector:
1143 case clang::DeclarationName::ObjCOneArgSelector:
1144 case clang::DeclarationName::ObjCMultiArgSelector:
1145 // FIXME: Per-identifier location info?
1146 return false;
1147 }
1148
1149 return false;
1150}
1151
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001152bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1153 SourceRange Range) {
1154 // FIXME: This whole routine is a hack to work around the lack of proper
1155 // source information in nested-name-specifiers (PR5791). Since we do have
1156 // a beginning source location, we can visit the first component of the
1157 // nested-name-specifier, if it's a single-token component.
1158 if (!NNS)
1159 return false;
1160
1161 // Get the first component in the nested-name-specifier.
1162 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1163 NNS = Prefix;
1164
1165 switch (NNS->getKind()) {
1166 case NestedNameSpecifier::Namespace:
1167 // FIXME: The token at this source location might actually have been a
1168 // namespace alias, but we don't model that. Lame!
1169 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1170 TU));
1171
1172 case NestedNameSpecifier::TypeSpec: {
1173 // If the type has a form where we know that the beginning of the source
1174 // range matches up with a reference cursor. Visit the appropriate reference
1175 // cursor.
1176 Type *T = NNS->getAsType();
1177 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1178 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1179 if (const TagType *Tag = dyn_cast<TagType>(T))
1180 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1181 if (const TemplateSpecializationType *TST
1182 = dyn_cast<TemplateSpecializationType>(T))
1183 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1184 break;
1185 }
1186
1187 case NestedNameSpecifier::TypeSpecWithTemplate:
1188 case NestedNameSpecifier::Global:
1189 case NestedNameSpecifier::Identifier:
1190 break;
1191 }
1192
1193 return false;
1194}
1195
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001196bool CursorVisitor::VisitTemplateParameters(
1197 const TemplateParameterList *Params) {
1198 if (!Params)
1199 return false;
1200
1201 for (TemplateParameterList::const_iterator P = Params->begin(),
1202 PEnd = Params->end();
1203 P != PEnd; ++P) {
1204 if (Visit(MakeCXCursor(*P, TU)))
1205 return true;
1206 }
1207
1208 return false;
1209}
1210
Douglas Gregor0b36e612010-08-31 20:37:03 +00001211bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1212 switch (Name.getKind()) {
1213 case TemplateName::Template:
1214 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1215
1216 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001217 // Visit the overloaded template set.
1218 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1219 return true;
1220
Douglas Gregor0b36e612010-08-31 20:37:03 +00001221 return false;
1222
1223 case TemplateName::DependentTemplate:
1224 // FIXME: Visit nested-name-specifier.
1225 return false;
1226
1227 case TemplateName::QualifiedTemplate:
1228 // FIXME: Visit nested-name-specifier.
1229 return Visit(MakeCursorTemplateRef(
1230 Name.getAsQualifiedTemplateName()->getDecl(),
1231 Loc, TU));
1232 }
1233
1234 return false;
1235}
1236
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001237bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1238 switch (TAL.getArgument().getKind()) {
1239 case TemplateArgument::Null:
1240 case TemplateArgument::Integral:
1241 return false;
1242
1243 case TemplateArgument::Pack:
1244 // FIXME: Implement when variadic templates come along.
1245 return false;
1246
1247 case TemplateArgument::Type:
1248 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1249 return Visit(TSInfo->getTypeLoc());
1250 return false;
1251
1252 case TemplateArgument::Declaration:
1253 if (Expr *E = TAL.getSourceDeclExpression())
1254 return Visit(MakeCXCursor(E, StmtParent, TU));
1255 return false;
1256
1257 case TemplateArgument::Expression:
1258 if (Expr *E = TAL.getSourceExpression())
1259 return Visit(MakeCXCursor(E, StmtParent, TU));
1260 return false;
1261
1262 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001263 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1264 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001265 }
1266
1267 return false;
1268}
1269
Ted Kremeneka0536d82010-05-07 01:04:29 +00001270bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1271 return VisitDeclContext(D);
1272}
1273
Douglas Gregor01829d32010-08-31 14:41:23 +00001274bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1275 return Visit(TL.getUnqualifiedLoc());
1276}
1277
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1279 ASTContext &Context = TU->getASTContext();
1280
1281 // Some builtin types (such as Objective-C's "id", "sel", and
1282 // "Class") have associated declarations. Create cursors for those.
1283 QualType VisitType;
1284 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001285 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001286 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001287 case BuiltinType::Char_U:
1288 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001289 case BuiltinType::Char16:
1290 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001291 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001292 case BuiltinType::UInt:
1293 case BuiltinType::ULong:
1294 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001295 case BuiltinType::UInt128:
1296 case BuiltinType::Char_S:
1297 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001298 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001299 case BuiltinType::Short:
1300 case BuiltinType::Int:
1301 case BuiltinType::Long:
1302 case BuiltinType::LongLong:
1303 case BuiltinType::Int128:
1304 case BuiltinType::Float:
1305 case BuiltinType::Double:
1306 case BuiltinType::LongDouble:
1307 case BuiltinType::NullPtr:
1308 case BuiltinType::Overload:
1309 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001310 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001311
1312 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001313 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001314
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001315 case BuiltinType::ObjCId:
1316 VisitType = Context.getObjCIdType();
1317 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001318
1319 case BuiltinType::ObjCClass:
1320 VisitType = Context.getObjCClassType();
1321 break;
1322
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323 case BuiltinType::ObjCSel:
1324 VisitType = Context.getObjCSelType();
1325 break;
1326 }
1327
1328 if (!VisitType.isNull()) {
1329 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001330 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331 TU));
1332 }
1333
1334 return false;
1335}
1336
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001337bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1338 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1339}
1340
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1342 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1343}
1344
1345bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1346 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1347}
1348
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001349bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001350 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001351 // no context information with which we can match up the depth/index in the
1352 // type to the appropriate
1353 return false;
1354}
1355
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001356bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1357 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1358 return true;
1359
John McCallc12c5bb2010-05-15 11:32:37 +00001360 return false;
1361}
1362
1363bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1364 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1365 return true;
1366
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1368 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1369 TU)))
1370 return true;
1371 }
1372
1373 return false;
1374}
1375
1376bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001377 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378}
1379
1380bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1381 return Visit(TL.getPointeeLoc());
1382}
1383
1384bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1385 return Visit(TL.getPointeeLoc());
1386}
1387
1388bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1389 return Visit(TL.getPointeeLoc());
1390}
1391
1392bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394}
1395
1396bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001397 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001398}
1399
Douglas Gregor01829d32010-08-31 14:41:23 +00001400bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1401 bool SkipResultType) {
1402 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001403 return true;
1404
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001405 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001406 if (Decl *D = TL.getArg(I))
1407 if (Visit(MakeCXCursor(D, TU)))
1408 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409
1410 return false;
1411}
1412
1413bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1414 if (Visit(TL.getElementLoc()))
1415 return true;
1416
1417 if (Expr *Size = TL.getSizeExpr())
1418 return Visit(MakeCXCursor(Size, StmtParent, TU));
1419
1420 return false;
1421}
1422
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001423bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1424 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001425 // Visit the template name.
1426 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1427 TL.getTemplateNameLoc()))
1428 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001429
1430 // Visit the template arguments.
1431 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1432 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1433 return true;
1434
1435 return false;
1436}
1437
Douglas Gregor2332c112010-01-21 20:48:56 +00001438bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1439 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1440}
1441
1442bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1443 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1444 return Visit(TSInfo->getTypeLoc());
1445
1446 return false;
1447}
1448
Douglas Gregora59e3902010-01-21 23:27:09 +00001449bool CursorVisitor::VisitStmt(Stmt *S) {
1450 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1451 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001452 if (Stmt *C = *Child)
1453 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1454 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001455 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001456
Douglas Gregora59e3902010-01-21 23:27:09 +00001457 return false;
1458}
1459
1460bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001461 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001462 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1463 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001464 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001465 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001466 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001468
Douglas Gregora59e3902010-01-21 23:27:09 +00001469 return false;
1470}
1471
Douglas Gregor36897b02010-09-10 00:22:18 +00001472bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1473 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1474}
1475
Douglas Gregor8947a752010-09-02 20:35:02 +00001476bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1477 // Visit nested-name-specifier, if present.
1478 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1479 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1480 return true;
1481
1482 // Visit declaration name.
1483 if (VisitDeclarationNameInfo(E->getNameInfo()))
1484 return true;
1485
1486 // Visit explicitly-specified template arguments.
1487 if (E->hasExplicitTemplateArgs()) {
1488 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1489 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1490 *ArgEnd = Arg + Args.NumTemplateArgs;
1491 Arg != ArgEnd; ++Arg)
1492 if (VisitTemplateArgumentLoc(*Arg))
1493 return true;
1494 }
1495
1496 return false;
1497}
1498
Ted Kremenek3064ef92010-08-27 21:34:58 +00001499bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1500 if (D->isDefinition()) {
1501 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1502 E = D->bases_end(); I != E; ++I) {
1503 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1504 return true;
1505 }
1506 }
1507
1508 return VisitTagDecl(D);
1509}
1510
1511
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001512bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1513 return Visit(B->getBlockDecl());
1514}
1515
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001516bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001517 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001518 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1519 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001520
1521 // Visit the components of the offsetof expression.
1522 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1523 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1524 const OffsetOfNode &Node = E->getComponent(I);
1525 switch (Node.getKind()) {
1526 case OffsetOfNode::Array:
1527 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1528 StmtParent, TU)))
1529 return true;
1530 break;
1531
1532 case OffsetOfNode::Field:
1533 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1534 TU)))
1535 return true;
1536 break;
1537
1538 case OffsetOfNode::Identifier:
1539 case OffsetOfNode::Base:
1540 continue;
1541 }
1542 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001543
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001544 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001545}
1546
Douglas Gregor336fd812010-01-23 00:40:08 +00001547bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1548 if (E->isArgumentType()) {
1549 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1550 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001551
Douglas Gregor336fd812010-01-23 00:40:08 +00001552 return false;
1553 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001554
Douglas Gregor336fd812010-01-23 00:40:08 +00001555 return VisitExpr(E);
1556}
1557
1558bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1559 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1560 if (Visit(TSInfo->getTypeLoc()))
1561 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001562
Douglas Gregor336fd812010-01-23 00:40:08 +00001563 return VisitCastExpr(E);
1564}
1565
1566bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1567 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1568 if (Visit(TSInfo->getTypeLoc()))
1569 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001570
Douglas Gregor336fd812010-01-23 00:40:08 +00001571 return VisitExpr(E);
1572}
1573
Douglas Gregor36897b02010-09-10 00:22:18 +00001574bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1575 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1576}
1577
Douglas Gregor648220e2010-08-10 15:02:34 +00001578bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1579 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1580 Visit(E->getArgTInfo2()->getTypeLoc());
1581}
1582
1583bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1584 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1585 return true;
1586
1587 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1588}
1589
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001590bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1591 // Visit the designators.
1592 typedef DesignatedInitExpr::Designator Designator;
1593 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1594 DEnd = E->designators_end();
1595 D != DEnd; ++D) {
1596 if (D->isFieldDesignator()) {
1597 if (FieldDecl *Field = D->getField())
1598 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1599 return true;
1600
1601 continue;
1602 }
1603
1604 if (D->isArrayDesignator()) {
1605 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1606 return true;
1607
1608 continue;
1609 }
1610
1611 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1612 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1613 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1614 return true;
1615 }
1616
1617 // Visit the initializer value itself.
1618 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1619}
1620
Douglas Gregor94802292010-09-02 21:20:16 +00001621bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1622 if (E->isTypeOperand()) {
1623 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1624 return Visit(TSInfo->getTypeLoc());
1625
1626 return false;
1627 }
1628
1629 return VisitExpr(E);
1630}
1631
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001632bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1633 if (E->isTypeOperand()) {
1634 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1635 return Visit(TSInfo->getTypeLoc());
1636
1637 return false;
1638 }
1639
1640 return VisitExpr(E);
1641}
1642
Douglas Gregorab6677e2010-09-08 00:15:04 +00001643bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1644 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001645 if (Visit(TSInfo->getTypeLoc()))
1646 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001647
1648 return VisitExpr(E);
1649}
1650
1651bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1652 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1653 return Visit(TSInfo->getTypeLoc());
1654
1655 return false;
1656}
1657
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001658bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1659 // Visit placement arguments.
1660 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1661 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1662 return true;
1663
1664 // Visit the allocated type.
1665 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1666 if (Visit(TSInfo->getTypeLoc()))
1667 return true;
1668
1669 // Visit the array size, if any.
1670 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1671 return true;
1672
1673 // Visit the initializer or constructor arguments.
1674 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1675 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1676 return true;
1677
1678 return false;
1679}
1680
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001681bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1682 // Visit base expression.
1683 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1684 return true;
1685
1686 // Visit the nested-name-specifier.
1687 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1688 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1689 return true;
1690
1691 // Visit the scope type that looks disturbingly like the nested-name-specifier
1692 // but isn't.
1693 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1694 if (Visit(TSInfo->getTypeLoc()))
1695 return true;
1696
1697 // Visit the name of the type being destroyed.
1698 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1699 if (Visit(TSInfo->getTypeLoc()))
1700 return true;
1701
1702 return false;
1703}
1704
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001705bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1706 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1707}
1708
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001709bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001710 // Visit the nested-name-specifier.
1711 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1712 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1713 return true;
1714
1715 // Visit the declaration name.
1716 if (VisitDeclarationNameInfo(E->getNameInfo()))
1717 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001718
1719 // Visit the overloaded declaration reference.
1720 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1721 return true;
1722
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001723 // Visit the explicitly-specified template arguments.
1724 if (const ExplicitTemplateArgumentList *ArgList
1725 = E->getOptionalExplicitTemplateArgs()) {
1726 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1727 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1728 Arg != ArgEnd; ++Arg) {
1729 if (VisitTemplateArgumentLoc(*Arg))
1730 return true;
1731 }
1732 }
1733
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001734 return false;
1735}
1736
Douglas Gregorbfebed22010-09-03 17:24:10 +00001737bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1738 DependentScopeDeclRefExpr *E) {
1739 // Visit the nested-name-specifier.
1740 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1741 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1742 return true;
1743
1744 // Visit the declaration name.
1745 if (VisitDeclarationNameInfo(E->getNameInfo()))
1746 return true;
1747
1748 // Visit the explicitly-specified template arguments.
1749 if (const ExplicitTemplateArgumentList *ArgList
1750 = E->getOptionalExplicitTemplateArgs()) {
1751 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1752 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1753 Arg != ArgEnd; ++Arg) {
1754 if (VisitTemplateArgumentLoc(*Arg))
1755 return true;
1756 }
1757 }
1758
1759 return false;
1760}
1761
Douglas Gregorab6677e2010-09-08 00:15:04 +00001762bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1763 CXXUnresolvedConstructExpr *E) {
1764 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1765 if (Visit(TSInfo->getTypeLoc()))
1766 return true;
1767
1768 return VisitExpr(E);
1769}
1770
Douglas Gregor25d63622010-09-03 17:35:34 +00001771bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1772 CXXDependentScopeMemberExpr *E) {
1773 // Visit the base expression, if there is one.
1774 if (!E->isImplicitAccess() &&
1775 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1776 return true;
1777
1778 // Visit the nested-name-specifier.
1779 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1780 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1781 return true;
1782
1783 // Visit the declaration name.
1784 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1785 return true;
1786
1787 // Visit the explicitly-specified template arguments.
1788 if (const ExplicitTemplateArgumentList *ArgList
1789 = E->getOptionalExplicitTemplateArgs()) {
1790 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1791 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1792 Arg != ArgEnd; ++Arg) {
1793 if (VisitTemplateArgumentLoc(*Arg))
1794 return true;
1795 }
1796 }
1797
1798 return false;
1799}
1800
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001801bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1802 // Visit the base expression, if there is one.
1803 if (!E->isImplicitAccess() &&
1804 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1805 return true;
1806
1807 return VisitOverloadExpr(E);
1808}
Douglas Gregor25d63622010-09-03 17:35:34 +00001809
Douglas Gregorc2350e52010-03-08 16:40:19 +00001810bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001811 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1812 if (Visit(TSInfo->getTypeLoc()))
1813 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001814
1815 return VisitExpr(E);
1816}
1817
Douglas Gregor81d34662010-04-20 15:39:42 +00001818bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1819 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1820}
1821
1822
Ted Kremenek09dfa372010-02-18 05:46:33 +00001823bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001824 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1825 i != e; ++i)
1826 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001827 return true;
1828
1829 return false;
1830}
1831
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001832//===----------------------------------------------------------------------===//
1833// Data-recursive visitor methods.
1834//===----------------------------------------------------------------------===//
1835
Ted Kremeneka6b70432010-11-12 21:34:09 +00001836static void EnqueueChildren(VisitorWorkList &WL, CXCursor Parent, Stmt *S) {
1837 unsigned size = WL.size();
1838 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1839 Child != ChildEnd; ++Child) {
1840 WLAddStmt(WL, Parent, *Child);
1841 }
1842 if (size == WL.size())
1843 return;
1844 // Now reverse the entries we just added. This will match the DFS
1845 // ordering performed by the worklist.
1846 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1847 std::reverse(I, E);
1848}
1849
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001850void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1851 CXCursor C = MakeCXCursor(S, StmtParent, TU);
1852 switch (S->getStmtClass()) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001853 default:
1854 EnqueueChildren(WL, C, S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001855 break;
Ted Kremenekf1107452010-11-12 18:26:56 +00001856 case Stmt::CXXOperatorCallExprClass: {
1857 CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(S);
1858 // Note that we enqueue things in reverse order so that
1859 // they are visited correctly by the DFS.
Ted Kremenekf1107452010-11-12 18:26:56 +00001860 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
Ted Kremenekae3c2202010-11-12 18:27:01 +00001861 WLAddStmt(WL, C, CE->getArg(N-I));
Ted Kremenekf1107452010-11-12 18:26:56 +00001862
Ted Kremenekae3c2202010-11-12 18:27:01 +00001863 WLAddStmt(WL, C, CE->getCallee());
1864 WLAddStmt(WL, C, CE->getArg(0));
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001865 break;
1866 }
1867 case Stmt::BinaryOperatorClass: {
1868 BinaryOperator *B = cast<BinaryOperator>(S);
Ted Kremenekae3c2202010-11-12 18:27:01 +00001869 WLAddStmt(WL, C, B->getRHS());
1870 WLAddStmt(WL, C, B->getLHS());
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001871 break;
1872 }
Ted Kremenekbb677132010-11-12 18:27:04 +00001873 case Stmt::ForStmtClass: {
1874 ForStmt *FS = cast<ForStmt>(S);
1875 WLAddStmt(WL, C, FS->getBody());
1876 WLAddStmt(WL, C, FS->getInc());
1877 WLAddStmt(WL, C, FS->getCond());
1878 WLAddDecl(WL, C, FS->getConditionVariable());
1879 WLAddStmt(WL, C, FS->getInit());
1880 break;
1881 }
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001882 case Stmt::IfStmtClass: {
1883 IfStmt *If = cast<IfStmt>(S);
1884 WLAddStmt(WL, C, If->getElse());
1885 WLAddStmt(WL, C, If->getThen());
1886 WLAddStmt(WL, C, If->getCond());
Ted Kremenekae3c2202010-11-12 18:27:01 +00001887 WLAddDecl(WL, C, If->getConditionVariable());
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001888 break;
1889 }
Ted Kremeneka6b70432010-11-12 21:34:09 +00001890 case Stmt::InitListExprClass: {
1891 InitListExpr *IE = cast<InitListExpr>(S);
1892 // We care about the syntactic form of the initializer list, only.
1893 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1894 IE = Syntactic;
1895 EnqueueChildren(WL, C, IE);
1896 break;
1897 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001898 case Stmt::MemberExprClass: {
1899 MemberExpr *M = cast<MemberExpr>(S);
1900 WL.push_back(MemberExprParts(M, C));
Ted Kremenekae3c2202010-11-12 18:27:01 +00001901 WLAddStmt(WL, C, M->getBase());
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001902 break;
1903 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001904 case Stmt::ParenExprClass: {
Ted Kremenekae3c2202010-11-12 18:27:01 +00001905 WLAddStmt(WL, C, cast<ParenExpr>(S)->getSubExpr());
Ted Kremenekf1107452010-11-12 18:26:56 +00001906 break;
1907 }
1908 case Stmt::SwitchStmtClass: {
1909 SwitchStmt *SS = cast<SwitchStmt>(S);
Ted Kremenekae3c2202010-11-12 18:27:01 +00001910 WLAddStmt(WL, C, SS->getBody());
1911 WLAddStmt(WL, C, SS->getCond());
1912 WLAddDecl(WL, C, SS->getConditionVariable());
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001913 break;
1914 }
Ted Kremenekbb677132010-11-12 18:27:04 +00001915 case Stmt::WhileStmtClass: {
1916 WhileStmt *W = cast<WhileStmt>(S);
1917 WLAddStmt(WL, C, W->getBody());
1918 WLAddStmt(WL, C, W->getCond());
1919 WLAddDecl(WL, C, W->getConditionVariable());
1920 break;
1921 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001922 }
1923}
1924
1925bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1926 if (RegionOfInterest.isValid()) {
1927 SourceRange Range = getRawCursorExtent(C);
1928 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1929 return false;
1930 }
1931 return true;
1932}
1933
1934bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1935 while (!WL.empty()) {
1936 // Dequeue the worklist item.
1937 VisitorJob LI = WL.back(); WL.pop_back();
1938
1939 // Set the Parent field, then back to its old value once we're done.
1940 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1941
1942 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001943 case VisitorJob::DeclVisitKind: {
1944 Decl *D = cast<DeclVisit>(LI).get();
1945 if (!D)
1946 continue;
1947
1948 // For now, perform default visitation for Decls.
1949 if (Visit(MakeCXCursor(D, TU)))
1950 return true;
1951
1952 continue;
1953 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001954 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001955 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001956 if (!S)
1957 continue;
1958
Ted Kremenekf1107452010-11-12 18:26:56 +00001959 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001960 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1961
1962 switch (S->getStmtClass()) {
1963 default: {
1964 // Perform default visitation for other cases.
1965 if (Visit(Cursor))
1966 return true;
1967 continue;
1968 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001969 case Stmt::BinaryOperatorClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001970 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001971 case Stmt::CaseStmtClass:
1972 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001973 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001974 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001975 case Stmt::DefaultStmtClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001976 case Stmt::DoStmtClass:
1977 case Stmt::ForStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001978 case Stmt::IfStmtClass:
Ted Kremeneka6b70432010-11-12 21:34:09 +00001979 case Stmt::InitListExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001980 case Stmt::MemberExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001981 case Stmt::ParenExprClass:
1982 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00001983 case Stmt::UnaryOperatorClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001984 case Stmt::WhileStmtClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001985 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001986 if (!IsInRegionOfInterest(Cursor))
1987 continue;
1988 switch (Visitor(Cursor, Parent, ClientData)) {
1989 case CXChildVisit_Break:
1990 return true;
1991 case CXChildVisit_Continue:
1992 break;
1993 case CXChildVisit_Recurse:
1994 EnqueueWorkList(WL, S);
1995 break;
1996 }
1997 }
1998 }
1999 continue;
2000 }
2001 case VisitorJob::MemberExprPartsKind: {
2002 // Handle the other pieces in the MemberExpr besides the base.
2003 MemberExpr *M = cast<MemberExprParts>(LI).get();
2004
2005 // Visit the nested-name-specifier
2006 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2007 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2008 return true;
2009
2010 // Visit the declaration name.
2011 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2012 return true;
2013
2014 // Visit the explicitly-specified template arguments, if any.
2015 if (M->hasExplicitTemplateArgs()) {
2016 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2017 *ArgEnd = Arg + M->getNumTemplateArgs();
2018 Arg != ArgEnd; ++Arg) {
2019 if (VisitTemplateArgumentLoc(*Arg))
2020 return true;
2021 }
2022 }
2023 continue;
2024 }
2025 }
2026 }
2027 return false;
2028}
2029
2030bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2031 VisitorWorkList WL;
2032 EnqueueWorkList(WL, S);
2033 return RunVisitorWorkList(WL);
2034}
2035
2036//===----------------------------------------------------------------------===//
2037// Misc. API hooks.
2038//===----------------------------------------------------------------------===//
2039
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002040static llvm::sys::Mutex EnableMultithreadingMutex;
2041static bool EnabledMultithreading;
2042
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002043extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002044CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2045 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002046 // Disable pretty stack trace functionality, which will otherwise be a very
2047 // poor citizen of the world and set up all sorts of signal handlers.
2048 llvm::DisablePrettyStackTrace = true;
2049
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002050 // We use crash recovery to make some of our APIs more reliable, implicitly
2051 // enable it.
2052 llvm::CrashRecoveryContext::Enable();
2053
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002054 // Enable support for multithreading in LLVM.
2055 {
2056 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2057 if (!EnabledMultithreading) {
2058 llvm::llvm_start_multithreaded();
2059 EnabledMultithreading = true;
2060 }
2061 }
2062
Douglas Gregora030b7c2010-01-22 20:35:53 +00002063 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002064 if (excludeDeclarationsFromPCH)
2065 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002066 if (displayDiagnostics)
2067 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002068 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002069}
2070
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002071void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002072 if (CIdx)
2073 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002074}
2075
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002076CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002077 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002078 if (!CIdx)
2079 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002080
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002081 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002082 FileSystemOptions FileSystemOpts;
2083 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002084
Douglas Gregor28019772010-04-05 23:52:57 +00002085 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002086 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002087 CXXIdx->getOnlyLocalDecls(),
2088 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002089}
2090
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002091unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002092 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002093 CXTranslationUnit_CacheCompletionResults |
2094 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002095}
2096
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002097CXTranslationUnit
2098clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2099 const char *source_filename,
2100 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002101 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002102 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002103 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002104 return clang_parseTranslationUnit(CIdx, source_filename,
2105 command_line_args, num_command_line_args,
2106 unsaved_files, num_unsaved_files,
2107 CXTranslationUnit_DetailedPreprocessingRecord);
2108}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002109
2110struct ParseTranslationUnitInfo {
2111 CXIndex CIdx;
2112 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002113 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002114 int num_command_line_args;
2115 struct CXUnsavedFile *unsaved_files;
2116 unsigned num_unsaved_files;
2117 unsigned options;
2118 CXTranslationUnit result;
2119};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002120static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002121 ParseTranslationUnitInfo *PTUI =
2122 static_cast<ParseTranslationUnitInfo*>(UserData);
2123 CXIndex CIdx = PTUI->CIdx;
2124 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002125 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002126 int num_command_line_args = PTUI->num_command_line_args;
2127 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2128 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2129 unsigned options = PTUI->options;
2130 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002131
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002132 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002133 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002134
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002135 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2136
Douglas Gregor44c181a2010-07-23 00:33:23 +00002137 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002138 bool CompleteTranslationUnit
2139 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002140 bool CacheCodeCompetionResults
2141 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002142 bool CXXPrecompilePreamble
2143 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2144 bool CXXChainedPCH
2145 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002146
Douglas Gregor5352ac02010-01-28 00:27:43 +00002147 // Configure the diagnostics.
2148 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002149 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2150 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002151
Douglas Gregor4db64a42010-01-23 00:14:00 +00002152 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2153 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002154 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002155 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002156 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002157 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2158 Buffer));
2159 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160
Douglas Gregorb10daed2010-10-11 16:52:23 +00002161 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002162
Ted Kremenek139ba862009-10-22 00:03:57 +00002163 // The 'source_filename' argument is optional. If the caller does not
2164 // specify it then it is assumed that the source file is specified
2165 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002166 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002167 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002168
2169 // Since the Clang C library is primarily used by batch tools dealing with
2170 // (often very broken) source code, where spell-checking can have a
2171 // significant negative impact on performance (particularly when
2172 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002173 // Only do this if we haven't found a spell-checking-related argument.
2174 bool FoundSpellCheckingArgument = false;
2175 for (int I = 0; I != num_command_line_args; ++I) {
2176 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2177 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2178 FoundSpellCheckingArgument = true;
2179 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002180 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002181 }
2182 if (!FoundSpellCheckingArgument)
2183 Args.push_back("-fno-spell-checking");
2184
2185 Args.insert(Args.end(), command_line_args,
2186 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002187
Douglas Gregor44c181a2010-07-23 00:33:23 +00002188 // Do we need the detailed preprocessing record?
2189 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002190 Args.push_back("-Xclang");
2191 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002192 }
2193
Douglas Gregorb10daed2010-10-11 16:52:23 +00002194 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002195 llvm::OwningPtr<ASTUnit> Unit(
2196 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2197 Diags,
2198 CXXIdx->getClangResourcesPath(),
2199 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002200 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002201 RemappedFiles.data(),
2202 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002203 PrecompilePreamble,
2204 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002205 CacheCodeCompetionResults,
2206 CXXPrecompilePreamble,
2207 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002208
Douglas Gregorb10daed2010-10-11 16:52:23 +00002209 if (NumErrors != Diags->getNumErrors()) {
2210 // Make sure to check that 'Unit' is non-NULL.
2211 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2212 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2213 DEnd = Unit->stored_diag_end();
2214 D != DEnd; ++D) {
2215 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2216 CXString Msg = clang_formatDiagnostic(&Diag,
2217 clang_defaultDiagnosticDisplayOptions());
2218 fprintf(stderr, "%s\n", clang_getCString(Msg));
2219 clang_disposeString(Msg);
2220 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002221#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002222 // On Windows, force a flush, since there may be multiple copies of
2223 // stderr and stdout in the file system, all with different buffers
2224 // but writing to the same device.
2225 fflush(stderr);
2226#endif
2227 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002228 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002229
Douglas Gregorb10daed2010-10-11 16:52:23 +00002230 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002231}
2232CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2233 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002234 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002235 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002236 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002237 unsigned num_unsaved_files,
2238 unsigned options) {
2239 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002240 num_command_line_args, unsaved_files,
2241 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002242 llvm::CrashRecoveryContext CRC;
2243
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002244 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002245 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2246 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2247 fprintf(stderr, " 'command_line_args' : [");
2248 for (int i = 0; i != num_command_line_args; ++i) {
2249 if (i)
2250 fprintf(stderr, ", ");
2251 fprintf(stderr, "'%s'", command_line_args[i]);
2252 }
2253 fprintf(stderr, "],\n");
2254 fprintf(stderr, " 'unsaved_files' : [");
2255 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2256 if (i)
2257 fprintf(stderr, ", ");
2258 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2259 unsaved_files[i].Length);
2260 }
2261 fprintf(stderr, "],\n");
2262 fprintf(stderr, " 'options' : %d,\n", options);
2263 fprintf(stderr, "}\n");
2264
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002265 return 0;
2266 }
2267
2268 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002269}
2270
Douglas Gregor19998442010-08-13 15:35:05 +00002271unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2272 return CXSaveTranslationUnit_None;
2273}
2274
2275int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2276 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002277 if (!TU)
2278 return 1;
2279
2280 return static_cast<ASTUnit *>(TU)->Save(FileName);
2281}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002282
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002283void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002284 if (CTUnit) {
2285 // If the translation unit has been marked as unsafe to free, just discard
2286 // it.
2287 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2288 return;
2289
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002290 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002291 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002292}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002293
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002294unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2295 return CXReparse_None;
2296}
2297
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002298struct ReparseTranslationUnitInfo {
2299 CXTranslationUnit TU;
2300 unsigned num_unsaved_files;
2301 struct CXUnsavedFile *unsaved_files;
2302 unsigned options;
2303 int result;
2304};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002305
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002306static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002307 ReparseTranslationUnitInfo *RTUI =
2308 static_cast<ReparseTranslationUnitInfo*>(UserData);
2309 CXTranslationUnit TU = RTUI->TU;
2310 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2311 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2312 unsigned options = RTUI->options;
2313 (void) options;
2314 RTUI->result = 1;
2315
Douglas Gregorabc563f2010-07-19 21:46:24 +00002316 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002317 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002318
2319 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2320 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002321
2322 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2323 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2324 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2325 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002326 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002327 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2328 Buffer));
2329 }
2330
Douglas Gregor593b0c12010-09-23 18:47:53 +00002331 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2332 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002333}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002334
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002335int clang_reparseTranslationUnit(CXTranslationUnit TU,
2336 unsigned num_unsaved_files,
2337 struct CXUnsavedFile *unsaved_files,
2338 unsigned options) {
2339 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2340 options, 0 };
2341 llvm::CrashRecoveryContext CRC;
2342
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002343 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002344 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002345 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2346 return 1;
2347 }
2348
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002349
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002350 return RTUI.result;
2351}
2352
Douglas Gregordf95a132010-08-09 20:45:32 +00002353
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002354CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002355 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002356 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002357
Steve Naroff77accc12009-09-03 18:19:54 +00002358 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002359 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002360}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002361
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002362CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002363 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002364 return Result;
2365}
2366
Ted Kremenekfb480492010-01-13 21:46:36 +00002367} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002368
Ted Kremenekfb480492010-01-13 21:46:36 +00002369//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002370// CXSourceLocation and CXSourceRange Operations.
2371//===----------------------------------------------------------------------===//
2372
Douglas Gregorb9790342010-01-22 21:44:22 +00002373extern "C" {
2374CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002375 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002376 return Result;
2377}
2378
2379unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002380 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2381 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2382 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002383}
2384
2385CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2386 CXFile file,
2387 unsigned line,
2388 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002389 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002390 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002391
Douglas Gregorb9790342010-01-22 21:44:22 +00002392 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2393 SourceLocation SLoc
2394 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002395 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002396 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002397 if (SLoc.isInvalid()) return clang_getNullLocation();
2398
2399 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2400}
2401
2402CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2403 CXFile file,
2404 unsigned offset) {
2405 if (!tu || !file)
2406 return clang_getNullLocation();
2407
2408 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2409 SourceLocation Start
2410 = CXXUnit->getSourceManager().getLocation(
2411 static_cast<const FileEntry *>(file),
2412 1, 1);
2413 if (Start.isInvalid()) return clang_getNullLocation();
2414
2415 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2416
2417 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002418
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002419 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002420}
2421
Douglas Gregor5352ac02010-01-28 00:27:43 +00002422CXSourceRange clang_getNullRange() {
2423 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2424 return Result;
2425}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002426
Douglas Gregor5352ac02010-01-28 00:27:43 +00002427CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2428 if (begin.ptr_data[0] != end.ptr_data[0] ||
2429 begin.ptr_data[1] != end.ptr_data[1])
2430 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002431
2432 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002433 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002434 return Result;
2435}
2436
Douglas Gregor46766dc2010-01-26 19:19:08 +00002437void clang_getInstantiationLocation(CXSourceLocation location,
2438 CXFile *file,
2439 unsigned *line,
2440 unsigned *column,
2441 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002442 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2443
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002444 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002445 if (file)
2446 *file = 0;
2447 if (line)
2448 *line = 0;
2449 if (column)
2450 *column = 0;
2451 if (offset)
2452 *offset = 0;
2453 return;
2454 }
2455
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002456 const SourceManager &SM =
2457 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002458 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002459
2460 if (file)
2461 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2462 if (line)
2463 *line = SM.getInstantiationLineNumber(InstLoc);
2464 if (column)
2465 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002466 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002467 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002468}
2469
Douglas Gregora9b06d42010-11-09 06:24:54 +00002470void clang_getSpellingLocation(CXSourceLocation location,
2471 CXFile *file,
2472 unsigned *line,
2473 unsigned *column,
2474 unsigned *offset) {
2475 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2476
2477 if (!location.ptr_data[0] || Loc.isInvalid()) {
2478 if (file)
2479 *file = 0;
2480 if (line)
2481 *line = 0;
2482 if (column)
2483 *column = 0;
2484 if (offset)
2485 *offset = 0;
2486 return;
2487 }
2488
2489 const SourceManager &SM =
2490 *static_cast<const SourceManager*>(location.ptr_data[0]);
2491 SourceLocation SpellLoc = Loc;
2492 if (SpellLoc.isMacroID()) {
2493 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2494 if (SimpleSpellingLoc.isFileID() &&
2495 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2496 SpellLoc = SimpleSpellingLoc;
2497 else
2498 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2499 }
2500
2501 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2502 FileID FID = LocInfo.first;
2503 unsigned FileOffset = LocInfo.second;
2504
2505 if (file)
2506 *file = (void *)SM.getFileEntryForID(FID);
2507 if (line)
2508 *line = SM.getLineNumber(FID, FileOffset);
2509 if (column)
2510 *column = SM.getColumnNumber(FID, FileOffset);
2511 if (offset)
2512 *offset = FileOffset;
2513}
2514
Douglas Gregor1db19de2010-01-19 21:36:55 +00002515CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002516 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002517 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002518 return Result;
2519}
2520
2521CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002522 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002523 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002524 return Result;
2525}
2526
Douglas Gregorb9790342010-01-22 21:44:22 +00002527} // end: extern "C"
2528
Douglas Gregor1db19de2010-01-19 21:36:55 +00002529//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002530// CXFile Operations.
2531//===----------------------------------------------------------------------===//
2532
2533extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002534CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002535 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002536 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002537
Steve Naroff88145032009-10-27 14:35:18 +00002538 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002539 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002540}
2541
2542time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002543 if (!SFile)
2544 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002545
Steve Naroff88145032009-10-27 14:35:18 +00002546 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2547 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002548}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002549
Douglas Gregorb9790342010-01-22 21:44:22 +00002550CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2551 if (!tu)
2552 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002553
Douglas Gregorb9790342010-01-22 21:44:22 +00002554 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002555
Douglas Gregorb9790342010-01-22 21:44:22 +00002556 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002557 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2558 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002559 return const_cast<FileEntry *>(File);
2560}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002561
Ted Kremenekfb480492010-01-13 21:46:36 +00002562} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002563
Ted Kremenekfb480492010-01-13 21:46:36 +00002564//===----------------------------------------------------------------------===//
2565// CXCursor Operations.
2566//===----------------------------------------------------------------------===//
2567
Ted Kremenekfb480492010-01-13 21:46:36 +00002568static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002569 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2570 return getDeclFromExpr(CE->getSubExpr());
2571
Ted Kremenekfb480492010-01-13 21:46:36 +00002572 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2573 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002574 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2575 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002576 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2577 return ME->getMemberDecl();
2578 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2579 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002580 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2581 return PRE->getProperty();
2582
Ted Kremenekfb480492010-01-13 21:46:36 +00002583 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2584 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002585 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2586 if (!CE->isElidable())
2587 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002588 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2589 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590
Douglas Gregordb1314e2010-10-01 21:11:22 +00002591 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2592 return PE->getProtocol();
2593
Ted Kremenekfb480492010-01-13 21:46:36 +00002594 return 0;
2595}
2596
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002597static SourceLocation getLocationFromExpr(Expr *E) {
2598 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2599 return /*FIXME:*/Msg->getLeftLoc();
2600 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2601 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002602 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2603 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002604 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2605 return Member->getMemberLoc();
2606 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2607 return Ivar->getLocation();
2608 return E->getLocStart();
2609}
2610
Ted Kremenekfb480492010-01-13 21:46:36 +00002611extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002612
2613unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002614 CXCursorVisitor visitor,
2615 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002616 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002617
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002618 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2619 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002620 return CursorVis.VisitChildren(parent);
2621}
2622
David Chisnall3387c652010-11-03 14:12:26 +00002623#ifndef __has_feature
2624#define __has_feature(x) 0
2625#endif
2626#if __has_feature(blocks)
2627typedef enum CXChildVisitResult
2628 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2629
2630static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2631 CXClientData client_data) {
2632 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2633 return block(cursor, parent);
2634}
2635#else
2636// If we are compiled with a compiler that doesn't have native blocks support,
2637// define and call the block manually, so the
2638typedef struct _CXChildVisitResult
2639{
2640 void *isa;
2641 int flags;
2642 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002643 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2644 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002645} *CXCursorVisitorBlock;
2646
2647static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2648 CXClientData client_data) {
2649 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2650 return block->invoke(block, cursor, parent);
2651}
2652#endif
2653
2654
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002655unsigned clang_visitChildrenWithBlock(CXCursor parent,
2656 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002657 return clang_visitChildren(parent, visitWithBlock, block);
2658}
2659
Douglas Gregor78205d42010-01-20 21:45:58 +00002660static CXString getDeclSpelling(Decl *D) {
2661 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2662 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002663 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002664
Douglas Gregor78205d42010-01-20 21:45:58 +00002665 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002666 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002667
Douglas Gregor78205d42010-01-20 21:45:58 +00002668 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2669 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2670 // and returns different names. NamedDecl returns the class name and
2671 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002672 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002673
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002674 if (isa<UsingDirectiveDecl>(D))
2675 return createCXString("");
2676
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002677 llvm::SmallString<1024> S;
2678 llvm::raw_svector_ostream os(S);
2679 ND->printName(os);
2680
2681 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002682}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002683
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002684CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002685 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002686 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002687
Steve Narofff334b4e2009-09-02 18:26:48 +00002688 if (clang_isReference(C.kind)) {
2689 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002690 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002691 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002692 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002693 }
2694 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002695 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002696 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002697 }
2698 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002699 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002700 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002701 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002702 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002703 case CXCursor_CXXBaseSpecifier: {
2704 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2705 return createCXString(B->getType().getAsString());
2706 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002707 case CXCursor_TypeRef: {
2708 TypeDecl *Type = getCursorTypeRef(C).first;
2709 assert(Type && "Missing type decl");
2710
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002711 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2712 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002713 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002714 case CXCursor_TemplateRef: {
2715 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002716 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002717
2718 return createCXString(Template->getNameAsString());
2719 }
Douglas Gregor69319002010-08-31 23:48:11 +00002720
2721 case CXCursor_NamespaceRef: {
2722 NamedDecl *NS = getCursorNamespaceRef(C).first;
2723 assert(NS && "Missing namespace decl");
2724
2725 return createCXString(NS->getNameAsString());
2726 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002727
Douglas Gregora67e03f2010-09-09 21:42:20 +00002728 case CXCursor_MemberRef: {
2729 FieldDecl *Field = getCursorMemberRef(C).first;
2730 assert(Field && "Missing member decl");
2731
2732 return createCXString(Field->getNameAsString());
2733 }
2734
Douglas Gregor36897b02010-09-10 00:22:18 +00002735 case CXCursor_LabelRef: {
2736 LabelStmt *Label = getCursorLabelRef(C).first;
2737 assert(Label && "Missing label");
2738
2739 return createCXString(Label->getID()->getName());
2740 }
2741
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002742 case CXCursor_OverloadedDeclRef: {
2743 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2744 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2745 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2746 return createCXString(ND->getNameAsString());
2747 return createCXString("");
2748 }
2749 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2750 return createCXString(E->getName().getAsString());
2751 OverloadedTemplateStorage *Ovl
2752 = Storage.get<OverloadedTemplateStorage*>();
2753 if (Ovl->size() == 0)
2754 return createCXString("");
2755 return createCXString((*Ovl->begin())->getNameAsString());
2756 }
2757
Daniel Dunbaracca7252009-11-30 20:42:49 +00002758 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002759 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002760 }
2761 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002762
2763 if (clang_isExpression(C.kind)) {
2764 Decl *D = getDeclFromExpr(getCursorExpr(C));
2765 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002766 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002767 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002768 }
2769
Douglas Gregor36897b02010-09-10 00:22:18 +00002770 if (clang_isStatement(C.kind)) {
2771 Stmt *S = getCursorStmt(C);
2772 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2773 return createCXString(Label->getID()->getName());
2774
2775 return createCXString("");
2776 }
2777
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002778 if (C.kind == CXCursor_MacroInstantiation)
2779 return createCXString(getCursorMacroInstantiation(C)->getName()
2780 ->getNameStart());
2781
Douglas Gregor572feb22010-03-18 18:04:21 +00002782 if (C.kind == CXCursor_MacroDefinition)
2783 return createCXString(getCursorMacroDefinition(C)->getName()
2784 ->getNameStart());
2785
Douglas Gregorecdcb882010-10-20 22:00:55 +00002786 if (C.kind == CXCursor_InclusionDirective)
2787 return createCXString(getCursorInclusionDirective(C)->getFileName());
2788
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002789 if (clang_isDeclaration(C.kind))
2790 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002791
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002792 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002793}
2794
Douglas Gregor358559d2010-10-02 22:49:11 +00002795CXString clang_getCursorDisplayName(CXCursor C) {
2796 if (!clang_isDeclaration(C.kind))
2797 return clang_getCursorSpelling(C);
2798
2799 Decl *D = getCursorDecl(C);
2800 if (!D)
2801 return createCXString("");
2802
2803 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2804 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2805 D = FunTmpl->getTemplatedDecl();
2806
2807 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2808 llvm::SmallString<64> Str;
2809 llvm::raw_svector_ostream OS(Str);
2810 OS << Function->getNameAsString();
2811 if (Function->getPrimaryTemplate())
2812 OS << "<>";
2813 OS << "(";
2814 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2815 if (I)
2816 OS << ", ";
2817 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2818 }
2819
2820 if (Function->isVariadic()) {
2821 if (Function->getNumParams())
2822 OS << ", ";
2823 OS << "...";
2824 }
2825 OS << ")";
2826 return createCXString(OS.str());
2827 }
2828
2829 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2830 llvm::SmallString<64> Str;
2831 llvm::raw_svector_ostream OS(Str);
2832 OS << ClassTemplate->getNameAsString();
2833 OS << "<";
2834 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2835 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2836 if (I)
2837 OS << ", ";
2838
2839 NamedDecl *Param = Params->getParam(I);
2840 if (Param->getIdentifier()) {
2841 OS << Param->getIdentifier()->getName();
2842 continue;
2843 }
2844
2845 // There is no parameter name, which makes this tricky. Try to come up
2846 // with something useful that isn't too long.
2847 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2848 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2849 else if (NonTypeTemplateParmDecl *NTTP
2850 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2851 OS << NTTP->getType().getAsString(Policy);
2852 else
2853 OS << "template<...> class";
2854 }
2855
2856 OS << ">";
2857 return createCXString(OS.str());
2858 }
2859
2860 if (ClassTemplateSpecializationDecl *ClassSpec
2861 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2862 // If the type was explicitly written, use that.
2863 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2864 return createCXString(TSInfo->getType().getAsString(Policy));
2865
2866 llvm::SmallString<64> Str;
2867 llvm::raw_svector_ostream OS(Str);
2868 OS << ClassSpec->getNameAsString();
2869 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002870 ClassSpec->getTemplateArgs().data(),
2871 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002872 Policy);
2873 return createCXString(OS.str());
2874 }
2875
2876 return clang_getCursorSpelling(C);
2877}
2878
Ted Kremeneke68fff62010-02-17 00:41:32 +00002879CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002880 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002881 case CXCursor_FunctionDecl:
2882 return createCXString("FunctionDecl");
2883 case CXCursor_TypedefDecl:
2884 return createCXString("TypedefDecl");
2885 case CXCursor_EnumDecl:
2886 return createCXString("EnumDecl");
2887 case CXCursor_EnumConstantDecl:
2888 return createCXString("EnumConstantDecl");
2889 case CXCursor_StructDecl:
2890 return createCXString("StructDecl");
2891 case CXCursor_UnionDecl:
2892 return createCXString("UnionDecl");
2893 case CXCursor_ClassDecl:
2894 return createCXString("ClassDecl");
2895 case CXCursor_FieldDecl:
2896 return createCXString("FieldDecl");
2897 case CXCursor_VarDecl:
2898 return createCXString("VarDecl");
2899 case CXCursor_ParmDecl:
2900 return createCXString("ParmDecl");
2901 case CXCursor_ObjCInterfaceDecl:
2902 return createCXString("ObjCInterfaceDecl");
2903 case CXCursor_ObjCCategoryDecl:
2904 return createCXString("ObjCCategoryDecl");
2905 case CXCursor_ObjCProtocolDecl:
2906 return createCXString("ObjCProtocolDecl");
2907 case CXCursor_ObjCPropertyDecl:
2908 return createCXString("ObjCPropertyDecl");
2909 case CXCursor_ObjCIvarDecl:
2910 return createCXString("ObjCIvarDecl");
2911 case CXCursor_ObjCInstanceMethodDecl:
2912 return createCXString("ObjCInstanceMethodDecl");
2913 case CXCursor_ObjCClassMethodDecl:
2914 return createCXString("ObjCClassMethodDecl");
2915 case CXCursor_ObjCImplementationDecl:
2916 return createCXString("ObjCImplementationDecl");
2917 case CXCursor_ObjCCategoryImplDecl:
2918 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002919 case CXCursor_CXXMethod:
2920 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002921 case CXCursor_UnexposedDecl:
2922 return createCXString("UnexposedDecl");
2923 case CXCursor_ObjCSuperClassRef:
2924 return createCXString("ObjCSuperClassRef");
2925 case CXCursor_ObjCProtocolRef:
2926 return createCXString("ObjCProtocolRef");
2927 case CXCursor_ObjCClassRef:
2928 return createCXString("ObjCClassRef");
2929 case CXCursor_TypeRef:
2930 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002931 case CXCursor_TemplateRef:
2932 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002933 case CXCursor_NamespaceRef:
2934 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002935 case CXCursor_MemberRef:
2936 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002937 case CXCursor_LabelRef:
2938 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002939 case CXCursor_OverloadedDeclRef:
2940 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002941 case CXCursor_UnexposedExpr:
2942 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002943 case CXCursor_BlockExpr:
2944 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002945 case CXCursor_DeclRefExpr:
2946 return createCXString("DeclRefExpr");
2947 case CXCursor_MemberRefExpr:
2948 return createCXString("MemberRefExpr");
2949 case CXCursor_CallExpr:
2950 return createCXString("CallExpr");
2951 case CXCursor_ObjCMessageExpr:
2952 return createCXString("ObjCMessageExpr");
2953 case CXCursor_UnexposedStmt:
2954 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002955 case CXCursor_LabelStmt:
2956 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002957 case CXCursor_InvalidFile:
2958 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002959 case CXCursor_InvalidCode:
2960 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002961 case CXCursor_NoDeclFound:
2962 return createCXString("NoDeclFound");
2963 case CXCursor_NotImplemented:
2964 return createCXString("NotImplemented");
2965 case CXCursor_TranslationUnit:
2966 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002967 case CXCursor_UnexposedAttr:
2968 return createCXString("UnexposedAttr");
2969 case CXCursor_IBActionAttr:
2970 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002971 case CXCursor_IBOutletAttr:
2972 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002973 case CXCursor_IBOutletCollectionAttr:
2974 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002975 case CXCursor_PreprocessingDirective:
2976 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002977 case CXCursor_MacroDefinition:
2978 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002979 case CXCursor_MacroInstantiation:
2980 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002981 case CXCursor_InclusionDirective:
2982 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002983 case CXCursor_Namespace:
2984 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002985 case CXCursor_LinkageSpec:
2986 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002987 case CXCursor_CXXBaseSpecifier:
2988 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002989 case CXCursor_Constructor:
2990 return createCXString("CXXConstructor");
2991 case CXCursor_Destructor:
2992 return createCXString("CXXDestructor");
2993 case CXCursor_ConversionFunction:
2994 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002995 case CXCursor_TemplateTypeParameter:
2996 return createCXString("TemplateTypeParameter");
2997 case CXCursor_NonTypeTemplateParameter:
2998 return createCXString("NonTypeTemplateParameter");
2999 case CXCursor_TemplateTemplateParameter:
3000 return createCXString("TemplateTemplateParameter");
3001 case CXCursor_FunctionTemplate:
3002 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003003 case CXCursor_ClassTemplate:
3004 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003005 case CXCursor_ClassTemplatePartialSpecialization:
3006 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003007 case CXCursor_NamespaceAlias:
3008 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003009 case CXCursor_UsingDirective:
3010 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003011 case CXCursor_UsingDeclaration:
3012 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003013 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003014
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003015 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003016 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003017}
Steve Naroff89922f82009-08-31 00:59:03 +00003018
Ted Kremeneke68fff62010-02-17 00:41:32 +00003019enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3020 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003021 CXClientData client_data) {
3022 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003023
3024 // If our current best cursor is the construction of a temporary object,
3025 // don't replace that cursor with a type reference, because we want
3026 // clang_getCursor() to point at the constructor.
3027 if (clang_isExpression(BestCursor->kind) &&
3028 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3029 cursor.kind == CXCursor_TypeRef)
3030 return CXChildVisit_Recurse;
3031
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003032 *BestCursor = cursor;
3033 return CXChildVisit_Recurse;
3034}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003035
Douglas Gregorb9790342010-01-22 21:44:22 +00003036CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3037 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003038 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003039
Douglas Gregorb9790342010-01-22 21:44:22 +00003040 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003041 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3042
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003043 // Translate the given source location to make it point at the beginning of
3044 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003045 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003046
3047 // Guard against an invalid SourceLocation, or we may assert in one
3048 // of the following calls.
3049 if (SLoc.isInvalid())
3050 return clang_getNullCursor();
3051
Douglas Gregor40749ee2010-11-03 00:35:38 +00003052 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003053 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3054 CXXUnit->getASTContext().getLangOptions());
3055
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003056 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3057 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003058 // FIXME: Would be great to have a "hint" cursor, then walk from that
3059 // hint cursor upward until we find a cursor whose source range encloses
3060 // the region of interest, rather than starting from the translation unit.
3061 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003062 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003063 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003064 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003065 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003066
3067 if (Logging) {
3068 CXFile SearchFile;
3069 unsigned SearchLine, SearchColumn;
3070 CXFile ResultFile;
3071 unsigned ResultLine, ResultColumn;
3072 CXString SearchFileName, ResultFileName, KindSpelling;
3073 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3074
3075 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3076 0);
3077 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3078 &ResultColumn, 0);
3079 SearchFileName = clang_getFileName(SearchFile);
3080 ResultFileName = clang_getFileName(ResultFile);
3081 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3082 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3083 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3084 clang_getCString(KindSpelling),
3085 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3086 clang_disposeString(SearchFileName);
3087 clang_disposeString(ResultFileName);
3088 clang_disposeString(KindSpelling);
3089 }
3090
Ted Kremeneke68fff62010-02-17 00:41:32 +00003091 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003092}
3093
Ted Kremenek73885552009-11-17 19:28:59 +00003094CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003095 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003096}
3097
3098unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003099 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003100}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003101
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003102unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003103 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3104}
3105
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003106unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003107 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3108}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003109
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003110unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003111 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3112}
3113
Douglas Gregor97b98722010-01-19 23:20:36 +00003114unsigned clang_isExpression(enum CXCursorKind K) {
3115 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3116}
3117
3118unsigned clang_isStatement(enum CXCursorKind K) {
3119 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3120}
3121
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003122unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3123 return K == CXCursor_TranslationUnit;
3124}
3125
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003126unsigned clang_isPreprocessing(enum CXCursorKind K) {
3127 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3128}
3129
Ted Kremenekad6eff62010-03-08 21:17:29 +00003130unsigned clang_isUnexposed(enum CXCursorKind K) {
3131 switch (K) {
3132 case CXCursor_UnexposedDecl:
3133 case CXCursor_UnexposedExpr:
3134 case CXCursor_UnexposedStmt:
3135 case CXCursor_UnexposedAttr:
3136 return true;
3137 default:
3138 return false;
3139 }
3140}
3141
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003142CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003143 return C.kind;
3144}
3145
Douglas Gregor98258af2010-01-18 22:46:11 +00003146CXSourceLocation clang_getCursorLocation(CXCursor C) {
3147 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003148 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003149 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003150 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3151 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003152 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003153 }
3154
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003155 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003156 std::pair<ObjCProtocolDecl *, SourceLocation> P
3157 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003158 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003159 }
3160
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003161 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003162 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3163 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003164 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003165 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003166
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003167 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003168 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003169 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003170 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003171
3172 case CXCursor_TemplateRef: {
3173 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3174 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3175 }
3176
Douglas Gregor69319002010-08-31 23:48:11 +00003177 case CXCursor_NamespaceRef: {
3178 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3179 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3180 }
3181
Douglas Gregora67e03f2010-09-09 21:42:20 +00003182 case CXCursor_MemberRef: {
3183 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3184 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3185 }
3186
Ted Kremenek3064ef92010-08-27 21:34:58 +00003187 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003188 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3189 if (!BaseSpec)
3190 return clang_getNullLocation();
3191
3192 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3193 return cxloc::translateSourceLocation(getCursorContext(C),
3194 TSInfo->getTypeLoc().getBeginLoc());
3195
3196 return cxloc::translateSourceLocation(getCursorContext(C),
3197 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003198 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003199
Douglas Gregor36897b02010-09-10 00:22:18 +00003200 case CXCursor_LabelRef: {
3201 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3202 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3203 }
3204
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003205 case CXCursor_OverloadedDeclRef:
3206 return cxloc::translateSourceLocation(getCursorContext(C),
3207 getCursorOverloadedDeclRef(C).second);
3208
Douglas Gregorf46034a2010-01-18 23:41:10 +00003209 default:
3210 // FIXME: Need a way to enumerate all non-reference cases.
3211 llvm_unreachable("Missed a reference kind");
3212 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003213 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003214
3215 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003216 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003217 getLocationFromExpr(getCursorExpr(C)));
3218
Douglas Gregor36897b02010-09-10 00:22:18 +00003219 if (clang_isStatement(C.kind))
3220 return cxloc::translateSourceLocation(getCursorContext(C),
3221 getCursorStmt(C)->getLocStart());
3222
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003223 if (C.kind == CXCursor_PreprocessingDirective) {
3224 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3225 return cxloc::translateSourceLocation(getCursorContext(C), L);
3226 }
Douglas Gregor48072312010-03-18 15:23:44 +00003227
3228 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003229 SourceLocation L
3230 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003231 return cxloc::translateSourceLocation(getCursorContext(C), L);
3232 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003233
3234 if (C.kind == CXCursor_MacroDefinition) {
3235 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3236 return cxloc::translateSourceLocation(getCursorContext(C), L);
3237 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003238
3239 if (C.kind == CXCursor_InclusionDirective) {
3240 SourceLocation L
3241 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3242 return cxloc::translateSourceLocation(getCursorContext(C), L);
3243 }
3244
Ted Kremenek9a700d22010-05-12 06:16:13 +00003245 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003246 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003247
Douglas Gregorf46034a2010-01-18 23:41:10 +00003248 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003249 SourceLocation Loc = D->getLocation();
3250 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3251 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003252 // FIXME: Multiple variables declared in a single declaration
3253 // currently lack the information needed to correctly determine their
3254 // ranges when accounting for the type-specifier. We use context
3255 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3256 // and if so, whether it is the first decl.
3257 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3258 if (!cxcursor::isFirstInDeclGroup(C))
3259 Loc = VD->getLocation();
3260 }
3261
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003262 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003263}
Douglas Gregora7bde202010-01-19 00:34:46 +00003264
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003265} // end extern "C"
3266
3267static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003268 if (clang_isReference(C.kind)) {
3269 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003270 case CXCursor_ObjCSuperClassRef:
3271 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003272
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003273 case CXCursor_ObjCProtocolRef:
3274 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003275
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003276 case CXCursor_ObjCClassRef:
3277 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003278
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003279 case CXCursor_TypeRef:
3280 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003281
3282 case CXCursor_TemplateRef:
3283 return getCursorTemplateRef(C).second;
3284
Douglas Gregor69319002010-08-31 23:48:11 +00003285 case CXCursor_NamespaceRef:
3286 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003287
3288 case CXCursor_MemberRef:
3289 return getCursorMemberRef(C).second;
3290
Ted Kremenek3064ef92010-08-27 21:34:58 +00003291 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003292 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003293
Douglas Gregor36897b02010-09-10 00:22:18 +00003294 case CXCursor_LabelRef:
3295 return getCursorLabelRef(C).second;
3296
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003297 case CXCursor_OverloadedDeclRef:
3298 return getCursorOverloadedDeclRef(C).second;
3299
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003300 default:
3301 // FIXME: Need a way to enumerate all non-reference cases.
3302 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003303 }
3304 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003305
3306 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003307 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003308
3309 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003310 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003311
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003312 if (C.kind == CXCursor_PreprocessingDirective)
3313 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003314
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003315 if (C.kind == CXCursor_MacroInstantiation)
3316 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003317
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003318 if (C.kind == CXCursor_MacroDefinition)
3319 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003320
3321 if (C.kind == CXCursor_InclusionDirective)
3322 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3323
Ted Kremenek007a7c92010-11-01 23:26:51 +00003324 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3325 Decl *D = cxcursor::getCursorDecl(C);
3326 SourceRange R = D->getSourceRange();
3327 // FIXME: Multiple variables declared in a single declaration
3328 // currently lack the information needed to correctly determine their
3329 // ranges when accounting for the type-specifier. We use context
3330 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3331 // and if so, whether it is the first decl.
3332 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3333 if (!cxcursor::isFirstInDeclGroup(C))
3334 R.setBegin(VD->getLocation());
3335 }
3336 return R;
3337 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003338 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003339
3340extern "C" {
3341
3342CXSourceRange clang_getCursorExtent(CXCursor C) {
3343 SourceRange R = getRawCursorExtent(C);
3344 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003345 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003346
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003347 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003348}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003349
3350CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003351 if (clang_isInvalid(C.kind))
3352 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003353
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003354 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003355 if (clang_isDeclaration(C.kind)) {
3356 Decl *D = getCursorDecl(C);
3357 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3358 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3359 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3360 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3361 if (ObjCForwardProtocolDecl *Protocols
3362 = dyn_cast<ObjCForwardProtocolDecl>(D))
3363 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3364
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003365 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003366 }
3367
Douglas Gregor97b98722010-01-19 23:20:36 +00003368 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003369 Expr *E = getCursorExpr(C);
3370 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003371 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003372 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003373
3374 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3375 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3376
Douglas Gregor97b98722010-01-19 23:20:36 +00003377 return clang_getNullCursor();
3378 }
3379
Douglas Gregor36897b02010-09-10 00:22:18 +00003380 if (clang_isStatement(C.kind)) {
3381 Stmt *S = getCursorStmt(C);
3382 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3383 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3384 getCursorASTUnit(C));
3385
3386 return clang_getNullCursor();
3387 }
3388
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003389 if (C.kind == CXCursor_MacroInstantiation) {
3390 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3391 return MakeMacroDefinitionCursor(Def, CXXUnit);
3392 }
3393
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003394 if (!clang_isReference(C.kind))
3395 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003396
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003397 switch (C.kind) {
3398 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003399 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003400
3401 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003402 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003403
3404 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003405 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003406
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003407 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003408 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003409
3410 case CXCursor_TemplateRef:
3411 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3412
Douglas Gregor69319002010-08-31 23:48:11 +00003413 case CXCursor_NamespaceRef:
3414 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3415
Douglas Gregora67e03f2010-09-09 21:42:20 +00003416 case CXCursor_MemberRef:
3417 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3418
Ted Kremenek3064ef92010-08-27 21:34:58 +00003419 case CXCursor_CXXBaseSpecifier: {
3420 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3421 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3422 CXXUnit));
3423 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003424
Douglas Gregor36897b02010-09-10 00:22:18 +00003425 case CXCursor_LabelRef:
3426 // FIXME: We end up faking the "parent" declaration here because we
3427 // don't want to make CXCursor larger.
3428 return MakeCXCursor(getCursorLabelRef(C).first,
3429 CXXUnit->getASTContext().getTranslationUnitDecl(),
3430 CXXUnit);
3431
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003432 case CXCursor_OverloadedDeclRef:
3433 return C;
3434
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003435 default:
3436 // We would prefer to enumerate all non-reference cursor kinds here.
3437 llvm_unreachable("Unhandled reference cursor kind");
3438 break;
3439 }
3440 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003441
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003442 return clang_getNullCursor();
3443}
3444
Douglas Gregorb6998662010-01-19 19:34:47 +00003445CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003446 if (clang_isInvalid(C.kind))
3447 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003448
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003449 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003450
Douglas Gregorb6998662010-01-19 19:34:47 +00003451 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003452 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003453 C = clang_getCursorReferenced(C);
3454 WasReference = true;
3455 }
3456
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003457 if (C.kind == CXCursor_MacroInstantiation)
3458 return clang_getCursorReferenced(C);
3459
Douglas Gregorb6998662010-01-19 19:34:47 +00003460 if (!clang_isDeclaration(C.kind))
3461 return clang_getNullCursor();
3462
3463 Decl *D = getCursorDecl(C);
3464 if (!D)
3465 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003466
Douglas Gregorb6998662010-01-19 19:34:47 +00003467 switch (D->getKind()) {
3468 // Declaration kinds that don't really separate the notions of
3469 // declaration and definition.
3470 case Decl::Namespace:
3471 case Decl::Typedef:
3472 case Decl::TemplateTypeParm:
3473 case Decl::EnumConstant:
3474 case Decl::Field:
3475 case Decl::ObjCIvar:
3476 case Decl::ObjCAtDefsField:
3477 case Decl::ImplicitParam:
3478 case Decl::ParmVar:
3479 case Decl::NonTypeTemplateParm:
3480 case Decl::TemplateTemplateParm:
3481 case Decl::ObjCCategoryImpl:
3482 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003483 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003484 case Decl::LinkageSpec:
3485 case Decl::ObjCPropertyImpl:
3486 case Decl::FileScopeAsm:
3487 case Decl::StaticAssert:
3488 case Decl::Block:
3489 return C;
3490
3491 // Declaration kinds that don't make any sense here, but are
3492 // nonetheless harmless.
3493 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003494 break;
3495
3496 // Declaration kinds for which the definition is not resolvable.
3497 case Decl::UnresolvedUsingTypename:
3498 case Decl::UnresolvedUsingValue:
3499 break;
3500
3501 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003502 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3503 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003504
3505 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003506 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003507
3508 case Decl::Enum:
3509 case Decl::Record:
3510 case Decl::CXXRecord:
3511 case Decl::ClassTemplateSpecialization:
3512 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003513 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003514 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003515 return clang_getNullCursor();
3516
3517 case Decl::Function:
3518 case Decl::CXXMethod:
3519 case Decl::CXXConstructor:
3520 case Decl::CXXDestructor:
3521 case Decl::CXXConversion: {
3522 const FunctionDecl *Def = 0;
3523 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003524 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003525 return clang_getNullCursor();
3526 }
3527
3528 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003529 // Ask the variable if it has a definition.
3530 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3531 return MakeCXCursor(Def, CXXUnit);
3532 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003533 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003534
Douglas Gregorb6998662010-01-19 19:34:47 +00003535 case Decl::FunctionTemplate: {
3536 const FunctionDecl *Def = 0;
3537 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003538 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003539 return clang_getNullCursor();
3540 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003541
Douglas Gregorb6998662010-01-19 19:34:47 +00003542 case Decl::ClassTemplate: {
3543 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003544 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003545 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003546 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003547 return clang_getNullCursor();
3548 }
3549
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003550 case Decl::Using:
3551 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3552 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003553
3554 case Decl::UsingShadow:
3555 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003556 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003557 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003558
3559 case Decl::ObjCMethod: {
3560 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3561 if (Method->isThisDeclarationADefinition())
3562 return C;
3563
3564 // Dig out the method definition in the associated
3565 // @implementation, if we have it.
3566 // FIXME: The ASTs should make finding the definition easier.
3567 if (ObjCInterfaceDecl *Class
3568 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3569 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3570 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3571 Method->isInstanceMethod()))
3572 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003573 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003574
3575 return clang_getNullCursor();
3576 }
3577
3578 case Decl::ObjCCategory:
3579 if (ObjCCategoryImplDecl *Impl
3580 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003581 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003582 return clang_getNullCursor();
3583
3584 case Decl::ObjCProtocol:
3585 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3586 return C;
3587 return clang_getNullCursor();
3588
3589 case Decl::ObjCInterface:
3590 // There are two notions of a "definition" for an Objective-C
3591 // class: the interface and its implementation. When we resolved a
3592 // reference to an Objective-C class, produce the @interface as
3593 // the definition; when we were provided with the interface,
3594 // produce the @implementation as the definition.
3595 if (WasReference) {
3596 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3597 return C;
3598 } else if (ObjCImplementationDecl *Impl
3599 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003600 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003601 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003602
Douglas Gregorb6998662010-01-19 19:34:47 +00003603 case Decl::ObjCProperty:
3604 // FIXME: We don't really know where to find the
3605 // ObjCPropertyImplDecls that implement this property.
3606 return clang_getNullCursor();
3607
3608 case Decl::ObjCCompatibleAlias:
3609 if (ObjCInterfaceDecl *Class
3610 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3611 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003612 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003613
Douglas Gregorb6998662010-01-19 19:34:47 +00003614 return clang_getNullCursor();
3615
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003616 case Decl::ObjCForwardProtocol:
3617 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3618 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003619
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003620 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003621 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003622 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003623
3624 case Decl::Friend:
3625 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003626 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003627 return clang_getNullCursor();
3628
3629 case Decl::FriendTemplate:
3630 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003631 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003632 return clang_getNullCursor();
3633 }
3634
3635 return clang_getNullCursor();
3636}
3637
3638unsigned clang_isCursorDefinition(CXCursor C) {
3639 if (!clang_isDeclaration(C.kind))
3640 return 0;
3641
3642 return clang_getCursorDefinition(C) == C;
3643}
3644
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003645unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003646 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003647 return 0;
3648
3649 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3650 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3651 return E->getNumDecls();
3652
3653 if (OverloadedTemplateStorage *S
3654 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3655 return S->size();
3656
3657 Decl *D = Storage.get<Decl*>();
3658 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003659 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003660 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3661 return Classes->size();
3662 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3663 return Protocols->protocol_size();
3664
3665 return 0;
3666}
3667
3668CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003669 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003670 return clang_getNullCursor();
3671
3672 if (index >= clang_getNumOverloadedDecls(cursor))
3673 return clang_getNullCursor();
3674
3675 ASTUnit *Unit = getCursorASTUnit(cursor);
3676 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3677 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3678 return MakeCXCursor(E->decls_begin()[index], Unit);
3679
3680 if (OverloadedTemplateStorage *S
3681 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3682 return MakeCXCursor(S->begin()[index], Unit);
3683
3684 Decl *D = Storage.get<Decl*>();
3685 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3686 // FIXME: This is, unfortunately, linear time.
3687 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3688 std::advance(Pos, index);
3689 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3690 }
3691
3692 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3693 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3694
3695 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3696 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3697
3698 return clang_getNullCursor();
3699}
3700
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003701void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003702 const char **startBuf,
3703 const char **endBuf,
3704 unsigned *startLine,
3705 unsigned *startColumn,
3706 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003707 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003708 assert(getCursorDecl(C) && "CXCursor has null decl");
3709 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003710 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3711 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003712
Steve Naroff4ade6d62009-09-23 17:52:52 +00003713 SourceManager &SM = FD->getASTContext().getSourceManager();
3714 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3715 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3716 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3717 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3718 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3719 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3720}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003721
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003722void clang_enableStackTraces(void) {
3723 llvm::sys::PrintStackTraceOnErrorSignal();
3724}
3725
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003726void clang_executeOnThread(void (*fn)(void*), void *user_data,
3727 unsigned stack_size) {
3728 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3729}
3730
Ted Kremenekfb480492010-01-13 21:46:36 +00003731} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003732
Ted Kremenekfb480492010-01-13 21:46:36 +00003733//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003734// Token-based Operations.
3735//===----------------------------------------------------------------------===//
3736
3737/* CXToken layout:
3738 * int_data[0]: a CXTokenKind
3739 * int_data[1]: starting token location
3740 * int_data[2]: token length
3741 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003742 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003743 * otherwise unused.
3744 */
3745extern "C" {
3746
3747CXTokenKind clang_getTokenKind(CXToken CXTok) {
3748 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3749}
3750
3751CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3752 switch (clang_getTokenKind(CXTok)) {
3753 case CXToken_Identifier:
3754 case CXToken_Keyword:
3755 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003756 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3757 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003758
3759 case CXToken_Literal: {
3760 // We have stashed the starting pointer in the ptr_data field. Use it.
3761 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003762 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003763 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003764
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003765 case CXToken_Punctuation:
3766 case CXToken_Comment:
3767 break;
3768 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003769
3770 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003771 // deconstructing the source location.
3772 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3773 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003774 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003775
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003776 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3777 std::pair<FileID, unsigned> LocInfo
3778 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003779 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003780 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003781 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3782 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003783 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003784
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003785 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003786}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003787
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003788CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3789 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3790 if (!CXXUnit)
3791 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003792
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003793 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3794 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3795}
3796
3797CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3798 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003799 if (!CXXUnit)
3800 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003801
3802 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003803 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3804}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003805
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003806void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3807 CXToken **Tokens, unsigned *NumTokens) {
3808 if (Tokens)
3809 *Tokens = 0;
3810 if (NumTokens)
3811 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003812
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003813 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3814 if (!CXXUnit || !Tokens || !NumTokens)
3815 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003816
Douglas Gregorbdf60622010-03-05 21:16:25 +00003817 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3818
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003819 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820 if (R.isInvalid())
3821 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003822
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003823 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3824 std::pair<FileID, unsigned> BeginLocInfo
3825 = SourceMgr.getDecomposedLoc(R.getBegin());
3826 std::pair<FileID, unsigned> EndLocInfo
3827 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003828
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003829 // Cannot tokenize across files.
3830 if (BeginLocInfo.first != EndLocInfo.first)
3831 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832
3833 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003834 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003835 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003836 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003837 if (Invalid)
3838 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003839
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003840 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3841 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003842 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003843 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003844
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003845 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003846 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003847 llvm::SmallVector<CXToken, 32> CXTokens;
3848 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003849 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003850 do {
3851 // Lex the next token
3852 Lex.LexFromRawLexer(Tok);
3853 if (Tok.is(tok::eof))
3854 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003855
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003856 // Initialize the CXToken.
3857 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 // - Common fields
3860 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3861 CXTok.int_data[2] = Tok.getLength();
3862 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 // - Kind-specific fields
3865 if (Tok.isLiteral()) {
3866 CXTok.int_data[0] = CXToken_Literal;
3867 CXTok.ptr_data = (void *)Tok.getLiteralData();
3868 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003869 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870 std::pair<FileID, unsigned> LocInfo
3871 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003872 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003873 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003874 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3875 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003876 return;
3877
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003878 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003879 IdentifierInfo *II
3880 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003881
David Chisnall096428b2010-10-13 21:44:48 +00003882 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003883 CXTok.int_data[0] = CXToken_Keyword;
3884 }
3885 else {
3886 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3887 CXToken_Identifier
3888 : CXToken_Keyword;
3889 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 CXTok.ptr_data = II;
3891 } else if (Tok.is(tok::comment)) {
3892 CXTok.int_data[0] = CXToken_Comment;
3893 CXTok.ptr_data = 0;
3894 } else {
3895 CXTok.int_data[0] = CXToken_Punctuation;
3896 CXTok.ptr_data = 0;
3897 }
3898 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003899 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003900 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003901
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003902 if (CXTokens.empty())
3903 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003904
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003905 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3906 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3907 *NumTokens = CXTokens.size();
3908}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003909
Ted Kremenek6db61092010-05-05 00:55:15 +00003910void clang_disposeTokens(CXTranslationUnit TU,
3911 CXToken *Tokens, unsigned NumTokens) {
3912 free(Tokens);
3913}
3914
3915} // end: extern "C"
3916
3917//===----------------------------------------------------------------------===//
3918// Token annotation APIs.
3919//===----------------------------------------------------------------------===//
3920
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003921typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003922static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3923 CXCursor parent,
3924 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003925namespace {
3926class AnnotateTokensWorker {
3927 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003928 CXToken *Tokens;
3929 CXCursor *Cursors;
3930 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003931 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003932 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003933 CursorVisitor AnnotateVis;
3934 SourceManager &SrcMgr;
3935
3936 bool MoreTokens() const { return TokIdx < NumTokens; }
3937 unsigned NextToken() const { return TokIdx; }
3938 void AdvanceToken() { ++TokIdx; }
3939 SourceLocation GetTokenLoc(unsigned tokI) {
3940 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3941 }
3942
Ted Kremenek6db61092010-05-05 00:55:15 +00003943public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003944 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003945 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3946 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003947 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003948 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003949 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3950 Decl::MaxPCHLevel, RegionOfInterest),
3951 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003952
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003953 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003954 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003955 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003956 void AnnotateTokens() {
3957 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3958 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003959};
3960}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003961
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003962void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3963 // Walk the AST within the region of interest, annotating tokens
3964 // along the way.
3965 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003966
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003967 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3968 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003969 if (Pos != Annotated.end() &&
3970 (clang_isInvalid(Cursors[I].kind) ||
3971 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003972 Cursors[I] = Pos->second;
3973 }
3974
3975 // Finish up annotating any tokens left.
3976 if (!MoreTokens())
3977 return;
3978
3979 const CXCursor &C = clang_getNullCursor();
3980 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3981 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3982 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003983 }
3984}
3985
Ted Kremenek6db61092010-05-05 00:55:15 +00003986enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003987AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003988 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003989 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003990 if (cursorRange.isInvalid())
3991 return CXChildVisit_Recurse;
3992
Douglas Gregor4419b672010-10-21 06:10:04 +00003993 if (clang_isPreprocessing(cursor.kind)) {
3994 // For macro instantiations, just note where the beginning of the macro
3995 // instantiation occurs.
3996 if (cursor.kind == CXCursor_MacroInstantiation) {
3997 Annotated[Loc.int_data] = cursor;
3998 return CXChildVisit_Recurse;
3999 }
4000
Douglas Gregor4419b672010-10-21 06:10:04 +00004001 // Items in the preprocessing record are kept separate from items in
4002 // declarations, so we keep a separate token index.
4003 unsigned SavedTokIdx = TokIdx;
4004 TokIdx = PreprocessingTokIdx;
4005
4006 // Skip tokens up until we catch up to the beginning of the preprocessing
4007 // entry.
4008 while (MoreTokens()) {
4009 const unsigned I = NextToken();
4010 SourceLocation TokLoc = GetTokenLoc(I);
4011 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4012 case RangeBefore:
4013 AdvanceToken();
4014 continue;
4015 case RangeAfter:
4016 case RangeOverlap:
4017 break;
4018 }
4019 break;
4020 }
4021
4022 // Look at all of the tokens within this range.
4023 while (MoreTokens()) {
4024 const unsigned I = NextToken();
4025 SourceLocation TokLoc = GetTokenLoc(I);
4026 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4027 case RangeBefore:
4028 assert(0 && "Infeasible");
4029 case RangeAfter:
4030 break;
4031 case RangeOverlap:
4032 Cursors[I] = cursor;
4033 AdvanceToken();
4034 continue;
4035 }
4036 break;
4037 }
4038
4039 // Save the preprocessing token index; restore the non-preprocessing
4040 // token index.
4041 PreprocessingTokIdx = TokIdx;
4042 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004043 return CXChildVisit_Recurse;
4044 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004045
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004046 if (cursorRange.isInvalid())
4047 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004048
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004049 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4050
Ted Kremeneka333c662010-05-12 05:29:33 +00004051 // Adjust the annotated range based specific declarations.
4052 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4053 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004054 Decl *D = cxcursor::getCursorDecl(cursor);
4055 // Don't visit synthesized ObjC methods, since they have no syntatic
4056 // representation in the source.
4057 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4058 if (MD->isSynthesized())
4059 return CXChildVisit_Continue;
4060 }
4061 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004062 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4063 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004064 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004065 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004066 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004067 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004068 }
4069 }
4070 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004071
Ted Kremenek3f404602010-08-14 01:14:06 +00004072 // If the location of the cursor occurs within a macro instantiation, record
4073 // the spelling location of the cursor in our annotation map. We can then
4074 // paper over the token labelings during a post-processing step to try and
4075 // get cursor mappings for tokens that are the *arguments* of a macro
4076 // instantiation.
4077 if (L.isMacroID()) {
4078 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4079 // Only invalidate the old annotation if it isn't part of a preprocessing
4080 // directive. Here we assume that the default construction of CXCursor
4081 // results in CXCursor.kind being an initialized value (i.e., 0). If
4082 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004083
Ted Kremenek3f404602010-08-14 01:14:06 +00004084 CXCursor &oldC = Annotated[rawEncoding];
4085 if (!clang_isPreprocessing(oldC.kind))
4086 oldC = cursor;
4087 }
4088
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004089 const enum CXCursorKind K = clang_getCursorKind(parent);
4090 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004091 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4092 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004093
4094 while (MoreTokens()) {
4095 const unsigned I = NextToken();
4096 SourceLocation TokLoc = GetTokenLoc(I);
4097 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4098 case RangeBefore:
4099 Cursors[I] = updateC;
4100 AdvanceToken();
4101 continue;
4102 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004103 case RangeOverlap:
4104 break;
4105 }
4106 break;
4107 }
4108
4109 // Visit children to get their cursor information.
4110 const unsigned BeforeChildren = NextToken();
4111 VisitChildren(cursor);
4112 const unsigned AfterChildren = NextToken();
4113
4114 // Adjust 'Last' to the last token within the extent of the cursor.
4115 while (MoreTokens()) {
4116 const unsigned I = NextToken();
4117 SourceLocation TokLoc = GetTokenLoc(I);
4118 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4119 case RangeBefore:
4120 assert(0 && "Infeasible");
4121 case RangeAfter:
4122 break;
4123 case RangeOverlap:
4124 Cursors[I] = updateC;
4125 AdvanceToken();
4126 continue;
4127 }
4128 break;
4129 }
4130 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004131
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004132 // Scan the tokens that are at the beginning of the cursor, but are not
4133 // capture by the child cursors.
4134
4135 // For AST elements within macros, rely on a post-annotate pass to
4136 // to correctly annotate the tokens with cursors. Otherwise we can
4137 // get confusing results of having tokens that map to cursors that really
4138 // are expanded by an instantiation.
4139 if (L.isMacroID())
4140 cursor = clang_getNullCursor();
4141
4142 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4143 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4144 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004145
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004146 Cursors[I] = cursor;
4147 }
4148 // Scan the tokens that are at the end of the cursor, but are not captured
4149 // but the child cursors.
4150 for (unsigned I = AfterChildren; I != Last; ++I)
4151 Cursors[I] = cursor;
4152
4153 TokIdx = Last;
4154 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004155}
4156
Ted Kremenek6db61092010-05-05 00:55:15 +00004157static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4158 CXCursor parent,
4159 CXClientData client_data) {
4160 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4161}
4162
Ted Kremenekab979612010-11-11 08:05:23 +00004163// This gets run a separate thread to avoid stack blowout.
4164static void runAnnotateTokensWorker(void *UserData) {
4165 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4166}
4167
Ted Kremenek6db61092010-05-05 00:55:15 +00004168extern "C" {
4169
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004170void clang_annotateTokens(CXTranslationUnit TU,
4171 CXToken *Tokens, unsigned NumTokens,
4172 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004173
4174 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004175 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004176
Douglas Gregor4419b672010-10-21 06:10:04 +00004177 // Any token we don't specifically annotate will have a NULL cursor.
4178 CXCursor C = clang_getNullCursor();
4179 for (unsigned I = 0; I != NumTokens; ++I)
4180 Cursors[I] = C;
4181
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004182 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004183 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004184 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004185
Douglas Gregorbdf60622010-03-05 21:16:25 +00004186 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004187
Douglas Gregor0396f462010-03-19 05:22:59 +00004188 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004189 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004190 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4191 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004192 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4193 clang_getTokenLocation(TU,
4194 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004195
Douglas Gregor0396f462010-03-19 05:22:59 +00004196 // A mapping from the source locations found when re-lexing or traversing the
4197 // region of interest to the corresponding cursors.
4198 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004199
4200 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004201 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004202 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4203 std::pair<FileID, unsigned> BeginLocInfo
4204 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4205 std::pair<FileID, unsigned> EndLocInfo
4206 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004207
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004208 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004209 bool Invalid = false;
4210 if (BeginLocInfo.first == EndLocInfo.first &&
4211 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4212 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004213 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4214 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004215 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004216 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004217 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004218
4219 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004220 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004221 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004222 Token Tok;
4223 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004224
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004225 reprocess:
4226 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4227 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004228 // don't see it while preprocessing these tokens later, but keep track
4229 // of all of the token locations inside this preprocessing directive so
4230 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004231 //
4232 // FIXME: Some simple tests here could identify macro definitions and
4233 // #undefs, to provide specific cursor kinds for those.
4234 std::vector<SourceLocation> Locations;
4235 do {
4236 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004237 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004238 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004240 using namespace cxcursor;
4241 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004242 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4243 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004244 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4246 Annotated[Locations[I].getRawEncoding()] = Cursor;
4247 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004248
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004249 if (Tok.isAtStartOfLine())
4250 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004251
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004252 continue;
4253 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004254
Douglas Gregor48072312010-03-18 15:23:44 +00004255 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004256 break;
4257 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004258 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004259
Douglas Gregor0396f462010-03-19 05:22:59 +00004260 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004261 // a specific cursor.
4262 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4263 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004264
4265 // Run the worker within a CrashRecoveryContext.
4266 llvm::CrashRecoveryContext CRC;
4267 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4268 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4269 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004270}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004271} // end: extern "C"
4272
4273//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004274// Operations for querying linkage of a cursor.
4275//===----------------------------------------------------------------------===//
4276
4277extern "C" {
4278CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004279 if (!clang_isDeclaration(cursor.kind))
4280 return CXLinkage_Invalid;
4281
Ted Kremenek16b42592010-03-03 06:36:57 +00004282 Decl *D = cxcursor::getCursorDecl(cursor);
4283 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4284 switch (ND->getLinkage()) {
4285 case NoLinkage: return CXLinkage_NoLinkage;
4286 case InternalLinkage: return CXLinkage_Internal;
4287 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4288 case ExternalLinkage: return CXLinkage_External;
4289 };
4290
4291 return CXLinkage_Invalid;
4292}
4293} // end: extern "C"
4294
4295//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004296// Operations for querying language of a cursor.
4297//===----------------------------------------------------------------------===//
4298
4299static CXLanguageKind getDeclLanguage(const Decl *D) {
4300 switch (D->getKind()) {
4301 default:
4302 break;
4303 case Decl::ImplicitParam:
4304 case Decl::ObjCAtDefsField:
4305 case Decl::ObjCCategory:
4306 case Decl::ObjCCategoryImpl:
4307 case Decl::ObjCClass:
4308 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004309 case Decl::ObjCForwardProtocol:
4310 case Decl::ObjCImplementation:
4311 case Decl::ObjCInterface:
4312 case Decl::ObjCIvar:
4313 case Decl::ObjCMethod:
4314 case Decl::ObjCProperty:
4315 case Decl::ObjCPropertyImpl:
4316 case Decl::ObjCProtocol:
4317 return CXLanguage_ObjC;
4318 case Decl::CXXConstructor:
4319 case Decl::CXXConversion:
4320 case Decl::CXXDestructor:
4321 case Decl::CXXMethod:
4322 case Decl::CXXRecord:
4323 case Decl::ClassTemplate:
4324 case Decl::ClassTemplatePartialSpecialization:
4325 case Decl::ClassTemplateSpecialization:
4326 case Decl::Friend:
4327 case Decl::FriendTemplate:
4328 case Decl::FunctionTemplate:
4329 case Decl::LinkageSpec:
4330 case Decl::Namespace:
4331 case Decl::NamespaceAlias:
4332 case Decl::NonTypeTemplateParm:
4333 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004334 case Decl::TemplateTemplateParm:
4335 case Decl::TemplateTypeParm:
4336 case Decl::UnresolvedUsingTypename:
4337 case Decl::UnresolvedUsingValue:
4338 case Decl::Using:
4339 case Decl::UsingDirective:
4340 case Decl::UsingShadow:
4341 return CXLanguage_CPlusPlus;
4342 }
4343
4344 return CXLanguage_C;
4345}
4346
4347extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004348
4349enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4350 if (clang_isDeclaration(cursor.kind))
4351 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4352 if (D->hasAttr<UnavailableAttr>() ||
4353 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4354 return CXAvailability_Available;
4355
4356 if (D->hasAttr<DeprecatedAttr>())
4357 return CXAvailability_Deprecated;
4358 }
4359
4360 return CXAvailability_Available;
4361}
4362
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004363CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4364 if (clang_isDeclaration(cursor.kind))
4365 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4366
4367 return CXLanguage_Invalid;
4368}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004369
4370CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4371 if (clang_isDeclaration(cursor.kind)) {
4372 if (Decl *D = getCursorDecl(cursor)) {
4373 DeclContext *DC = D->getDeclContext();
4374 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4375 }
4376 }
4377
4378 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4379 if (Decl *D = getCursorDecl(cursor))
4380 return MakeCXCursor(D, getCursorASTUnit(cursor));
4381 }
4382
4383 return clang_getNullCursor();
4384}
4385
4386CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4387 if (clang_isDeclaration(cursor.kind)) {
4388 if (Decl *D = getCursorDecl(cursor)) {
4389 DeclContext *DC = D->getLexicalDeclContext();
4390 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4391 }
4392 }
4393
4394 // FIXME: Note that we can't easily compute the lexical context of a
4395 // statement or expression, so we return nothing.
4396 return clang_getNullCursor();
4397}
4398
Douglas Gregor9f592342010-10-01 20:25:15 +00004399static void CollectOverriddenMethods(DeclContext *Ctx,
4400 ObjCMethodDecl *Method,
4401 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4402 if (!Ctx)
4403 return;
4404
4405 // If we have a class or category implementation, jump straight to the
4406 // interface.
4407 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4408 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4409
4410 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4411 if (!Container)
4412 return;
4413
4414 // Check whether we have a matching method at this level.
4415 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4416 Method->isInstanceMethod()))
4417 if (Method != Overridden) {
4418 // We found an override at this level; there is no need to look
4419 // into other protocols or categories.
4420 Methods.push_back(Overridden);
4421 return;
4422 }
4423
4424 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4425 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4426 PEnd = Protocol->protocol_end();
4427 P != PEnd; ++P)
4428 CollectOverriddenMethods(*P, Method, Methods);
4429 }
4430
4431 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4432 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4433 PEnd = Category->protocol_end();
4434 P != PEnd; ++P)
4435 CollectOverriddenMethods(*P, Method, Methods);
4436 }
4437
4438 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4439 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4440 PEnd = Interface->protocol_end();
4441 P != PEnd; ++P)
4442 CollectOverriddenMethods(*P, Method, Methods);
4443
4444 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4445 Category; Category = Category->getNextClassCategory())
4446 CollectOverriddenMethods(Category, Method, Methods);
4447
4448 // We only look into the superclass if we haven't found anything yet.
4449 if (Methods.empty())
4450 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4451 return CollectOverriddenMethods(Super, Method, Methods);
4452 }
4453}
4454
4455void clang_getOverriddenCursors(CXCursor cursor,
4456 CXCursor **overridden,
4457 unsigned *num_overridden) {
4458 if (overridden)
4459 *overridden = 0;
4460 if (num_overridden)
4461 *num_overridden = 0;
4462 if (!overridden || !num_overridden)
4463 return;
4464
4465 if (!clang_isDeclaration(cursor.kind))
4466 return;
4467
4468 Decl *D = getCursorDecl(cursor);
4469 if (!D)
4470 return;
4471
4472 // Handle C++ member functions.
4473 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4474 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4475 *num_overridden = CXXMethod->size_overridden_methods();
4476 if (!*num_overridden)
4477 return;
4478
4479 *overridden = new CXCursor [*num_overridden];
4480 unsigned I = 0;
4481 for (CXXMethodDecl::method_iterator
4482 M = CXXMethod->begin_overridden_methods(),
4483 MEnd = CXXMethod->end_overridden_methods();
4484 M != MEnd; (void)++M, ++I)
4485 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4486 return;
4487 }
4488
4489 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4490 if (!Method)
4491 return;
4492
4493 // Handle Objective-C methods.
4494 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4495 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4496
4497 if (Methods.empty())
4498 return;
4499
4500 *num_overridden = Methods.size();
4501 *overridden = new CXCursor [Methods.size()];
4502 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4503 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4504}
4505
4506void clang_disposeOverriddenCursors(CXCursor *overridden) {
4507 delete [] overridden;
4508}
4509
Douglas Gregorecdcb882010-10-20 22:00:55 +00004510CXFile clang_getIncludedFile(CXCursor cursor) {
4511 if (cursor.kind != CXCursor_InclusionDirective)
4512 return 0;
4513
4514 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4515 return (void *)ID->getFile();
4516}
4517
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004518} // end: extern "C"
4519
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004520
4521//===----------------------------------------------------------------------===//
4522// C++ AST instrospection.
4523//===----------------------------------------------------------------------===//
4524
4525extern "C" {
4526unsigned clang_CXXMethod_isStatic(CXCursor C) {
4527 if (!clang_isDeclaration(C.kind))
4528 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004529
4530 CXXMethodDecl *Method = 0;
4531 Decl *D = cxcursor::getCursorDecl(C);
4532 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4533 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4534 else
4535 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4536 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004537}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004538
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004539} // end: extern "C"
4540
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004541//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004542// Attribute introspection.
4543//===----------------------------------------------------------------------===//
4544
4545extern "C" {
4546CXType clang_getIBOutletCollectionType(CXCursor C) {
4547 if (C.kind != CXCursor_IBOutletCollectionAttr)
4548 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4549
4550 IBOutletCollectionAttr *A =
4551 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4552
4553 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4554}
4555} // end: extern "C"
4556
4557//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004558// CXString Operations.
4559//===----------------------------------------------------------------------===//
4560
4561extern "C" {
4562const char *clang_getCString(CXString string) {
4563 return string.Spelling;
4564}
4565
4566void clang_disposeString(CXString string) {
4567 if (string.MustFreeString && string.Spelling)
4568 free((void*)string.Spelling);
4569}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004570
Ted Kremenekfb480492010-01-13 21:46:36 +00004571} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004572
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004573namespace clang { namespace cxstring {
4574CXString createCXString(const char *String, bool DupString){
4575 CXString Str;
4576 if (DupString) {
4577 Str.Spelling = strdup(String);
4578 Str.MustFreeString = 1;
4579 } else {
4580 Str.Spelling = String;
4581 Str.MustFreeString = 0;
4582 }
4583 return Str;
4584}
4585
4586CXString createCXString(llvm::StringRef String, bool DupString) {
4587 CXString Result;
4588 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4589 char *Spelling = (char *)malloc(String.size() + 1);
4590 memmove(Spelling, String.data(), String.size());
4591 Spelling[String.size()] = 0;
4592 Result.Spelling = Spelling;
4593 Result.MustFreeString = 1;
4594 } else {
4595 Result.Spelling = String.data();
4596 Result.MustFreeString = 0;
4597 }
4598 return Result;
4599}
4600}}
4601
Ted Kremenek04bb7162010-01-22 22:44:15 +00004602//===----------------------------------------------------------------------===//
4603// Misc. utility functions.
4604//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004605
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004606/// Default to using an 8 MB stack size on "safety" threads.
4607static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004608
4609namespace clang {
4610
4611bool RunSafely(llvm::CrashRecoveryContext &CRC,
4612 void (*Fn)(void*), void *UserData) {
4613 if (unsigned Size = GetSafetyThreadStackSize())
4614 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4615 return CRC.RunSafely(Fn, UserData);
4616}
4617
4618unsigned GetSafetyThreadStackSize() {
4619 return SafetyStackThreadSize;
4620}
4621
4622void SetSafetyThreadStackSize(unsigned Value) {
4623 SafetyStackThreadSize = Value;
4624}
4625
4626}
4627
Ted Kremenek04bb7162010-01-22 22:44:15 +00004628extern "C" {
4629
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004630CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004631 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004632}
4633
4634} // end: extern "C"