blob: af4d7ee1cd39fee53cb69dd9a3e5264ee0b6965c [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);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000333 bool VisitWhileStmt(WhileStmt *S);
334 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000335
Douglas Gregor336fd812010-01-23 00:40:08 +0000336 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000337 bool VisitDeclRefExpr(DeclRefExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000338 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000339 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000340 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000341 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000342 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000343 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000344 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000345 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000346 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
347 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000348 bool VisitInitListExpr(InitListExpr *E);
349 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000350 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000351 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000352 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000353 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
354 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000355 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000356 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000357 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000358 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000359 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000360 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000361 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000362 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000363
364#define DATA_RECURSIVE_VISIT(NAME)\
365bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
366 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000367 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000368 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000369 DATA_RECURSIVE_VISIT(IfStmt)
370 DATA_RECURSIVE_VISIT(MemberExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000371 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000372
373 // Data-recursive visitor functions.
374 bool IsInRegionOfInterest(CXCursor C);
375 bool RunVisitorWorkList(VisitorWorkList &WL);
376 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
377 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000378};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000379
Ted Kremenekab188932010-01-05 19:32:54 +0000380} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000381
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000382static SourceRange getRawCursorExtent(CXCursor C);
383
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000384RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
386}
387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388/// \brief Visit the given cursor and, if requested by the visitor,
389/// its children.
390///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391/// \param Cursor the cursor to visit.
392///
393/// \param CheckRegionOfInterest if true, then the caller already checked that
394/// this cursor is within the region of interest.
395///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396/// \returns true if the visitation should be aborted, false if it
397/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000398bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399 if (clang_isInvalid(Cursor.kind))
400 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000401
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402 if (clang_isDeclaration(Cursor.kind)) {
403 Decl *D = getCursorDecl(Cursor);
404 assert(D && "Invalid declaration cursor");
405 if (D->getPCHLevel() > MaxPCHLevel)
406 return false;
407
408 if (D->isImplicit())
409 return false;
410 }
411
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000412 // If we have a range of interest, and this cursor doesn't intersect with it,
413 // we're done.
414 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000415 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000416 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000417 return false;
418 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000419
Douglas Gregorb1373d02010-01-20 20:59:29 +0000420 switch (Visitor(Cursor, Parent, ClientData)) {
421 case CXChildVisit_Break:
422 return true;
423
424 case CXChildVisit_Continue:
425 return false;
426
427 case CXChildVisit_Recurse:
428 return VisitChildren(Cursor);
429 }
430
Douglas Gregorfd643772010-01-25 16:45:46 +0000431 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432}
433
Douglas Gregor788f5a12010-03-20 00:41:21 +0000434std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
435CursorVisitor::getPreprocessedEntities() {
436 PreprocessingRecord &PPRec
437 = *TU->getPreprocessor().getPreprocessingRecord();
438
439 bool OnlyLocalDecls
440 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
441
442 // There is no region of interest; we have to walk everything.
443 if (RegionOfInterest.isInvalid())
444 return std::make_pair(PPRec.begin(OnlyLocalDecls),
445 PPRec.end(OnlyLocalDecls));
446
447 // Find the file in which the region of interest lands.
448 SourceManager &SM = TU->getSourceManager();
449 std::pair<FileID, unsigned> Begin
450 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
451 std::pair<FileID, unsigned> End
452 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
453
454 // The region of interest spans files; we have to walk everything.
455 if (Begin.first != End.first)
456 return std::make_pair(PPRec.begin(OnlyLocalDecls),
457 PPRec.end(OnlyLocalDecls));
458
459 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
460 = TU->getPreprocessedEntitiesByFile();
461 if (ByFileMap.empty()) {
462 // Build the mapping from files to sets of preprocessed entities.
463 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
464 EEnd = PPRec.end(OnlyLocalDecls);
465 E != EEnd; ++E) {
466 std::pair<FileID, unsigned> P
467 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
468 ByFileMap[P.first].push_back(*E);
469 }
470 }
471
472 return std::make_pair(ByFileMap[Begin.first].begin(),
473 ByFileMap[Begin.first].end());
474}
475
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476/// \brief Visit the children of the given cursor.
477///
478/// \returns true if the visitation should be aborted, false if it
479/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000480bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000481 if (clang_isReference(Cursor.kind)) {
482 // By definition, references have no children.
483 return false;
484 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000485
486 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000488 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000489
Douglas Gregorb1373d02010-01-20 20:59:29 +0000490 if (clang_isDeclaration(Cursor.kind)) {
491 Decl *D = getCursorDecl(Cursor);
492 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000493 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495
Douglas Gregora59e3902010-01-21 23:27:09 +0000496 if (clang_isStatement(Cursor.kind))
497 return Visit(getCursorStmt(Cursor));
498 if (clang_isExpression(Cursor.kind))
499 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000502 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000503 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
504 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000505 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
506 TLEnd = CXXUnit->top_level_end();
507 TL != TLEnd; ++TL) {
508 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000509 return true;
510 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000511 } else if (VisitDeclContext(
512 CXXUnit->getASTContext().getTranslationUnitDecl()))
513 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000514
Douglas Gregor0396f462010-03-19 05:22:59 +0000515 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000516 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 // FIXME: Once we have the ability to deserialize a preprocessing record,
518 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000519 PreprocessingRecord::iterator E, EEnd;
520 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
522 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
523 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000524
Douglas Gregor0396f462010-03-19 05:22:59 +0000525 continue;
526 }
527
528 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
529 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
530 return true;
531
532 continue;
533 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000534
535 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
536 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
537 return true;
538
539 continue;
540 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000541 }
542 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000543 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000544 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000545
Douglas Gregorb1373d02010-01-20 20:59:29 +0000546 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000547 return false;
548}
549
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000550bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000551 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
552 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000553
Ted Kremenek664cffd2010-07-22 11:30:19 +0000554 if (Stmt *Body = B->getBody())
555 return Visit(MakeCXCursor(Body, StmtParent, TU));
556
557 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000558}
559
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000560llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
561 if (RegionOfInterest.isValid()) {
562 SourceRange Range = getRawCursorExtent(Cursor);
563 if (Range.isInvalid())
564 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000565
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000566 switch (CompareRegionOfInterest(Range)) {
567 case RangeBefore:
568 // This declaration comes before the region of interest; skip it.
569 return llvm::Optional<bool>();
570
571 case RangeAfter:
572 // This declaration comes after the region of interest; we're done.
573 return false;
574
575 case RangeOverlap:
576 // This declaration overlaps the region of interest; visit it.
577 break;
578 }
579 }
580 return true;
581}
582
583bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
584 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
585
586 // FIXME: Eventually remove. This part of a hack to support proper
587 // iteration over all Decls contained lexically within an ObjC container.
588 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
589 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
590
591 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000592 Decl *D = *I;
593 if (D->getLexicalDeclContext() != DC)
594 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000595 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000596 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
597 if (!V.hasValue())
598 continue;
599 if (!V.getValue())
600 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000601 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000602 return true;
603 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000604 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000605}
606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
608 llvm_unreachable("Translation units are visited directly by Visit()");
609 return false;
610}
611
612bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
613 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
614 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000615
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000616 return false;
617}
618
619bool CursorVisitor::VisitTagDecl(TagDecl *D) {
620 return VisitDeclContext(D);
621}
622
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000623bool CursorVisitor::VisitClassTemplateSpecializationDecl(
624 ClassTemplateSpecializationDecl *D) {
625 bool ShouldVisitBody = false;
626 switch (D->getSpecializationKind()) {
627 case TSK_Undeclared:
628 case TSK_ImplicitInstantiation:
629 // Nothing to visit
630 return false;
631
632 case TSK_ExplicitInstantiationDeclaration:
633 case TSK_ExplicitInstantiationDefinition:
634 break;
635
636 case TSK_ExplicitSpecialization:
637 ShouldVisitBody = true;
638 break;
639 }
640
641 // Visit the template arguments used in the specialization.
642 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
643 TypeLoc TL = SpecType->getTypeLoc();
644 if (TemplateSpecializationTypeLoc *TSTLoc
645 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
646 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
647 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
648 return true;
649 }
650 }
651
652 if (ShouldVisitBody && VisitCXXRecordDecl(D))
653 return true;
654
655 return false;
656}
657
Douglas Gregor74dbe642010-08-31 19:31:58 +0000658bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
659 ClassTemplatePartialSpecializationDecl *D) {
660 // FIXME: Visit the "outer" template parameter lists on the TagDecl
661 // before visiting these template parameters.
662 if (VisitTemplateParameters(D->getTemplateParameters()))
663 return true;
664
665 // Visit the partial specialization arguments.
666 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
667 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
668 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
669 return true;
670
671 return VisitCXXRecordDecl(D);
672}
673
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000674bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000675 // Visit the default argument.
676 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
677 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
678 if (Visit(DefArg->getTypeLoc()))
679 return true;
680
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000681 return false;
682}
683
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000684bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
685 if (Expr *Init = D->getInitExpr())
686 return Visit(MakeCXCursor(Init, StmtParent, TU));
687 return false;
688}
689
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000690bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
691 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
692 if (Visit(TSInfo->getTypeLoc()))
693 return true;
694
695 return false;
696}
697
Douglas Gregora67e03f2010-09-09 21:42:20 +0000698/// \brief Compare two base or member initializers based on their source order.
699static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
700 CXXBaseOrMemberInitializer const * const *X
701 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
702 CXXBaseOrMemberInitializer const * const *Y
703 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
704
705 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
706 return -1;
707 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
708 return 1;
709 else
710 return 0;
711}
712
Douglas Gregorb1373d02010-01-20 20:59:29 +0000713bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000714 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
715 // Visit the function declaration's syntactic components in the order
716 // written. This requires a bit of work.
717 TypeLoc TL = TSInfo->getTypeLoc();
718 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
719
720 // If we have a function declared directly (without the use of a typedef),
721 // visit just the return type. Otherwise, just visit the function's type
722 // now.
723 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
724 (!FTL && Visit(TL)))
725 return true;
726
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000727 // Visit the nested-name-specifier, if present.
728 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
729 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
730 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000731
732 // Visit the declaration name.
733 if (VisitDeclarationNameInfo(ND->getNameInfo()))
734 return true;
735
736 // FIXME: Visit explicitly-specified template arguments!
737
738 // Visit the function parameters, if we have a function type.
739 if (FTL && VisitFunctionTypeLoc(*FTL, true))
740 return true;
741
742 // FIXME: Attributes?
743 }
744
Douglas Gregora67e03f2010-09-09 21:42:20 +0000745 if (ND->isThisDeclarationADefinition()) {
746 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
747 // Find the initializers that were written in the source.
748 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
749 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
750 IEnd = Constructor->init_end();
751 I != IEnd; ++I) {
752 if (!(*I)->isWritten())
753 continue;
754
755 WrittenInits.push_back(*I);
756 }
757
758 // Sort the initializers in source order
759 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
760 &CompareCXXBaseOrMemberInitializers);
761
762 // Visit the initializers in source order
763 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
764 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
765 if (Init->isMemberInitializer()) {
766 if (Visit(MakeCursorMemberRef(Init->getMember(),
767 Init->getMemberLocation(), TU)))
768 return true;
769 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
770 if (Visit(BaseInfo->getTypeLoc()))
771 return true;
772 }
773
774 // Visit the initializer value.
775 if (Expr *Initializer = Init->getInit())
776 if (Visit(MakeCXCursor(Initializer, ND, TU)))
777 return true;
778 }
779 }
780
781 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
782 return true;
783 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregorb1373d02010-01-20 20:59:29 +0000785 return false;
786}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
789 if (VisitDeclaratorDecl(D))
790 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000791
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000792 if (Expr *BitWidth = D->getBitWidth())
793 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 return false;
796}
797
798bool CursorVisitor::VisitVarDecl(VarDecl *D) {
799 if (VisitDeclaratorDecl(D))
800 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 if (Expr *Init = D->getInit())
803 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 return false;
806}
807
Douglas Gregor84b51d72010-09-01 20:16:53 +0000808bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
809 if (VisitDeclaratorDecl(D))
810 return true;
811
812 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
813 if (Expr *DefArg = D->getDefaultArgument())
814 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
815
816 return false;
817}
818
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000819bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
820 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
821 // before visiting these template parameters.
822 if (VisitTemplateParameters(D->getTemplateParameters()))
823 return true;
824
825 return VisitFunctionDecl(D->getTemplatedDecl());
826}
827
Douglas Gregor39d6f072010-08-31 19:02:00 +0000828bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
829 // FIXME: Visit the "outer" template parameter lists on the TagDecl
830 // before visiting these template parameters.
831 if (VisitTemplateParameters(D->getTemplateParameters()))
832 return true;
833
834 return VisitCXXRecordDecl(D->getTemplatedDecl());
835}
836
Douglas Gregor84b51d72010-09-01 20:16:53 +0000837bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
838 if (VisitTemplateParameters(D->getTemplateParameters()))
839 return true;
840
841 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
842 VisitTemplateArgumentLoc(D->getDefaultArgument()))
843 return true;
844
845 return false;
846}
847
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000849 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
850 if (Visit(TSInfo->getTypeLoc()))
851 return true;
852
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 PEnd = ND->param_end();
855 P != PEnd; ++P) {
856 if (Visit(MakeCXCursor(*P, TU)))
857 return true;
858 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000859
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860 if (ND->isThisDeclarationADefinition() &&
861 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
862 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000863
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000864 return false;
865}
866
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000867namespace {
868 struct ContainerDeclsSort {
869 SourceManager &SM;
870 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
871 bool operator()(Decl *A, Decl *B) {
872 SourceLocation L_A = A->getLocStart();
873 SourceLocation L_B = B->getLocStart();
874 assert(L_A.isValid() && L_B.isValid());
875 return SM.isBeforeInTranslationUnit(L_A, L_B);
876 }
877 };
878}
879
Douglas Gregora59e3902010-01-21 23:27:09 +0000880bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000881 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
882 // an @implementation can lexically contain Decls that are not properly
883 // nested in the AST. When we identify such cases, we need to retrofit
884 // this nesting here.
885 if (!DI_current)
886 return VisitDeclContext(D);
887
888 // Scan the Decls that immediately come after the container
889 // in the current DeclContext. If any fall within the
890 // container's lexical region, stash them into a vector
891 // for later processing.
892 llvm::SmallVector<Decl *, 24> DeclsInContainer;
893 SourceLocation EndLoc = D->getSourceRange().getEnd();
894 SourceManager &SM = TU->getSourceManager();
895 if (EndLoc.isValid()) {
896 DeclContext::decl_iterator next = *DI_current;
897 while (++next != DE_current) {
898 Decl *D_next = *next;
899 if (!D_next)
900 break;
901 SourceLocation L = D_next->getLocStart();
902 if (!L.isValid())
903 break;
904 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
905 *DI_current = next;
906 DeclsInContainer.push_back(D_next);
907 continue;
908 }
909 break;
910 }
911 }
912
913 // The common case.
914 if (DeclsInContainer.empty())
915 return VisitDeclContext(D);
916
917 // Get all the Decls in the DeclContext, and sort them with the
918 // additional ones we've collected. Then visit them.
919 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
920 I!=E; ++I) {
921 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000922 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
923 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000924 continue;
925 DeclsInContainer.push_back(subDecl);
926 }
927
928 // Now sort the Decls so that they appear in lexical order.
929 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
930 ContainerDeclsSort(SM));
931
932 // Now visit the decls.
933 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
934 E = DeclsInContainer.end(); I != E; ++I) {
935 CXCursor Cursor = MakeCXCursor(*I, TU);
936 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
937 if (!V.hasValue())
938 continue;
939 if (!V.getValue())
940 return false;
941 if (Visit(Cursor, true))
942 return true;
943 }
944 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000945}
946
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000948 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
949 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000950 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000951
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000952 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
953 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
954 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000955 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000956 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000957
Douglas Gregora59e3902010-01-21 23:27:09 +0000958 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000959}
960
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000961bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
962 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
963 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
964 E = PID->protocol_end(); I != E; ++I, ++PL)
965 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
966 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000967
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000968 return VisitObjCContainerDecl(PID);
969}
970
Ted Kremenek23173d72010-05-18 21:09:07 +0000971bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000972 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000973 return true;
974
Ted Kremenek23173d72010-05-18 21:09:07 +0000975 // FIXME: This implements a workaround with @property declarations also being
976 // installed in the DeclContext for the @interface. Eventually this code
977 // should be removed.
978 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
979 if (!CDecl || !CDecl->IsClassExtension())
980 return false;
981
982 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
983 if (!ID)
984 return false;
985
986 IdentifierInfo *PropertyId = PD->getIdentifier();
987 ObjCPropertyDecl *prevDecl =
988 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
989
990 if (!prevDecl)
991 return false;
992
993 // Visit synthesized methods since they will be skipped when visiting
994 // the @interface.
995 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000996 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000997 if (Visit(MakeCXCursor(MD, TU)))
998 return true;
999
1000 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001001 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001002 if (Visit(MakeCXCursor(MD, TU)))
1003 return true;
1004
1005 return false;
1006}
1007
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001009 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001010 if (D->getSuperClass() &&
1011 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001013 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001016 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1017 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1018 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001019 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001020 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021
Douglas Gregora59e3902010-01-21 23:27:09 +00001022 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001023}
1024
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001025bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1026 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001027}
1028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001030 // 'ID' could be null when dealing with invalid code.
1031 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1032 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001035 return VisitObjCImplDecl(D);
1036}
1037
1038bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1039#if 0
1040 // Issue callbacks for super class.
1041 // FIXME: No source location information!
1042 if (D->getSuperClass() &&
1043 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045 TU)))
1046 return true;
1047#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001049 return VisitObjCImplDecl(D);
1050}
1051
1052bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1053 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1054 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1055 E = D->protocol_end();
1056 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001057 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001058 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001059
1060 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001061}
1062
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1064 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1065 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1066 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001067
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001068 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001069}
1070
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001071bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1072 return VisitDeclContext(D);
1073}
1074
Douglas Gregor69319002010-08-31 23:48:11 +00001075bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001076 // Visit nested-name-specifier.
1077 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1078 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1079 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001080
1081 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1082 D->getTargetNameLoc(), TU));
1083}
1084
Douglas Gregor7e242562010-09-01 19:52:22 +00001085bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 // Visit nested-name-specifier.
1087 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1088 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1089 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001090
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001091 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1092 return true;
1093
Douglas Gregor7e242562010-09-01 19:52:22 +00001094 return VisitDeclarationNameInfo(D->getNameInfo());
1095}
1096
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001097bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001098 // Visit nested-name-specifier.
1099 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1100 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1101 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001102
1103 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1104 D->getIdentLocation(), TU));
1105}
1106
Douglas Gregor7e242562010-09-01 19:52:22 +00001107bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001108 // Visit nested-name-specifier.
1109 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1110 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1111 return true;
1112
Douglas Gregor7e242562010-09-01 19:52:22 +00001113 return VisitDeclarationNameInfo(D->getNameInfo());
1114}
1115
1116bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1117 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118 // Visit nested-name-specifier.
1119 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1120 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1121 return true;
1122
Douglas Gregor7e242562010-09-01 19:52:22 +00001123 return false;
1124}
1125
Douglas Gregor01829d32010-08-31 14:41:23 +00001126bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1127 switch (Name.getName().getNameKind()) {
1128 case clang::DeclarationName::Identifier:
1129 case clang::DeclarationName::CXXLiteralOperatorName:
1130 case clang::DeclarationName::CXXOperatorName:
1131 case clang::DeclarationName::CXXUsingDirective:
1132 return false;
1133
1134 case clang::DeclarationName::CXXConstructorName:
1135 case clang::DeclarationName::CXXDestructorName:
1136 case clang::DeclarationName::CXXConversionFunctionName:
1137 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1138 return Visit(TSInfo->getTypeLoc());
1139 return false;
1140
1141 case clang::DeclarationName::ObjCZeroArgSelector:
1142 case clang::DeclarationName::ObjCOneArgSelector:
1143 case clang::DeclarationName::ObjCMultiArgSelector:
1144 // FIXME: Per-identifier location info?
1145 return false;
1146 }
1147
1148 return false;
1149}
1150
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001151bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1152 SourceRange Range) {
1153 // FIXME: This whole routine is a hack to work around the lack of proper
1154 // source information in nested-name-specifiers (PR5791). Since we do have
1155 // a beginning source location, we can visit the first component of the
1156 // nested-name-specifier, if it's a single-token component.
1157 if (!NNS)
1158 return false;
1159
1160 // Get the first component in the nested-name-specifier.
1161 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1162 NNS = Prefix;
1163
1164 switch (NNS->getKind()) {
1165 case NestedNameSpecifier::Namespace:
1166 // FIXME: The token at this source location might actually have been a
1167 // namespace alias, but we don't model that. Lame!
1168 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1169 TU));
1170
1171 case NestedNameSpecifier::TypeSpec: {
1172 // If the type has a form where we know that the beginning of the source
1173 // range matches up with a reference cursor. Visit the appropriate reference
1174 // cursor.
1175 Type *T = NNS->getAsType();
1176 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1177 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1178 if (const TagType *Tag = dyn_cast<TagType>(T))
1179 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1180 if (const TemplateSpecializationType *TST
1181 = dyn_cast<TemplateSpecializationType>(T))
1182 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1183 break;
1184 }
1185
1186 case NestedNameSpecifier::TypeSpecWithTemplate:
1187 case NestedNameSpecifier::Global:
1188 case NestedNameSpecifier::Identifier:
1189 break;
1190 }
1191
1192 return false;
1193}
1194
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001195bool CursorVisitor::VisitTemplateParameters(
1196 const TemplateParameterList *Params) {
1197 if (!Params)
1198 return false;
1199
1200 for (TemplateParameterList::const_iterator P = Params->begin(),
1201 PEnd = Params->end();
1202 P != PEnd; ++P) {
1203 if (Visit(MakeCXCursor(*P, TU)))
1204 return true;
1205 }
1206
1207 return false;
1208}
1209
Douglas Gregor0b36e612010-08-31 20:37:03 +00001210bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1211 switch (Name.getKind()) {
1212 case TemplateName::Template:
1213 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1214
1215 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001216 // Visit the overloaded template set.
1217 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1218 return true;
1219
Douglas Gregor0b36e612010-08-31 20:37:03 +00001220 return false;
1221
1222 case TemplateName::DependentTemplate:
1223 // FIXME: Visit nested-name-specifier.
1224 return false;
1225
1226 case TemplateName::QualifiedTemplate:
1227 // FIXME: Visit nested-name-specifier.
1228 return Visit(MakeCursorTemplateRef(
1229 Name.getAsQualifiedTemplateName()->getDecl(),
1230 Loc, TU));
1231 }
1232
1233 return false;
1234}
1235
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001236bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1237 switch (TAL.getArgument().getKind()) {
1238 case TemplateArgument::Null:
1239 case TemplateArgument::Integral:
1240 return false;
1241
1242 case TemplateArgument::Pack:
1243 // FIXME: Implement when variadic templates come along.
1244 return false;
1245
1246 case TemplateArgument::Type:
1247 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1248 return Visit(TSInfo->getTypeLoc());
1249 return false;
1250
1251 case TemplateArgument::Declaration:
1252 if (Expr *E = TAL.getSourceDeclExpression())
1253 return Visit(MakeCXCursor(E, StmtParent, TU));
1254 return false;
1255
1256 case TemplateArgument::Expression:
1257 if (Expr *E = TAL.getSourceExpression())
1258 return Visit(MakeCXCursor(E, StmtParent, TU));
1259 return false;
1260
1261 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001262 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1263 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001264 }
1265
1266 return false;
1267}
1268
Ted Kremeneka0536d82010-05-07 01:04:29 +00001269bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1270 return VisitDeclContext(D);
1271}
1272
Douglas Gregor01829d32010-08-31 14:41:23 +00001273bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1274 return Visit(TL.getUnqualifiedLoc());
1275}
1276
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001277bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1278 ASTContext &Context = TU->getASTContext();
1279
1280 // Some builtin types (such as Objective-C's "id", "sel", and
1281 // "Class") have associated declarations. Create cursors for those.
1282 QualType VisitType;
1283 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001284 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001285 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001286 case BuiltinType::Char_U:
1287 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001288 case BuiltinType::Char16:
1289 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001290 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291 case BuiltinType::UInt:
1292 case BuiltinType::ULong:
1293 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001294 case BuiltinType::UInt128:
1295 case BuiltinType::Char_S:
1296 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001297 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001298 case BuiltinType::Short:
1299 case BuiltinType::Int:
1300 case BuiltinType::Long:
1301 case BuiltinType::LongLong:
1302 case BuiltinType::Int128:
1303 case BuiltinType::Float:
1304 case BuiltinType::Double:
1305 case BuiltinType::LongDouble:
1306 case BuiltinType::NullPtr:
1307 case BuiltinType::Overload:
1308 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001309 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001310
1311 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001312 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001313
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001314 case BuiltinType::ObjCId:
1315 VisitType = Context.getObjCIdType();
1316 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001317
1318 case BuiltinType::ObjCClass:
1319 VisitType = Context.getObjCClassType();
1320 break;
1321
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001322 case BuiltinType::ObjCSel:
1323 VisitType = Context.getObjCSelType();
1324 break;
1325 }
1326
1327 if (!VisitType.isNull()) {
1328 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001329 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001330 TU));
1331 }
1332
1333 return false;
1334}
1335
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001336bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1337 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1338}
1339
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1341 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1342}
1343
1344bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1345 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1346}
1347
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001348bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001349 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001350 // no context information with which we can match up the depth/index in the
1351 // type to the appropriate
1352 return false;
1353}
1354
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001355bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1356 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1357 return true;
1358
John McCallc12c5bb2010-05-15 11:32:37 +00001359 return false;
1360}
1361
1362bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1363 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1364 return true;
1365
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001366 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1367 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1368 TU)))
1369 return true;
1370 }
1371
1372 return false;
1373}
1374
1375bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001376 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001377}
1378
1379bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1380 return Visit(TL.getPointeeLoc());
1381}
1382
1383bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1384 return Visit(TL.getPointeeLoc());
1385}
1386
1387bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1388 return Visit(TL.getPointeeLoc());
1389}
1390
1391bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001392 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393}
1394
1395bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001396 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001397}
1398
Douglas Gregor01829d32010-08-31 14:41:23 +00001399bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1400 bool SkipResultType) {
1401 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001402 return true;
1403
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001404 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001405 if (Decl *D = TL.getArg(I))
1406 if (Visit(MakeCXCursor(D, TU)))
1407 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001408
1409 return false;
1410}
1411
1412bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1413 if (Visit(TL.getElementLoc()))
1414 return true;
1415
1416 if (Expr *Size = TL.getSizeExpr())
1417 return Visit(MakeCXCursor(Size, StmtParent, TU));
1418
1419 return false;
1420}
1421
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001422bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1423 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001424 // Visit the template name.
1425 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1426 TL.getTemplateNameLoc()))
1427 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001428
1429 // Visit the template arguments.
1430 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1431 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1432 return true;
1433
1434 return false;
1435}
1436
Douglas Gregor2332c112010-01-21 20:48:56 +00001437bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1438 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1439}
1440
1441bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1442 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1443 return Visit(TSInfo->getTypeLoc());
1444
1445 return false;
1446}
1447
Douglas Gregora59e3902010-01-21 23:27:09 +00001448bool CursorVisitor::VisitStmt(Stmt *S) {
1449 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1450 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001451 if (Stmt *C = *Child)
1452 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1453 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001454 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001455
Douglas Gregora59e3902010-01-21 23:27:09 +00001456 return false;
1457}
1458
1459bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001460 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001461 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1462 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001463 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001464 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001465 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001466 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001467
Douglas Gregora59e3902010-01-21 23:27:09 +00001468 return false;
1469}
1470
Douglas Gregor36897b02010-09-10 00:22:18 +00001471bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1472 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1473}
1474
Douglas Gregor263b47b2010-01-25 16:12:32 +00001475bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1476 if (VarDecl *Var = S->getConditionVariable()) {
1477 if (Visit(MakeCXCursor(Var, TU)))
1478 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001479 }
1480
Douglas Gregor263b47b2010-01-25 16:12:32 +00001481 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1482 return true;
1483 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001484 return true;
1485
Douglas Gregor263b47b2010-01-25 16:12:32 +00001486 return false;
1487}
1488
1489bool CursorVisitor::VisitForStmt(ForStmt *S) {
1490 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1491 return true;
1492 if (VarDecl *Var = S->getConditionVariable()) {
1493 if (Visit(MakeCXCursor(Var, TU)))
1494 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001495 }
1496
Douglas Gregor263b47b2010-01-25 16:12:32 +00001497 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1498 return true;
1499 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1500 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001501 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1502 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001503
Douglas Gregorf5bab412010-01-22 01:00:11 +00001504 return false;
1505}
1506
Douglas Gregor8947a752010-09-02 20:35:02 +00001507bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1508 // Visit nested-name-specifier, if present.
1509 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1510 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1511 return true;
1512
1513 // Visit declaration name.
1514 if (VisitDeclarationNameInfo(E->getNameInfo()))
1515 return true;
1516
1517 // Visit explicitly-specified template arguments.
1518 if (E->hasExplicitTemplateArgs()) {
1519 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1520 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1521 *ArgEnd = Arg + Args.NumTemplateArgs;
1522 Arg != ArgEnd; ++Arg)
1523 if (VisitTemplateArgumentLoc(*Arg))
1524 return true;
1525 }
1526
1527 return false;
1528}
1529
Ted Kremenek3064ef92010-08-27 21:34:58 +00001530bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1531 if (D->isDefinition()) {
1532 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1533 E = D->bases_end(); I != E; ++I) {
1534 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1535 return true;
1536 }
1537 }
1538
1539 return VisitTagDecl(D);
1540}
1541
1542
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001543bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1544 return Visit(B->getBlockDecl());
1545}
1546
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001547bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001548 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001549 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1550 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001551
1552 // Visit the components of the offsetof expression.
1553 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1554 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1555 const OffsetOfNode &Node = E->getComponent(I);
1556 switch (Node.getKind()) {
1557 case OffsetOfNode::Array:
1558 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1559 StmtParent, TU)))
1560 return true;
1561 break;
1562
1563 case OffsetOfNode::Field:
1564 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1565 TU)))
1566 return true;
1567 break;
1568
1569 case OffsetOfNode::Identifier:
1570 case OffsetOfNode::Base:
1571 continue;
1572 }
1573 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001574
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001575 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001576}
1577
Douglas Gregor336fd812010-01-23 00:40:08 +00001578bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1579 if (E->isArgumentType()) {
1580 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1581 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001582
Douglas Gregor336fd812010-01-23 00:40:08 +00001583 return false;
1584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001585
Douglas Gregor336fd812010-01-23 00:40:08 +00001586 return VisitExpr(E);
1587}
1588
1589bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1590 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1591 if (Visit(TSInfo->getTypeLoc()))
1592 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001593
Douglas Gregor336fd812010-01-23 00:40:08 +00001594 return VisitCastExpr(E);
1595}
1596
1597bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1598 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1599 if (Visit(TSInfo->getTypeLoc()))
1600 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001601
Douglas Gregor336fd812010-01-23 00:40:08 +00001602 return VisitExpr(E);
1603}
1604
Douglas Gregor36897b02010-09-10 00:22:18 +00001605bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1606 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1607}
1608
Douglas Gregor648220e2010-08-10 15:02:34 +00001609bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1610 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1611 Visit(E->getArgTInfo2()->getTypeLoc());
1612}
1613
1614bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1615 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1616 return true;
1617
1618 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1619}
1620
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001621bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1622 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001623 if (InitListExpr *Syntactic = E->getSyntacticForm())
1624 return VisitExpr(Syntactic);
1625
1626 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001627}
1628
1629bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1630 // Visit the designators.
1631 typedef DesignatedInitExpr::Designator Designator;
1632 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1633 DEnd = E->designators_end();
1634 D != DEnd; ++D) {
1635 if (D->isFieldDesignator()) {
1636 if (FieldDecl *Field = D->getField())
1637 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1638 return true;
1639
1640 continue;
1641 }
1642
1643 if (D->isArrayDesignator()) {
1644 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1645 return true;
1646
1647 continue;
1648 }
1649
1650 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1651 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1652 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1653 return true;
1654 }
1655
1656 // Visit the initializer value itself.
1657 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1658}
1659
Douglas Gregor94802292010-09-02 21:20:16 +00001660bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1661 if (E->isTypeOperand()) {
1662 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1663 return Visit(TSInfo->getTypeLoc());
1664
1665 return false;
1666 }
1667
1668 return VisitExpr(E);
1669}
1670
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001671bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1672 if (E->isTypeOperand()) {
1673 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1674 return Visit(TSInfo->getTypeLoc());
1675
1676 return false;
1677 }
1678
1679 return VisitExpr(E);
1680}
1681
Douglas Gregorab6677e2010-09-08 00:15:04 +00001682bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1683 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001684 if (Visit(TSInfo->getTypeLoc()))
1685 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001686
1687 return VisitExpr(E);
1688}
1689
1690bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1691 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1692 return Visit(TSInfo->getTypeLoc());
1693
1694 return false;
1695}
1696
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001697bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1698 // Visit placement arguments.
1699 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1700 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1701 return true;
1702
1703 // Visit the allocated type.
1704 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1705 if (Visit(TSInfo->getTypeLoc()))
1706 return true;
1707
1708 // Visit the array size, if any.
1709 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1710 return true;
1711
1712 // Visit the initializer or constructor arguments.
1713 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1714 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1715 return true;
1716
1717 return false;
1718}
1719
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001720bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1721 // Visit base expression.
1722 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1723 return true;
1724
1725 // Visit the nested-name-specifier.
1726 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1727 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1728 return true;
1729
1730 // Visit the scope type that looks disturbingly like the nested-name-specifier
1731 // but isn't.
1732 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1733 if (Visit(TSInfo->getTypeLoc()))
1734 return true;
1735
1736 // Visit the name of the type being destroyed.
1737 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1738 if (Visit(TSInfo->getTypeLoc()))
1739 return true;
1740
1741 return false;
1742}
1743
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001744bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1745 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1746}
1747
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001748bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001749 // Visit the nested-name-specifier.
1750 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1751 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1752 return true;
1753
1754 // Visit the declaration name.
1755 if (VisitDeclarationNameInfo(E->getNameInfo()))
1756 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001757
1758 // Visit the overloaded declaration reference.
1759 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1760 return true;
1761
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001762 // Visit the explicitly-specified template arguments.
1763 if (const ExplicitTemplateArgumentList *ArgList
1764 = E->getOptionalExplicitTemplateArgs()) {
1765 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1766 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1767 Arg != ArgEnd; ++Arg) {
1768 if (VisitTemplateArgumentLoc(*Arg))
1769 return true;
1770 }
1771 }
1772
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001773 return false;
1774}
1775
Douglas Gregorbfebed22010-09-03 17:24:10 +00001776bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1777 DependentScopeDeclRefExpr *E) {
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->getNameInfo()))
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 Gregorab6677e2010-09-08 00:15:04 +00001801bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1802 CXXUnresolvedConstructExpr *E) {
1803 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1804 if (Visit(TSInfo->getTypeLoc()))
1805 return true;
1806
1807 return VisitExpr(E);
1808}
1809
Douglas Gregor25d63622010-09-03 17:35:34 +00001810bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1811 CXXDependentScopeMemberExpr *E) {
1812 // Visit the base expression, if there is one.
1813 if (!E->isImplicitAccess() &&
1814 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1815 return true;
1816
1817 // Visit the nested-name-specifier.
1818 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1819 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1820 return true;
1821
1822 // Visit the declaration name.
1823 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1824 return true;
1825
1826 // Visit the explicitly-specified template arguments.
1827 if (const ExplicitTemplateArgumentList *ArgList
1828 = E->getOptionalExplicitTemplateArgs()) {
1829 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1830 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1831 Arg != ArgEnd; ++Arg) {
1832 if (VisitTemplateArgumentLoc(*Arg))
1833 return true;
1834 }
1835 }
1836
1837 return false;
1838}
1839
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001840bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1841 // Visit the base expression, if there is one.
1842 if (!E->isImplicitAccess() &&
1843 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1844 return true;
1845
1846 return VisitOverloadExpr(E);
1847}
Douglas Gregor25d63622010-09-03 17:35:34 +00001848
Douglas Gregorc2350e52010-03-08 16:40:19 +00001849bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001850 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1851 if (Visit(TSInfo->getTypeLoc()))
1852 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001853
1854 return VisitExpr(E);
1855}
1856
Douglas Gregor81d34662010-04-20 15:39:42 +00001857bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1858 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1859}
1860
1861
Ted Kremenek09dfa372010-02-18 05:46:33 +00001862bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001863 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1864 i != e; ++i)
1865 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001866 return true;
1867
1868 return false;
1869}
1870
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001871//===----------------------------------------------------------------------===//
1872// Data-recursive visitor methods.
1873//===----------------------------------------------------------------------===//
1874
1875void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1876 CXCursor C = MakeCXCursor(S, StmtParent, TU);
1877 switch (S->getStmtClass()) {
1878 default: {
1879 unsigned size = WL.size();
1880 for (Stmt::child_iterator Child = S->child_begin(),
1881 ChildEnd = S->child_end(); Child != ChildEnd; ++Child) {
1882 if (Stmt *child = *Child) {
1883 WL.push_back(StmtVisit(child, C));
1884 }
1885 }
1886
1887 if (size == WL.size())
1888 return;
1889
1890 // Now reverse the entries we just added. This will match the DFS
1891 // ordering performed by the worklist.
1892 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1893 std::reverse(I, E);
1894 break;
Ted Kremenekf1107452010-11-12 18:26:56 +00001895 }
1896 case Stmt::CXXOperatorCallExprClass: {
1897 CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(S);
1898 // Note that we enqueue things in reverse order so that
1899 // they are visited correctly by the DFS.
1900
1901 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
1902 WL.push_back(StmtVisit(CE->getArg(N-I), C));
1903
1904 WL.push_back(StmtVisit(CE->getCallee(), C));
1905 WL.push_back(StmtVisit(CE->getArg(0), C));
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001906 break;
1907 }
1908 case Stmt::BinaryOperatorClass: {
1909 BinaryOperator *B = cast<BinaryOperator>(S);
1910 WL.push_back(StmtVisit(B->getRHS(), C));
1911 WL.push_back(StmtVisit(B->getLHS(), C));
1912 break;
1913 }
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001914 case Stmt::IfStmtClass: {
1915 IfStmt *If = cast<IfStmt>(S);
1916 WLAddStmt(WL, C, If->getElse());
1917 WLAddStmt(WL, C, If->getThen());
1918 WLAddStmt(WL, C, If->getCond());
1919 WLAddDecl(WL, C, If->getConditionVariable());
1920 break;
1921 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001922 case Stmt::MemberExprClass: {
1923 MemberExpr *M = cast<MemberExpr>(S);
1924 WL.push_back(MemberExprParts(M, C));
1925 WL.push_back(StmtVisit(M->getBase(), C));
1926 break;
1927 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001928 case Stmt::ParenExprClass: {
1929 WL.push_back(StmtVisit(cast<ParenExpr>(S)->getSubExpr(), C));
1930 break;
1931 }
1932 case Stmt::SwitchStmtClass: {
1933 SwitchStmt *SS = cast<SwitchStmt>(S);
1934 if (Stmt *Body = SS->getBody())
1935 WL.push_back(StmtVisit(Body, C));
1936 if (Stmt *Cond = SS->getCond())
1937 WL.push_back(StmtVisit(Cond, C));
1938 if (VarDecl *Var = SS->getConditionVariable())
1939 WL.push_back(DeclVisit(Var, C));
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001940 break;
1941 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001942 }
1943}
1944
1945bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1946 if (RegionOfInterest.isValid()) {
1947 SourceRange Range = getRawCursorExtent(C);
1948 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1949 return false;
1950 }
1951 return true;
1952}
1953
1954bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1955 while (!WL.empty()) {
1956 // Dequeue the worklist item.
1957 VisitorJob LI = WL.back(); WL.pop_back();
1958
1959 // Set the Parent field, then back to its old value once we're done.
1960 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1961
1962 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001963 case VisitorJob::DeclVisitKind: {
1964 Decl *D = cast<DeclVisit>(LI).get();
1965 if (!D)
1966 continue;
1967
1968 // For now, perform default visitation for Decls.
1969 if (Visit(MakeCXCursor(D, TU)))
1970 return true;
1971
1972 continue;
1973 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001974 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001975 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001976 if (!S)
1977 continue;
1978
Ted Kremenekf1107452010-11-12 18:26:56 +00001979 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001980 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1981
1982 switch (S->getStmtClass()) {
1983 default: {
1984 // Perform default visitation for other cases.
1985 if (Visit(Cursor))
1986 return true;
1987 continue;
1988 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001989 case Stmt::BinaryOperatorClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001990 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001991 case Stmt::CaseStmtClass:
1992 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001993 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001994 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001995 case Stmt::DefaultStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001996 case Stmt::IfStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001997 case Stmt::MemberExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001998 case Stmt::ParenExprClass:
1999 case Stmt::SwitchStmtClass:
2000 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002001 if (!IsInRegionOfInterest(Cursor))
2002 continue;
2003 switch (Visitor(Cursor, Parent, ClientData)) {
2004 case CXChildVisit_Break:
2005 return true;
2006 case CXChildVisit_Continue:
2007 break;
2008 case CXChildVisit_Recurse:
2009 EnqueueWorkList(WL, S);
2010 break;
2011 }
2012 }
2013 }
2014 continue;
2015 }
2016 case VisitorJob::MemberExprPartsKind: {
2017 // Handle the other pieces in the MemberExpr besides the base.
2018 MemberExpr *M = cast<MemberExprParts>(LI).get();
2019
2020 // Visit the nested-name-specifier
2021 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2022 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2023 return true;
2024
2025 // Visit the declaration name.
2026 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2027 return true;
2028
2029 // Visit the explicitly-specified template arguments, if any.
2030 if (M->hasExplicitTemplateArgs()) {
2031 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2032 *ArgEnd = Arg + M->getNumTemplateArgs();
2033 Arg != ArgEnd; ++Arg) {
2034 if (VisitTemplateArgumentLoc(*Arg))
2035 return true;
2036 }
2037 }
2038 continue;
2039 }
2040 }
2041 }
2042 return false;
2043}
2044
2045bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2046 VisitorWorkList WL;
2047 EnqueueWorkList(WL, S);
2048 return RunVisitorWorkList(WL);
2049}
2050
2051//===----------------------------------------------------------------------===//
2052// Misc. API hooks.
2053//===----------------------------------------------------------------------===//
2054
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002055static llvm::sys::Mutex EnableMultithreadingMutex;
2056static bool EnabledMultithreading;
2057
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002058extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002059CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2060 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002061 // Disable pretty stack trace functionality, which will otherwise be a very
2062 // poor citizen of the world and set up all sorts of signal handlers.
2063 llvm::DisablePrettyStackTrace = true;
2064
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002065 // We use crash recovery to make some of our APIs more reliable, implicitly
2066 // enable it.
2067 llvm::CrashRecoveryContext::Enable();
2068
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002069 // Enable support for multithreading in LLVM.
2070 {
2071 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2072 if (!EnabledMultithreading) {
2073 llvm::llvm_start_multithreaded();
2074 EnabledMultithreading = true;
2075 }
2076 }
2077
Douglas Gregora030b7c2010-01-22 20:35:53 +00002078 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002079 if (excludeDeclarationsFromPCH)
2080 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002081 if (displayDiagnostics)
2082 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002083 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002084}
2085
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002086void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002087 if (CIdx)
2088 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002089}
2090
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002091CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002092 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002093 if (!CIdx)
2094 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002095
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002096 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002097 FileSystemOptions FileSystemOpts;
2098 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002099
Douglas Gregor28019772010-04-05 23:52:57 +00002100 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002101 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002102 CXXIdx->getOnlyLocalDecls(),
2103 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002104}
2105
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002106unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002107 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002108 CXTranslationUnit_CacheCompletionResults |
2109 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002110}
2111
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002112CXTranslationUnit
2113clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2114 const char *source_filename,
2115 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002116 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002117 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002118 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002119 return clang_parseTranslationUnit(CIdx, source_filename,
2120 command_line_args, num_command_line_args,
2121 unsaved_files, num_unsaved_files,
2122 CXTranslationUnit_DetailedPreprocessingRecord);
2123}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002124
2125struct ParseTranslationUnitInfo {
2126 CXIndex CIdx;
2127 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002128 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002129 int num_command_line_args;
2130 struct CXUnsavedFile *unsaved_files;
2131 unsigned num_unsaved_files;
2132 unsigned options;
2133 CXTranslationUnit result;
2134};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002135static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002136 ParseTranslationUnitInfo *PTUI =
2137 static_cast<ParseTranslationUnitInfo*>(UserData);
2138 CXIndex CIdx = PTUI->CIdx;
2139 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002140 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002141 int num_command_line_args = PTUI->num_command_line_args;
2142 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2143 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2144 unsigned options = PTUI->options;
2145 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002146
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002147 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002148 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002150 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2151
Douglas Gregor44c181a2010-07-23 00:33:23 +00002152 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002153 bool CompleteTranslationUnit
2154 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002155 bool CacheCodeCompetionResults
2156 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002157 bool CXXPrecompilePreamble
2158 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2159 bool CXXChainedPCH
2160 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002161
Douglas Gregor5352ac02010-01-28 00:27:43 +00002162 // Configure the diagnostics.
2163 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002164 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2165 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002166
Douglas Gregor4db64a42010-01-23 00:14:00 +00002167 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2168 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002169 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002170 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002171 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002172 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2173 Buffer));
2174 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002175
Douglas Gregorb10daed2010-10-11 16:52:23 +00002176 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002177
Ted Kremenek139ba862009-10-22 00:03:57 +00002178 // The 'source_filename' argument is optional. If the caller does not
2179 // specify it then it is assumed that the source file is specified
2180 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002181 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002182 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002183
2184 // Since the Clang C library is primarily used by batch tools dealing with
2185 // (often very broken) source code, where spell-checking can have a
2186 // significant negative impact on performance (particularly when
2187 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002188 // Only do this if we haven't found a spell-checking-related argument.
2189 bool FoundSpellCheckingArgument = false;
2190 for (int I = 0; I != num_command_line_args; ++I) {
2191 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2192 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2193 FoundSpellCheckingArgument = true;
2194 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002195 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002196 }
2197 if (!FoundSpellCheckingArgument)
2198 Args.push_back("-fno-spell-checking");
2199
2200 Args.insert(Args.end(), command_line_args,
2201 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002202
Douglas Gregor44c181a2010-07-23 00:33:23 +00002203 // Do we need the detailed preprocessing record?
2204 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002205 Args.push_back("-Xclang");
2206 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002207 }
2208
Douglas Gregorb10daed2010-10-11 16:52:23 +00002209 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002210 llvm::OwningPtr<ASTUnit> Unit(
2211 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2212 Diags,
2213 CXXIdx->getClangResourcesPath(),
2214 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002215 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 RemappedFiles.data(),
2217 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 PrecompilePreamble,
2219 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002220 CacheCodeCompetionResults,
2221 CXXPrecompilePreamble,
2222 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002223
Douglas Gregorb10daed2010-10-11 16:52:23 +00002224 if (NumErrors != Diags->getNumErrors()) {
2225 // Make sure to check that 'Unit' is non-NULL.
2226 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2227 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2228 DEnd = Unit->stored_diag_end();
2229 D != DEnd; ++D) {
2230 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2231 CXString Msg = clang_formatDiagnostic(&Diag,
2232 clang_defaultDiagnosticDisplayOptions());
2233 fprintf(stderr, "%s\n", clang_getCString(Msg));
2234 clang_disposeString(Msg);
2235 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002236#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002237 // On Windows, force a flush, since there may be multiple copies of
2238 // stderr and stdout in the file system, all with different buffers
2239 // but writing to the same device.
2240 fflush(stderr);
2241#endif
2242 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002243 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002244
Douglas Gregorb10daed2010-10-11 16:52:23 +00002245 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002246}
2247CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2248 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002249 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002250 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002251 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002252 unsigned num_unsaved_files,
2253 unsigned options) {
2254 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002255 num_command_line_args, unsaved_files,
2256 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002257 llvm::CrashRecoveryContext CRC;
2258
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002259 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002260 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2261 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2262 fprintf(stderr, " 'command_line_args' : [");
2263 for (int i = 0; i != num_command_line_args; ++i) {
2264 if (i)
2265 fprintf(stderr, ", ");
2266 fprintf(stderr, "'%s'", command_line_args[i]);
2267 }
2268 fprintf(stderr, "],\n");
2269 fprintf(stderr, " 'unsaved_files' : [");
2270 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2271 if (i)
2272 fprintf(stderr, ", ");
2273 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2274 unsaved_files[i].Length);
2275 }
2276 fprintf(stderr, "],\n");
2277 fprintf(stderr, " 'options' : %d,\n", options);
2278 fprintf(stderr, "}\n");
2279
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002280 return 0;
2281 }
2282
2283 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002284}
2285
Douglas Gregor19998442010-08-13 15:35:05 +00002286unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2287 return CXSaveTranslationUnit_None;
2288}
2289
2290int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2291 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002292 if (!TU)
2293 return 1;
2294
2295 return static_cast<ASTUnit *>(TU)->Save(FileName);
2296}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002297
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002298void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002299 if (CTUnit) {
2300 // If the translation unit has been marked as unsafe to free, just discard
2301 // it.
2302 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2303 return;
2304
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002305 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002306 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002307}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002308
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002309unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2310 return CXReparse_None;
2311}
2312
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002313struct ReparseTranslationUnitInfo {
2314 CXTranslationUnit TU;
2315 unsigned num_unsaved_files;
2316 struct CXUnsavedFile *unsaved_files;
2317 unsigned options;
2318 int result;
2319};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002320
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002321static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002322 ReparseTranslationUnitInfo *RTUI =
2323 static_cast<ReparseTranslationUnitInfo*>(UserData);
2324 CXTranslationUnit TU = RTUI->TU;
2325 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2326 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2327 unsigned options = RTUI->options;
2328 (void) options;
2329 RTUI->result = 1;
2330
Douglas Gregorabc563f2010-07-19 21:46:24 +00002331 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002332 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002333
2334 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2335 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002336
2337 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2338 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2339 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2340 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002341 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002342 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2343 Buffer));
2344 }
2345
Douglas Gregor593b0c12010-09-23 18:47:53 +00002346 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2347 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002348}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002349
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002350int clang_reparseTranslationUnit(CXTranslationUnit TU,
2351 unsigned num_unsaved_files,
2352 struct CXUnsavedFile *unsaved_files,
2353 unsigned options) {
2354 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2355 options, 0 };
2356 llvm::CrashRecoveryContext CRC;
2357
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002358 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002359 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002360 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2361 return 1;
2362 }
2363
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002364
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002365 return RTUI.result;
2366}
2367
Douglas Gregordf95a132010-08-09 20:45:32 +00002368
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002369CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002370 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002371 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002372
Steve Naroff77accc12009-09-03 18:19:54 +00002373 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002374 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002375}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002376
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002377CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002378 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002379 return Result;
2380}
2381
Ted Kremenekfb480492010-01-13 21:46:36 +00002382} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002383
Ted Kremenekfb480492010-01-13 21:46:36 +00002384//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002385// CXSourceLocation and CXSourceRange Operations.
2386//===----------------------------------------------------------------------===//
2387
Douglas Gregorb9790342010-01-22 21:44:22 +00002388extern "C" {
2389CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002390 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002391 return Result;
2392}
2393
2394unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002395 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2396 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2397 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002398}
2399
2400CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2401 CXFile file,
2402 unsigned line,
2403 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002404 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002405 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002406
Douglas Gregorb9790342010-01-22 21:44:22 +00002407 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2408 SourceLocation SLoc
2409 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002410 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002411 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002412 if (SLoc.isInvalid()) return clang_getNullLocation();
2413
2414 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2415}
2416
2417CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2418 CXFile file,
2419 unsigned offset) {
2420 if (!tu || !file)
2421 return clang_getNullLocation();
2422
2423 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2424 SourceLocation Start
2425 = CXXUnit->getSourceManager().getLocation(
2426 static_cast<const FileEntry *>(file),
2427 1, 1);
2428 if (Start.isInvalid()) return clang_getNullLocation();
2429
2430 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2431
2432 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002433
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002434 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002435}
2436
Douglas Gregor5352ac02010-01-28 00:27:43 +00002437CXSourceRange clang_getNullRange() {
2438 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2439 return Result;
2440}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002441
Douglas Gregor5352ac02010-01-28 00:27:43 +00002442CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2443 if (begin.ptr_data[0] != end.ptr_data[0] ||
2444 begin.ptr_data[1] != end.ptr_data[1])
2445 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002446
2447 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002448 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002449 return Result;
2450}
2451
Douglas Gregor46766dc2010-01-26 19:19:08 +00002452void clang_getInstantiationLocation(CXSourceLocation location,
2453 CXFile *file,
2454 unsigned *line,
2455 unsigned *column,
2456 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002457 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2458
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002459 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002460 if (file)
2461 *file = 0;
2462 if (line)
2463 *line = 0;
2464 if (column)
2465 *column = 0;
2466 if (offset)
2467 *offset = 0;
2468 return;
2469 }
2470
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002471 const SourceManager &SM =
2472 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002473 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002474
2475 if (file)
2476 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2477 if (line)
2478 *line = SM.getInstantiationLineNumber(InstLoc);
2479 if (column)
2480 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002481 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002482 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002483}
2484
Douglas Gregora9b06d42010-11-09 06:24:54 +00002485void clang_getSpellingLocation(CXSourceLocation location,
2486 CXFile *file,
2487 unsigned *line,
2488 unsigned *column,
2489 unsigned *offset) {
2490 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2491
2492 if (!location.ptr_data[0] || Loc.isInvalid()) {
2493 if (file)
2494 *file = 0;
2495 if (line)
2496 *line = 0;
2497 if (column)
2498 *column = 0;
2499 if (offset)
2500 *offset = 0;
2501 return;
2502 }
2503
2504 const SourceManager &SM =
2505 *static_cast<const SourceManager*>(location.ptr_data[0]);
2506 SourceLocation SpellLoc = Loc;
2507 if (SpellLoc.isMacroID()) {
2508 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2509 if (SimpleSpellingLoc.isFileID() &&
2510 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2511 SpellLoc = SimpleSpellingLoc;
2512 else
2513 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2514 }
2515
2516 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2517 FileID FID = LocInfo.first;
2518 unsigned FileOffset = LocInfo.second;
2519
2520 if (file)
2521 *file = (void *)SM.getFileEntryForID(FID);
2522 if (line)
2523 *line = SM.getLineNumber(FID, FileOffset);
2524 if (column)
2525 *column = SM.getColumnNumber(FID, FileOffset);
2526 if (offset)
2527 *offset = FileOffset;
2528}
2529
Douglas Gregor1db19de2010-01-19 21:36:55 +00002530CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002531 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002532 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002533 return Result;
2534}
2535
2536CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002537 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002538 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002539 return Result;
2540}
2541
Douglas Gregorb9790342010-01-22 21:44:22 +00002542} // end: extern "C"
2543
Douglas Gregor1db19de2010-01-19 21:36:55 +00002544//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002545// CXFile Operations.
2546//===----------------------------------------------------------------------===//
2547
2548extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002549CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002550 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002551 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002552
Steve Naroff88145032009-10-27 14:35:18 +00002553 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002554 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002555}
2556
2557time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002558 if (!SFile)
2559 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002560
Steve Naroff88145032009-10-27 14:35:18 +00002561 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2562 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002563}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002564
Douglas Gregorb9790342010-01-22 21:44:22 +00002565CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2566 if (!tu)
2567 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002568
Douglas Gregorb9790342010-01-22 21:44:22 +00002569 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002570
Douglas Gregorb9790342010-01-22 21:44:22 +00002571 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002572 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2573 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002574 return const_cast<FileEntry *>(File);
2575}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002576
Ted Kremenekfb480492010-01-13 21:46:36 +00002577} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002578
Ted Kremenekfb480492010-01-13 21:46:36 +00002579//===----------------------------------------------------------------------===//
2580// CXCursor Operations.
2581//===----------------------------------------------------------------------===//
2582
Ted Kremenekfb480492010-01-13 21:46:36 +00002583static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002584 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2585 return getDeclFromExpr(CE->getSubExpr());
2586
Ted Kremenekfb480492010-01-13 21:46:36 +00002587 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2588 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002589 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2590 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002591 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2592 return ME->getMemberDecl();
2593 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2594 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002595 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2596 return PRE->getProperty();
2597
Ted Kremenekfb480492010-01-13 21:46:36 +00002598 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2599 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002600 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2601 if (!CE->isElidable())
2602 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002603 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2604 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002605
Douglas Gregordb1314e2010-10-01 21:11:22 +00002606 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2607 return PE->getProtocol();
2608
Ted Kremenekfb480492010-01-13 21:46:36 +00002609 return 0;
2610}
2611
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002612static SourceLocation getLocationFromExpr(Expr *E) {
2613 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2614 return /*FIXME:*/Msg->getLeftLoc();
2615 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2616 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002617 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2618 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002619 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2620 return Member->getMemberLoc();
2621 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2622 return Ivar->getLocation();
2623 return E->getLocStart();
2624}
2625
Ted Kremenekfb480492010-01-13 21:46:36 +00002626extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002627
2628unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002629 CXCursorVisitor visitor,
2630 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002631 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002632
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002633 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2634 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002635 return CursorVis.VisitChildren(parent);
2636}
2637
David Chisnall3387c652010-11-03 14:12:26 +00002638#ifndef __has_feature
2639#define __has_feature(x) 0
2640#endif
2641#if __has_feature(blocks)
2642typedef enum CXChildVisitResult
2643 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2644
2645static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2646 CXClientData client_data) {
2647 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2648 return block(cursor, parent);
2649}
2650#else
2651// If we are compiled with a compiler that doesn't have native blocks support,
2652// define and call the block manually, so the
2653typedef struct _CXChildVisitResult
2654{
2655 void *isa;
2656 int flags;
2657 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002658 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2659 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002660} *CXCursorVisitorBlock;
2661
2662static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2663 CXClientData client_data) {
2664 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2665 return block->invoke(block, cursor, parent);
2666}
2667#endif
2668
2669
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002670unsigned clang_visitChildrenWithBlock(CXCursor parent,
2671 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002672 return clang_visitChildren(parent, visitWithBlock, block);
2673}
2674
Douglas Gregor78205d42010-01-20 21:45:58 +00002675static CXString getDeclSpelling(Decl *D) {
2676 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2677 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002678 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002679
Douglas Gregor78205d42010-01-20 21:45:58 +00002680 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002681 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002682
Douglas Gregor78205d42010-01-20 21:45:58 +00002683 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2684 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2685 // and returns different names. NamedDecl returns the class name and
2686 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002687 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002688
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002689 if (isa<UsingDirectiveDecl>(D))
2690 return createCXString("");
2691
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002692 llvm::SmallString<1024> S;
2693 llvm::raw_svector_ostream os(S);
2694 ND->printName(os);
2695
2696 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002697}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002698
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002699CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002700 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002701 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002702
Steve Narofff334b4e2009-09-02 18:26:48 +00002703 if (clang_isReference(C.kind)) {
2704 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002705 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002706 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002707 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002708 }
2709 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002710 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002711 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002712 }
2713 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002714 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002715 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002716 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002717 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002718 case CXCursor_CXXBaseSpecifier: {
2719 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2720 return createCXString(B->getType().getAsString());
2721 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002722 case CXCursor_TypeRef: {
2723 TypeDecl *Type = getCursorTypeRef(C).first;
2724 assert(Type && "Missing type decl");
2725
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002726 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2727 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002728 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002729 case CXCursor_TemplateRef: {
2730 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002731 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002732
2733 return createCXString(Template->getNameAsString());
2734 }
Douglas Gregor69319002010-08-31 23:48:11 +00002735
2736 case CXCursor_NamespaceRef: {
2737 NamedDecl *NS = getCursorNamespaceRef(C).first;
2738 assert(NS && "Missing namespace decl");
2739
2740 return createCXString(NS->getNameAsString());
2741 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002742
Douglas Gregora67e03f2010-09-09 21:42:20 +00002743 case CXCursor_MemberRef: {
2744 FieldDecl *Field = getCursorMemberRef(C).first;
2745 assert(Field && "Missing member decl");
2746
2747 return createCXString(Field->getNameAsString());
2748 }
2749
Douglas Gregor36897b02010-09-10 00:22:18 +00002750 case CXCursor_LabelRef: {
2751 LabelStmt *Label = getCursorLabelRef(C).first;
2752 assert(Label && "Missing label");
2753
2754 return createCXString(Label->getID()->getName());
2755 }
2756
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002757 case CXCursor_OverloadedDeclRef: {
2758 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2759 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2760 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2761 return createCXString(ND->getNameAsString());
2762 return createCXString("");
2763 }
2764 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2765 return createCXString(E->getName().getAsString());
2766 OverloadedTemplateStorage *Ovl
2767 = Storage.get<OverloadedTemplateStorage*>();
2768 if (Ovl->size() == 0)
2769 return createCXString("");
2770 return createCXString((*Ovl->begin())->getNameAsString());
2771 }
2772
Daniel Dunbaracca7252009-11-30 20:42:49 +00002773 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002774 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002775 }
2776 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002777
2778 if (clang_isExpression(C.kind)) {
2779 Decl *D = getDeclFromExpr(getCursorExpr(C));
2780 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002781 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002782 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002783 }
2784
Douglas Gregor36897b02010-09-10 00:22:18 +00002785 if (clang_isStatement(C.kind)) {
2786 Stmt *S = getCursorStmt(C);
2787 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2788 return createCXString(Label->getID()->getName());
2789
2790 return createCXString("");
2791 }
2792
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002793 if (C.kind == CXCursor_MacroInstantiation)
2794 return createCXString(getCursorMacroInstantiation(C)->getName()
2795 ->getNameStart());
2796
Douglas Gregor572feb22010-03-18 18:04:21 +00002797 if (C.kind == CXCursor_MacroDefinition)
2798 return createCXString(getCursorMacroDefinition(C)->getName()
2799 ->getNameStart());
2800
Douglas Gregorecdcb882010-10-20 22:00:55 +00002801 if (C.kind == CXCursor_InclusionDirective)
2802 return createCXString(getCursorInclusionDirective(C)->getFileName());
2803
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002804 if (clang_isDeclaration(C.kind))
2805 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002806
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002807 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002808}
2809
Douglas Gregor358559d2010-10-02 22:49:11 +00002810CXString clang_getCursorDisplayName(CXCursor C) {
2811 if (!clang_isDeclaration(C.kind))
2812 return clang_getCursorSpelling(C);
2813
2814 Decl *D = getCursorDecl(C);
2815 if (!D)
2816 return createCXString("");
2817
2818 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2819 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2820 D = FunTmpl->getTemplatedDecl();
2821
2822 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2823 llvm::SmallString<64> Str;
2824 llvm::raw_svector_ostream OS(Str);
2825 OS << Function->getNameAsString();
2826 if (Function->getPrimaryTemplate())
2827 OS << "<>";
2828 OS << "(";
2829 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2830 if (I)
2831 OS << ", ";
2832 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2833 }
2834
2835 if (Function->isVariadic()) {
2836 if (Function->getNumParams())
2837 OS << ", ";
2838 OS << "...";
2839 }
2840 OS << ")";
2841 return createCXString(OS.str());
2842 }
2843
2844 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2845 llvm::SmallString<64> Str;
2846 llvm::raw_svector_ostream OS(Str);
2847 OS << ClassTemplate->getNameAsString();
2848 OS << "<";
2849 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2850 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2851 if (I)
2852 OS << ", ";
2853
2854 NamedDecl *Param = Params->getParam(I);
2855 if (Param->getIdentifier()) {
2856 OS << Param->getIdentifier()->getName();
2857 continue;
2858 }
2859
2860 // There is no parameter name, which makes this tricky. Try to come up
2861 // with something useful that isn't too long.
2862 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2863 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2864 else if (NonTypeTemplateParmDecl *NTTP
2865 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2866 OS << NTTP->getType().getAsString(Policy);
2867 else
2868 OS << "template<...> class";
2869 }
2870
2871 OS << ">";
2872 return createCXString(OS.str());
2873 }
2874
2875 if (ClassTemplateSpecializationDecl *ClassSpec
2876 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2877 // If the type was explicitly written, use that.
2878 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2879 return createCXString(TSInfo->getType().getAsString(Policy));
2880
2881 llvm::SmallString<64> Str;
2882 llvm::raw_svector_ostream OS(Str);
2883 OS << ClassSpec->getNameAsString();
2884 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002885 ClassSpec->getTemplateArgs().data(),
2886 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002887 Policy);
2888 return createCXString(OS.str());
2889 }
2890
2891 return clang_getCursorSpelling(C);
2892}
2893
Ted Kremeneke68fff62010-02-17 00:41:32 +00002894CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002895 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002896 case CXCursor_FunctionDecl:
2897 return createCXString("FunctionDecl");
2898 case CXCursor_TypedefDecl:
2899 return createCXString("TypedefDecl");
2900 case CXCursor_EnumDecl:
2901 return createCXString("EnumDecl");
2902 case CXCursor_EnumConstantDecl:
2903 return createCXString("EnumConstantDecl");
2904 case CXCursor_StructDecl:
2905 return createCXString("StructDecl");
2906 case CXCursor_UnionDecl:
2907 return createCXString("UnionDecl");
2908 case CXCursor_ClassDecl:
2909 return createCXString("ClassDecl");
2910 case CXCursor_FieldDecl:
2911 return createCXString("FieldDecl");
2912 case CXCursor_VarDecl:
2913 return createCXString("VarDecl");
2914 case CXCursor_ParmDecl:
2915 return createCXString("ParmDecl");
2916 case CXCursor_ObjCInterfaceDecl:
2917 return createCXString("ObjCInterfaceDecl");
2918 case CXCursor_ObjCCategoryDecl:
2919 return createCXString("ObjCCategoryDecl");
2920 case CXCursor_ObjCProtocolDecl:
2921 return createCXString("ObjCProtocolDecl");
2922 case CXCursor_ObjCPropertyDecl:
2923 return createCXString("ObjCPropertyDecl");
2924 case CXCursor_ObjCIvarDecl:
2925 return createCXString("ObjCIvarDecl");
2926 case CXCursor_ObjCInstanceMethodDecl:
2927 return createCXString("ObjCInstanceMethodDecl");
2928 case CXCursor_ObjCClassMethodDecl:
2929 return createCXString("ObjCClassMethodDecl");
2930 case CXCursor_ObjCImplementationDecl:
2931 return createCXString("ObjCImplementationDecl");
2932 case CXCursor_ObjCCategoryImplDecl:
2933 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002934 case CXCursor_CXXMethod:
2935 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002936 case CXCursor_UnexposedDecl:
2937 return createCXString("UnexposedDecl");
2938 case CXCursor_ObjCSuperClassRef:
2939 return createCXString("ObjCSuperClassRef");
2940 case CXCursor_ObjCProtocolRef:
2941 return createCXString("ObjCProtocolRef");
2942 case CXCursor_ObjCClassRef:
2943 return createCXString("ObjCClassRef");
2944 case CXCursor_TypeRef:
2945 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002946 case CXCursor_TemplateRef:
2947 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002948 case CXCursor_NamespaceRef:
2949 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002950 case CXCursor_MemberRef:
2951 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002952 case CXCursor_LabelRef:
2953 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002954 case CXCursor_OverloadedDeclRef:
2955 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002956 case CXCursor_UnexposedExpr:
2957 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002958 case CXCursor_BlockExpr:
2959 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002960 case CXCursor_DeclRefExpr:
2961 return createCXString("DeclRefExpr");
2962 case CXCursor_MemberRefExpr:
2963 return createCXString("MemberRefExpr");
2964 case CXCursor_CallExpr:
2965 return createCXString("CallExpr");
2966 case CXCursor_ObjCMessageExpr:
2967 return createCXString("ObjCMessageExpr");
2968 case CXCursor_UnexposedStmt:
2969 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002970 case CXCursor_LabelStmt:
2971 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002972 case CXCursor_InvalidFile:
2973 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002974 case CXCursor_InvalidCode:
2975 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002976 case CXCursor_NoDeclFound:
2977 return createCXString("NoDeclFound");
2978 case CXCursor_NotImplemented:
2979 return createCXString("NotImplemented");
2980 case CXCursor_TranslationUnit:
2981 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002982 case CXCursor_UnexposedAttr:
2983 return createCXString("UnexposedAttr");
2984 case CXCursor_IBActionAttr:
2985 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002986 case CXCursor_IBOutletAttr:
2987 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002988 case CXCursor_IBOutletCollectionAttr:
2989 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002990 case CXCursor_PreprocessingDirective:
2991 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002992 case CXCursor_MacroDefinition:
2993 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002994 case CXCursor_MacroInstantiation:
2995 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002996 case CXCursor_InclusionDirective:
2997 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002998 case CXCursor_Namespace:
2999 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003000 case CXCursor_LinkageSpec:
3001 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003002 case CXCursor_CXXBaseSpecifier:
3003 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003004 case CXCursor_Constructor:
3005 return createCXString("CXXConstructor");
3006 case CXCursor_Destructor:
3007 return createCXString("CXXDestructor");
3008 case CXCursor_ConversionFunction:
3009 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003010 case CXCursor_TemplateTypeParameter:
3011 return createCXString("TemplateTypeParameter");
3012 case CXCursor_NonTypeTemplateParameter:
3013 return createCXString("NonTypeTemplateParameter");
3014 case CXCursor_TemplateTemplateParameter:
3015 return createCXString("TemplateTemplateParameter");
3016 case CXCursor_FunctionTemplate:
3017 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003018 case CXCursor_ClassTemplate:
3019 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003020 case CXCursor_ClassTemplatePartialSpecialization:
3021 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003022 case CXCursor_NamespaceAlias:
3023 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003024 case CXCursor_UsingDirective:
3025 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003026 case CXCursor_UsingDeclaration:
3027 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003028 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003029
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003030 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003031 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003032}
Steve Naroff89922f82009-08-31 00:59:03 +00003033
Ted Kremeneke68fff62010-02-17 00:41:32 +00003034enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3035 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003036 CXClientData client_data) {
3037 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003038
3039 // If our current best cursor is the construction of a temporary object,
3040 // don't replace that cursor with a type reference, because we want
3041 // clang_getCursor() to point at the constructor.
3042 if (clang_isExpression(BestCursor->kind) &&
3043 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3044 cursor.kind == CXCursor_TypeRef)
3045 return CXChildVisit_Recurse;
3046
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003047 *BestCursor = cursor;
3048 return CXChildVisit_Recurse;
3049}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003050
Douglas Gregorb9790342010-01-22 21:44:22 +00003051CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3052 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003053 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003054
Douglas Gregorb9790342010-01-22 21:44:22 +00003055 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003056 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3057
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003058 // Translate the given source location to make it point at the beginning of
3059 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003060 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003061
3062 // Guard against an invalid SourceLocation, or we may assert in one
3063 // of the following calls.
3064 if (SLoc.isInvalid())
3065 return clang_getNullCursor();
3066
Douglas Gregor40749ee2010-11-03 00:35:38 +00003067 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003068 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3069 CXXUnit->getASTContext().getLangOptions());
3070
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003071 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3072 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003073 // FIXME: Would be great to have a "hint" cursor, then walk from that
3074 // hint cursor upward until we find a cursor whose source range encloses
3075 // the region of interest, rather than starting from the translation unit.
3076 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003077 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003078 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003079 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003080 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003081
3082 if (Logging) {
3083 CXFile SearchFile;
3084 unsigned SearchLine, SearchColumn;
3085 CXFile ResultFile;
3086 unsigned ResultLine, ResultColumn;
3087 CXString SearchFileName, ResultFileName, KindSpelling;
3088 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3089
3090 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3091 0);
3092 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3093 &ResultColumn, 0);
3094 SearchFileName = clang_getFileName(SearchFile);
3095 ResultFileName = clang_getFileName(ResultFile);
3096 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3097 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3098 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3099 clang_getCString(KindSpelling),
3100 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3101 clang_disposeString(SearchFileName);
3102 clang_disposeString(ResultFileName);
3103 clang_disposeString(KindSpelling);
3104 }
3105
Ted Kremeneke68fff62010-02-17 00:41:32 +00003106 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003107}
3108
Ted Kremenek73885552009-11-17 19:28:59 +00003109CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003110 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003111}
3112
3113unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003114 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003115}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003116
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003117unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003118 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3119}
3120
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003121unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003122 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3123}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003124
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003125unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003126 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3127}
3128
Douglas Gregor97b98722010-01-19 23:20:36 +00003129unsigned clang_isExpression(enum CXCursorKind K) {
3130 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3131}
3132
3133unsigned clang_isStatement(enum CXCursorKind K) {
3134 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3135}
3136
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003137unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3138 return K == CXCursor_TranslationUnit;
3139}
3140
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003141unsigned clang_isPreprocessing(enum CXCursorKind K) {
3142 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3143}
3144
Ted Kremenekad6eff62010-03-08 21:17:29 +00003145unsigned clang_isUnexposed(enum CXCursorKind K) {
3146 switch (K) {
3147 case CXCursor_UnexposedDecl:
3148 case CXCursor_UnexposedExpr:
3149 case CXCursor_UnexposedStmt:
3150 case CXCursor_UnexposedAttr:
3151 return true;
3152 default:
3153 return false;
3154 }
3155}
3156
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003157CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003158 return C.kind;
3159}
3160
Douglas Gregor98258af2010-01-18 22:46:11 +00003161CXSourceLocation clang_getCursorLocation(CXCursor C) {
3162 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003163 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003164 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003165 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3166 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003167 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003168 }
3169
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003170 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003171 std::pair<ObjCProtocolDecl *, SourceLocation> P
3172 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003173 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003174 }
3175
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003176 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003177 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3178 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003179 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003180 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003181
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003182 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003183 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003184 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003185 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003186
3187 case CXCursor_TemplateRef: {
3188 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3189 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3190 }
3191
Douglas Gregor69319002010-08-31 23:48:11 +00003192 case CXCursor_NamespaceRef: {
3193 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3194 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3195 }
3196
Douglas Gregora67e03f2010-09-09 21:42:20 +00003197 case CXCursor_MemberRef: {
3198 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3199 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3200 }
3201
Ted Kremenek3064ef92010-08-27 21:34:58 +00003202 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003203 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3204 if (!BaseSpec)
3205 return clang_getNullLocation();
3206
3207 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3208 return cxloc::translateSourceLocation(getCursorContext(C),
3209 TSInfo->getTypeLoc().getBeginLoc());
3210
3211 return cxloc::translateSourceLocation(getCursorContext(C),
3212 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003213 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003214
Douglas Gregor36897b02010-09-10 00:22:18 +00003215 case CXCursor_LabelRef: {
3216 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3217 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3218 }
3219
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003220 case CXCursor_OverloadedDeclRef:
3221 return cxloc::translateSourceLocation(getCursorContext(C),
3222 getCursorOverloadedDeclRef(C).second);
3223
Douglas Gregorf46034a2010-01-18 23:41:10 +00003224 default:
3225 // FIXME: Need a way to enumerate all non-reference cases.
3226 llvm_unreachable("Missed a reference kind");
3227 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003228 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003229
3230 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003231 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003232 getLocationFromExpr(getCursorExpr(C)));
3233
Douglas Gregor36897b02010-09-10 00:22:18 +00003234 if (clang_isStatement(C.kind))
3235 return cxloc::translateSourceLocation(getCursorContext(C),
3236 getCursorStmt(C)->getLocStart());
3237
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003238 if (C.kind == CXCursor_PreprocessingDirective) {
3239 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3240 return cxloc::translateSourceLocation(getCursorContext(C), L);
3241 }
Douglas Gregor48072312010-03-18 15:23:44 +00003242
3243 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003244 SourceLocation L
3245 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003246 return cxloc::translateSourceLocation(getCursorContext(C), L);
3247 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003248
3249 if (C.kind == CXCursor_MacroDefinition) {
3250 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3251 return cxloc::translateSourceLocation(getCursorContext(C), L);
3252 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003253
3254 if (C.kind == CXCursor_InclusionDirective) {
3255 SourceLocation L
3256 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3257 return cxloc::translateSourceLocation(getCursorContext(C), L);
3258 }
3259
Ted Kremenek9a700d22010-05-12 06:16:13 +00003260 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003261 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003262
Douglas Gregorf46034a2010-01-18 23:41:10 +00003263 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003264 SourceLocation Loc = D->getLocation();
3265 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3266 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003267 // FIXME: Multiple variables declared in a single declaration
3268 // currently lack the information needed to correctly determine their
3269 // ranges when accounting for the type-specifier. We use context
3270 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3271 // and if so, whether it is the first decl.
3272 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3273 if (!cxcursor::isFirstInDeclGroup(C))
3274 Loc = VD->getLocation();
3275 }
3276
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003277 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003278}
Douglas Gregora7bde202010-01-19 00:34:46 +00003279
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003280} // end extern "C"
3281
3282static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003283 if (clang_isReference(C.kind)) {
3284 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003285 case CXCursor_ObjCSuperClassRef:
3286 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003287
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003288 case CXCursor_ObjCProtocolRef:
3289 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003290
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003291 case CXCursor_ObjCClassRef:
3292 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003293
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003294 case CXCursor_TypeRef:
3295 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003296
3297 case CXCursor_TemplateRef:
3298 return getCursorTemplateRef(C).second;
3299
Douglas Gregor69319002010-08-31 23:48:11 +00003300 case CXCursor_NamespaceRef:
3301 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003302
3303 case CXCursor_MemberRef:
3304 return getCursorMemberRef(C).second;
3305
Ted Kremenek3064ef92010-08-27 21:34:58 +00003306 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003307 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003308
Douglas Gregor36897b02010-09-10 00:22:18 +00003309 case CXCursor_LabelRef:
3310 return getCursorLabelRef(C).second;
3311
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003312 case CXCursor_OverloadedDeclRef:
3313 return getCursorOverloadedDeclRef(C).second;
3314
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003315 default:
3316 // FIXME: Need a way to enumerate all non-reference cases.
3317 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003318 }
3319 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003320
3321 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003322 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003323
3324 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003325 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003326
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003327 if (C.kind == CXCursor_PreprocessingDirective)
3328 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003329
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003330 if (C.kind == CXCursor_MacroInstantiation)
3331 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003332
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003333 if (C.kind == CXCursor_MacroDefinition)
3334 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003335
3336 if (C.kind == CXCursor_InclusionDirective)
3337 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3338
Ted Kremenek007a7c92010-11-01 23:26:51 +00003339 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3340 Decl *D = cxcursor::getCursorDecl(C);
3341 SourceRange R = D->getSourceRange();
3342 // FIXME: Multiple variables declared in a single declaration
3343 // currently lack the information needed to correctly determine their
3344 // ranges when accounting for the type-specifier. We use context
3345 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3346 // and if so, whether it is the first decl.
3347 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3348 if (!cxcursor::isFirstInDeclGroup(C))
3349 R.setBegin(VD->getLocation());
3350 }
3351 return R;
3352 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003353 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003354
3355extern "C" {
3356
3357CXSourceRange clang_getCursorExtent(CXCursor C) {
3358 SourceRange R = getRawCursorExtent(C);
3359 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003360 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003361
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003362 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003363}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003364
3365CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003366 if (clang_isInvalid(C.kind))
3367 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003368
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003369 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003370 if (clang_isDeclaration(C.kind)) {
3371 Decl *D = getCursorDecl(C);
3372 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3373 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3374 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3375 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3376 if (ObjCForwardProtocolDecl *Protocols
3377 = dyn_cast<ObjCForwardProtocolDecl>(D))
3378 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3379
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003380 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003381 }
3382
Douglas Gregor97b98722010-01-19 23:20:36 +00003383 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003384 Expr *E = getCursorExpr(C);
3385 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003386 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003387 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003388
3389 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3390 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3391
Douglas Gregor97b98722010-01-19 23:20:36 +00003392 return clang_getNullCursor();
3393 }
3394
Douglas Gregor36897b02010-09-10 00:22:18 +00003395 if (clang_isStatement(C.kind)) {
3396 Stmt *S = getCursorStmt(C);
3397 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3398 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3399 getCursorASTUnit(C));
3400
3401 return clang_getNullCursor();
3402 }
3403
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003404 if (C.kind == CXCursor_MacroInstantiation) {
3405 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3406 return MakeMacroDefinitionCursor(Def, CXXUnit);
3407 }
3408
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003409 if (!clang_isReference(C.kind))
3410 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003411
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003412 switch (C.kind) {
3413 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003414 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003415
3416 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003417 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003418
3419 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003420 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003421
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003422 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003423 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003424
3425 case CXCursor_TemplateRef:
3426 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3427
Douglas Gregor69319002010-08-31 23:48:11 +00003428 case CXCursor_NamespaceRef:
3429 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3430
Douglas Gregora67e03f2010-09-09 21:42:20 +00003431 case CXCursor_MemberRef:
3432 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3433
Ted Kremenek3064ef92010-08-27 21:34:58 +00003434 case CXCursor_CXXBaseSpecifier: {
3435 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3436 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3437 CXXUnit));
3438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003439
Douglas Gregor36897b02010-09-10 00:22:18 +00003440 case CXCursor_LabelRef:
3441 // FIXME: We end up faking the "parent" declaration here because we
3442 // don't want to make CXCursor larger.
3443 return MakeCXCursor(getCursorLabelRef(C).first,
3444 CXXUnit->getASTContext().getTranslationUnitDecl(),
3445 CXXUnit);
3446
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003447 case CXCursor_OverloadedDeclRef:
3448 return C;
3449
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003450 default:
3451 // We would prefer to enumerate all non-reference cursor kinds here.
3452 llvm_unreachable("Unhandled reference cursor kind");
3453 break;
3454 }
3455 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003457 return clang_getNullCursor();
3458}
3459
Douglas Gregorb6998662010-01-19 19:34:47 +00003460CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003461 if (clang_isInvalid(C.kind))
3462 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003463
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003464 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003465
Douglas Gregorb6998662010-01-19 19:34:47 +00003466 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003467 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003468 C = clang_getCursorReferenced(C);
3469 WasReference = true;
3470 }
3471
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003472 if (C.kind == CXCursor_MacroInstantiation)
3473 return clang_getCursorReferenced(C);
3474
Douglas Gregorb6998662010-01-19 19:34:47 +00003475 if (!clang_isDeclaration(C.kind))
3476 return clang_getNullCursor();
3477
3478 Decl *D = getCursorDecl(C);
3479 if (!D)
3480 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003481
Douglas Gregorb6998662010-01-19 19:34:47 +00003482 switch (D->getKind()) {
3483 // Declaration kinds that don't really separate the notions of
3484 // declaration and definition.
3485 case Decl::Namespace:
3486 case Decl::Typedef:
3487 case Decl::TemplateTypeParm:
3488 case Decl::EnumConstant:
3489 case Decl::Field:
3490 case Decl::ObjCIvar:
3491 case Decl::ObjCAtDefsField:
3492 case Decl::ImplicitParam:
3493 case Decl::ParmVar:
3494 case Decl::NonTypeTemplateParm:
3495 case Decl::TemplateTemplateParm:
3496 case Decl::ObjCCategoryImpl:
3497 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003498 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003499 case Decl::LinkageSpec:
3500 case Decl::ObjCPropertyImpl:
3501 case Decl::FileScopeAsm:
3502 case Decl::StaticAssert:
3503 case Decl::Block:
3504 return C;
3505
3506 // Declaration kinds that don't make any sense here, but are
3507 // nonetheless harmless.
3508 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003509 break;
3510
3511 // Declaration kinds for which the definition is not resolvable.
3512 case Decl::UnresolvedUsingTypename:
3513 case Decl::UnresolvedUsingValue:
3514 break;
3515
3516 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003517 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3518 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003519
3520 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003521 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003522
3523 case Decl::Enum:
3524 case Decl::Record:
3525 case Decl::CXXRecord:
3526 case Decl::ClassTemplateSpecialization:
3527 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003528 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003529 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003530 return clang_getNullCursor();
3531
3532 case Decl::Function:
3533 case Decl::CXXMethod:
3534 case Decl::CXXConstructor:
3535 case Decl::CXXDestructor:
3536 case Decl::CXXConversion: {
3537 const FunctionDecl *Def = 0;
3538 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003539 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003540 return clang_getNullCursor();
3541 }
3542
3543 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003544 // Ask the variable if it has a definition.
3545 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3546 return MakeCXCursor(Def, CXXUnit);
3547 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003548 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003549
Douglas Gregorb6998662010-01-19 19:34:47 +00003550 case Decl::FunctionTemplate: {
3551 const FunctionDecl *Def = 0;
3552 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003553 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003554 return clang_getNullCursor();
3555 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003556
Douglas Gregorb6998662010-01-19 19:34:47 +00003557 case Decl::ClassTemplate: {
3558 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003559 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003560 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003561 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003562 return clang_getNullCursor();
3563 }
3564
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003565 case Decl::Using:
3566 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3567 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003568
3569 case Decl::UsingShadow:
3570 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003571 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003572 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003573
3574 case Decl::ObjCMethod: {
3575 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3576 if (Method->isThisDeclarationADefinition())
3577 return C;
3578
3579 // Dig out the method definition in the associated
3580 // @implementation, if we have it.
3581 // FIXME: The ASTs should make finding the definition easier.
3582 if (ObjCInterfaceDecl *Class
3583 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3584 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3585 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3586 Method->isInstanceMethod()))
3587 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003588 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003589
3590 return clang_getNullCursor();
3591 }
3592
3593 case Decl::ObjCCategory:
3594 if (ObjCCategoryImplDecl *Impl
3595 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003596 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003597 return clang_getNullCursor();
3598
3599 case Decl::ObjCProtocol:
3600 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3601 return C;
3602 return clang_getNullCursor();
3603
3604 case Decl::ObjCInterface:
3605 // There are two notions of a "definition" for an Objective-C
3606 // class: the interface and its implementation. When we resolved a
3607 // reference to an Objective-C class, produce the @interface as
3608 // the definition; when we were provided with the interface,
3609 // produce the @implementation as the definition.
3610 if (WasReference) {
3611 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3612 return C;
3613 } else if (ObjCImplementationDecl *Impl
3614 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003615 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003616 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003617
Douglas Gregorb6998662010-01-19 19:34:47 +00003618 case Decl::ObjCProperty:
3619 // FIXME: We don't really know where to find the
3620 // ObjCPropertyImplDecls that implement this property.
3621 return clang_getNullCursor();
3622
3623 case Decl::ObjCCompatibleAlias:
3624 if (ObjCInterfaceDecl *Class
3625 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3626 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003627 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003628
Douglas Gregorb6998662010-01-19 19:34:47 +00003629 return clang_getNullCursor();
3630
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003631 case Decl::ObjCForwardProtocol:
3632 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3633 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003634
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003635 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003636 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003637 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003638
3639 case Decl::Friend:
3640 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003641 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003642 return clang_getNullCursor();
3643
3644 case Decl::FriendTemplate:
3645 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003646 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003647 return clang_getNullCursor();
3648 }
3649
3650 return clang_getNullCursor();
3651}
3652
3653unsigned clang_isCursorDefinition(CXCursor C) {
3654 if (!clang_isDeclaration(C.kind))
3655 return 0;
3656
3657 return clang_getCursorDefinition(C) == C;
3658}
3659
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003660unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003661 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003662 return 0;
3663
3664 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3665 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3666 return E->getNumDecls();
3667
3668 if (OverloadedTemplateStorage *S
3669 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3670 return S->size();
3671
3672 Decl *D = Storage.get<Decl*>();
3673 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003674 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003675 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3676 return Classes->size();
3677 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3678 return Protocols->protocol_size();
3679
3680 return 0;
3681}
3682
3683CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003684 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003685 return clang_getNullCursor();
3686
3687 if (index >= clang_getNumOverloadedDecls(cursor))
3688 return clang_getNullCursor();
3689
3690 ASTUnit *Unit = getCursorASTUnit(cursor);
3691 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3692 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3693 return MakeCXCursor(E->decls_begin()[index], Unit);
3694
3695 if (OverloadedTemplateStorage *S
3696 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3697 return MakeCXCursor(S->begin()[index], Unit);
3698
3699 Decl *D = Storage.get<Decl*>();
3700 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3701 // FIXME: This is, unfortunately, linear time.
3702 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3703 std::advance(Pos, index);
3704 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3705 }
3706
3707 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3708 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3709
3710 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3711 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3712
3713 return clang_getNullCursor();
3714}
3715
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003716void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003717 const char **startBuf,
3718 const char **endBuf,
3719 unsigned *startLine,
3720 unsigned *startColumn,
3721 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003722 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003723 assert(getCursorDecl(C) && "CXCursor has null decl");
3724 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003725 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3726 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003727
Steve Naroff4ade6d62009-09-23 17:52:52 +00003728 SourceManager &SM = FD->getASTContext().getSourceManager();
3729 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3730 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3731 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3732 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3733 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3734 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3735}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003736
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003737void clang_enableStackTraces(void) {
3738 llvm::sys::PrintStackTraceOnErrorSignal();
3739}
3740
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003741void clang_executeOnThread(void (*fn)(void*), void *user_data,
3742 unsigned stack_size) {
3743 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3744}
3745
Ted Kremenekfb480492010-01-13 21:46:36 +00003746} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003747
Ted Kremenekfb480492010-01-13 21:46:36 +00003748//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003749// Token-based Operations.
3750//===----------------------------------------------------------------------===//
3751
3752/* CXToken layout:
3753 * int_data[0]: a CXTokenKind
3754 * int_data[1]: starting token location
3755 * int_data[2]: token length
3756 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003757 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003758 * otherwise unused.
3759 */
3760extern "C" {
3761
3762CXTokenKind clang_getTokenKind(CXToken CXTok) {
3763 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3764}
3765
3766CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3767 switch (clang_getTokenKind(CXTok)) {
3768 case CXToken_Identifier:
3769 case CXToken_Keyword:
3770 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003771 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3772 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003773
3774 case CXToken_Literal: {
3775 // We have stashed the starting pointer in the ptr_data field. Use it.
3776 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003777 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003778 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003779
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003780 case CXToken_Punctuation:
3781 case CXToken_Comment:
3782 break;
3783 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003784
3785 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003786 // deconstructing the source location.
3787 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3788 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003789 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003790
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003791 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3792 std::pair<FileID, unsigned> LocInfo
3793 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003794 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003795 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003796 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3797 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003798 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003799
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003800 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003801}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003802
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003803CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3804 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3805 if (!CXXUnit)
3806 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003807
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003808 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3809 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3810}
3811
3812CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3813 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003814 if (!CXXUnit)
3815 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003816
3817 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003818 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3819}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003820
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003821void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3822 CXToken **Tokens, unsigned *NumTokens) {
3823 if (Tokens)
3824 *Tokens = 0;
3825 if (NumTokens)
3826 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003827
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003828 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3829 if (!CXXUnit || !Tokens || !NumTokens)
3830 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003831
Douglas Gregorbdf60622010-03-05 21:16:25 +00003832 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3833
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003834 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003835 if (R.isInvalid())
3836 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003837
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003838 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3839 std::pair<FileID, unsigned> BeginLocInfo
3840 = SourceMgr.getDecomposedLoc(R.getBegin());
3841 std::pair<FileID, unsigned> EndLocInfo
3842 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003844 // Cannot tokenize across files.
3845 if (BeginLocInfo.first != EndLocInfo.first)
3846 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
3848 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003849 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003850 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003851 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003852 if (Invalid)
3853 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003854
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3856 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003857 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003858 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003860 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003861 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003862 llvm::SmallVector<CXToken, 32> CXTokens;
3863 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003864 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003865 do {
3866 // Lex the next token
3867 Lex.LexFromRawLexer(Tok);
3868 if (Tok.is(tok::eof))
3869 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003870
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003871 // Initialize the CXToken.
3872 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003873
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 // - Common fields
3875 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3876 CXTok.int_data[2] = Tok.getLength();
3877 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003878
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003879 // - Kind-specific fields
3880 if (Tok.isLiteral()) {
3881 CXTok.int_data[0] = CXToken_Literal;
3882 CXTok.ptr_data = (void *)Tok.getLiteralData();
3883 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003884 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003885 std::pair<FileID, unsigned> LocInfo
3886 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003887 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003888 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003889 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3890 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003891 return;
3892
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003893 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 IdentifierInfo *II
3895 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003896
David Chisnall096428b2010-10-13 21:44:48 +00003897 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003898 CXTok.int_data[0] = CXToken_Keyword;
3899 }
3900 else {
3901 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3902 CXToken_Identifier
3903 : CXToken_Keyword;
3904 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003905 CXTok.ptr_data = II;
3906 } else if (Tok.is(tok::comment)) {
3907 CXTok.int_data[0] = CXToken_Comment;
3908 CXTok.ptr_data = 0;
3909 } else {
3910 CXTok.int_data[0] = CXToken_Punctuation;
3911 CXTok.ptr_data = 0;
3912 }
3913 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003914 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003915 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003916
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003917 if (CXTokens.empty())
3918 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003919
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003920 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3921 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3922 *NumTokens = CXTokens.size();
3923}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003924
Ted Kremenek6db61092010-05-05 00:55:15 +00003925void clang_disposeTokens(CXTranslationUnit TU,
3926 CXToken *Tokens, unsigned NumTokens) {
3927 free(Tokens);
3928}
3929
3930} // end: extern "C"
3931
3932//===----------------------------------------------------------------------===//
3933// Token annotation APIs.
3934//===----------------------------------------------------------------------===//
3935
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003936typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003937static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3938 CXCursor parent,
3939 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003940namespace {
3941class AnnotateTokensWorker {
3942 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003943 CXToken *Tokens;
3944 CXCursor *Cursors;
3945 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003946 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003947 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003948 CursorVisitor AnnotateVis;
3949 SourceManager &SrcMgr;
3950
3951 bool MoreTokens() const { return TokIdx < NumTokens; }
3952 unsigned NextToken() const { return TokIdx; }
3953 void AdvanceToken() { ++TokIdx; }
3954 SourceLocation GetTokenLoc(unsigned tokI) {
3955 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3956 }
3957
Ted Kremenek6db61092010-05-05 00:55:15 +00003958public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003959 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003960 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3961 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003962 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003963 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003964 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3965 Decl::MaxPCHLevel, RegionOfInterest),
3966 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003967
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003968 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003969 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003970 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003971 void AnnotateTokens() {
3972 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3973 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003974};
3975}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003976
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003977void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3978 // Walk the AST within the region of interest, annotating tokens
3979 // along the way.
3980 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003981
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003982 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3983 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003984 if (Pos != Annotated.end() &&
3985 (clang_isInvalid(Cursors[I].kind) ||
3986 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003987 Cursors[I] = Pos->second;
3988 }
3989
3990 // Finish up annotating any tokens left.
3991 if (!MoreTokens())
3992 return;
3993
3994 const CXCursor &C = clang_getNullCursor();
3995 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3996 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3997 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003998 }
3999}
4000
Ted Kremenek6db61092010-05-05 00:55:15 +00004001enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004002AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004003 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004004 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004005 if (cursorRange.isInvalid())
4006 return CXChildVisit_Recurse;
4007
Douglas Gregor4419b672010-10-21 06:10:04 +00004008 if (clang_isPreprocessing(cursor.kind)) {
4009 // For macro instantiations, just note where the beginning of the macro
4010 // instantiation occurs.
4011 if (cursor.kind == CXCursor_MacroInstantiation) {
4012 Annotated[Loc.int_data] = cursor;
4013 return CXChildVisit_Recurse;
4014 }
4015
Douglas Gregor4419b672010-10-21 06:10:04 +00004016 // Items in the preprocessing record are kept separate from items in
4017 // declarations, so we keep a separate token index.
4018 unsigned SavedTokIdx = TokIdx;
4019 TokIdx = PreprocessingTokIdx;
4020
4021 // Skip tokens up until we catch up to the beginning of the preprocessing
4022 // entry.
4023 while (MoreTokens()) {
4024 const unsigned I = NextToken();
4025 SourceLocation TokLoc = GetTokenLoc(I);
4026 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4027 case RangeBefore:
4028 AdvanceToken();
4029 continue;
4030 case RangeAfter:
4031 case RangeOverlap:
4032 break;
4033 }
4034 break;
4035 }
4036
4037 // Look at all of the tokens within this range.
4038 while (MoreTokens()) {
4039 const unsigned I = NextToken();
4040 SourceLocation TokLoc = GetTokenLoc(I);
4041 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4042 case RangeBefore:
4043 assert(0 && "Infeasible");
4044 case RangeAfter:
4045 break;
4046 case RangeOverlap:
4047 Cursors[I] = cursor;
4048 AdvanceToken();
4049 continue;
4050 }
4051 break;
4052 }
4053
4054 // Save the preprocessing token index; restore the non-preprocessing
4055 // token index.
4056 PreprocessingTokIdx = TokIdx;
4057 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004058 return CXChildVisit_Recurse;
4059 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004060
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004061 if (cursorRange.isInvalid())
4062 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004063
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004064 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4065
Ted Kremeneka333c662010-05-12 05:29:33 +00004066 // Adjust the annotated range based specific declarations.
4067 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4068 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004069 Decl *D = cxcursor::getCursorDecl(cursor);
4070 // Don't visit synthesized ObjC methods, since they have no syntatic
4071 // representation in the source.
4072 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4073 if (MD->isSynthesized())
4074 return CXChildVisit_Continue;
4075 }
4076 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004077 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4078 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004079 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004080 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004081 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004082 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004083 }
4084 }
4085 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004086
Ted Kremenek3f404602010-08-14 01:14:06 +00004087 // If the location of the cursor occurs within a macro instantiation, record
4088 // the spelling location of the cursor in our annotation map. We can then
4089 // paper over the token labelings during a post-processing step to try and
4090 // get cursor mappings for tokens that are the *arguments* of a macro
4091 // instantiation.
4092 if (L.isMacroID()) {
4093 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4094 // Only invalidate the old annotation if it isn't part of a preprocessing
4095 // directive. Here we assume that the default construction of CXCursor
4096 // results in CXCursor.kind being an initialized value (i.e., 0). If
4097 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004098
Ted Kremenek3f404602010-08-14 01:14:06 +00004099 CXCursor &oldC = Annotated[rawEncoding];
4100 if (!clang_isPreprocessing(oldC.kind))
4101 oldC = cursor;
4102 }
4103
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004104 const enum CXCursorKind K = clang_getCursorKind(parent);
4105 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004106 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4107 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004108
4109 while (MoreTokens()) {
4110 const unsigned I = NextToken();
4111 SourceLocation TokLoc = GetTokenLoc(I);
4112 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4113 case RangeBefore:
4114 Cursors[I] = updateC;
4115 AdvanceToken();
4116 continue;
4117 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004118 case RangeOverlap:
4119 break;
4120 }
4121 break;
4122 }
4123
4124 // Visit children to get their cursor information.
4125 const unsigned BeforeChildren = NextToken();
4126 VisitChildren(cursor);
4127 const unsigned AfterChildren = NextToken();
4128
4129 // Adjust 'Last' to the last token within the extent of the cursor.
4130 while (MoreTokens()) {
4131 const unsigned I = NextToken();
4132 SourceLocation TokLoc = GetTokenLoc(I);
4133 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4134 case RangeBefore:
4135 assert(0 && "Infeasible");
4136 case RangeAfter:
4137 break;
4138 case RangeOverlap:
4139 Cursors[I] = updateC;
4140 AdvanceToken();
4141 continue;
4142 }
4143 break;
4144 }
4145 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004146
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004147 // Scan the tokens that are at the beginning of the cursor, but are not
4148 // capture by the child cursors.
4149
4150 // For AST elements within macros, rely on a post-annotate pass to
4151 // to correctly annotate the tokens with cursors. Otherwise we can
4152 // get confusing results of having tokens that map to cursors that really
4153 // are expanded by an instantiation.
4154 if (L.isMacroID())
4155 cursor = clang_getNullCursor();
4156
4157 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4158 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4159 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004160
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004161 Cursors[I] = cursor;
4162 }
4163 // Scan the tokens that are at the end of the cursor, but are not captured
4164 // but the child cursors.
4165 for (unsigned I = AfterChildren; I != Last; ++I)
4166 Cursors[I] = cursor;
4167
4168 TokIdx = Last;
4169 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004170}
4171
Ted Kremenek6db61092010-05-05 00:55:15 +00004172static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4173 CXCursor parent,
4174 CXClientData client_data) {
4175 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4176}
4177
Ted Kremenekab979612010-11-11 08:05:23 +00004178// This gets run a separate thread to avoid stack blowout.
4179static void runAnnotateTokensWorker(void *UserData) {
4180 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4181}
4182
Ted Kremenek6db61092010-05-05 00:55:15 +00004183extern "C" {
4184
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004185void clang_annotateTokens(CXTranslationUnit TU,
4186 CXToken *Tokens, unsigned NumTokens,
4187 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004188
4189 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004190 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004191
Douglas Gregor4419b672010-10-21 06:10:04 +00004192 // Any token we don't specifically annotate will have a NULL cursor.
4193 CXCursor C = clang_getNullCursor();
4194 for (unsigned I = 0; I != NumTokens; ++I)
4195 Cursors[I] = C;
4196
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004197 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004198 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004199 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004200
Douglas Gregorbdf60622010-03-05 21:16:25 +00004201 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004202
Douglas Gregor0396f462010-03-19 05:22:59 +00004203 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004204 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004205 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4206 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004207 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4208 clang_getTokenLocation(TU,
4209 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004210
Douglas Gregor0396f462010-03-19 05:22:59 +00004211 // A mapping from the source locations found when re-lexing or traversing the
4212 // region of interest to the corresponding cursors.
4213 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004214
4215 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004216 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004217 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4218 std::pair<FileID, unsigned> BeginLocInfo
4219 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4220 std::pair<FileID, unsigned> EndLocInfo
4221 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004222
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004223 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004224 bool Invalid = false;
4225 if (BeginLocInfo.first == EndLocInfo.first &&
4226 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4227 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004228 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4229 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004230 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004231 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004232 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004233
4234 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004235 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004236 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004237 Token Tok;
4238 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004240 reprocess:
4241 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4242 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004243 // don't see it while preprocessing these tokens later, but keep track
4244 // of all of the token locations inside this preprocessing directive so
4245 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004246 //
4247 // FIXME: Some simple tests here could identify macro definitions and
4248 // #undefs, to provide specific cursor kinds for those.
4249 std::vector<SourceLocation> Locations;
4250 do {
4251 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004254
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004255 using namespace cxcursor;
4256 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004257 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4258 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004259 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004260 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4261 Annotated[Locations[I].getRawEncoding()] = Cursor;
4262 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004263
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004264 if (Tok.isAtStartOfLine())
4265 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004266
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004267 continue;
4268 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004269
Douglas Gregor48072312010-03-18 15:23:44 +00004270 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004271 break;
4272 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004273 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004274
Douglas Gregor0396f462010-03-19 05:22:59 +00004275 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004276 // a specific cursor.
4277 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4278 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004279
4280 // Run the worker within a CrashRecoveryContext.
4281 llvm::CrashRecoveryContext CRC;
4282 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4283 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4284 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004285}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004286} // end: extern "C"
4287
4288//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004289// Operations for querying linkage of a cursor.
4290//===----------------------------------------------------------------------===//
4291
4292extern "C" {
4293CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004294 if (!clang_isDeclaration(cursor.kind))
4295 return CXLinkage_Invalid;
4296
Ted Kremenek16b42592010-03-03 06:36:57 +00004297 Decl *D = cxcursor::getCursorDecl(cursor);
4298 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4299 switch (ND->getLinkage()) {
4300 case NoLinkage: return CXLinkage_NoLinkage;
4301 case InternalLinkage: return CXLinkage_Internal;
4302 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4303 case ExternalLinkage: return CXLinkage_External;
4304 };
4305
4306 return CXLinkage_Invalid;
4307}
4308} // end: extern "C"
4309
4310//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004311// Operations for querying language of a cursor.
4312//===----------------------------------------------------------------------===//
4313
4314static CXLanguageKind getDeclLanguage(const Decl *D) {
4315 switch (D->getKind()) {
4316 default:
4317 break;
4318 case Decl::ImplicitParam:
4319 case Decl::ObjCAtDefsField:
4320 case Decl::ObjCCategory:
4321 case Decl::ObjCCategoryImpl:
4322 case Decl::ObjCClass:
4323 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004324 case Decl::ObjCForwardProtocol:
4325 case Decl::ObjCImplementation:
4326 case Decl::ObjCInterface:
4327 case Decl::ObjCIvar:
4328 case Decl::ObjCMethod:
4329 case Decl::ObjCProperty:
4330 case Decl::ObjCPropertyImpl:
4331 case Decl::ObjCProtocol:
4332 return CXLanguage_ObjC;
4333 case Decl::CXXConstructor:
4334 case Decl::CXXConversion:
4335 case Decl::CXXDestructor:
4336 case Decl::CXXMethod:
4337 case Decl::CXXRecord:
4338 case Decl::ClassTemplate:
4339 case Decl::ClassTemplatePartialSpecialization:
4340 case Decl::ClassTemplateSpecialization:
4341 case Decl::Friend:
4342 case Decl::FriendTemplate:
4343 case Decl::FunctionTemplate:
4344 case Decl::LinkageSpec:
4345 case Decl::Namespace:
4346 case Decl::NamespaceAlias:
4347 case Decl::NonTypeTemplateParm:
4348 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004349 case Decl::TemplateTemplateParm:
4350 case Decl::TemplateTypeParm:
4351 case Decl::UnresolvedUsingTypename:
4352 case Decl::UnresolvedUsingValue:
4353 case Decl::Using:
4354 case Decl::UsingDirective:
4355 case Decl::UsingShadow:
4356 return CXLanguage_CPlusPlus;
4357 }
4358
4359 return CXLanguage_C;
4360}
4361
4362extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004363
4364enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4365 if (clang_isDeclaration(cursor.kind))
4366 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4367 if (D->hasAttr<UnavailableAttr>() ||
4368 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4369 return CXAvailability_Available;
4370
4371 if (D->hasAttr<DeprecatedAttr>())
4372 return CXAvailability_Deprecated;
4373 }
4374
4375 return CXAvailability_Available;
4376}
4377
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004378CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4379 if (clang_isDeclaration(cursor.kind))
4380 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4381
4382 return CXLanguage_Invalid;
4383}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004384
4385CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4386 if (clang_isDeclaration(cursor.kind)) {
4387 if (Decl *D = getCursorDecl(cursor)) {
4388 DeclContext *DC = D->getDeclContext();
4389 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4390 }
4391 }
4392
4393 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4394 if (Decl *D = getCursorDecl(cursor))
4395 return MakeCXCursor(D, getCursorASTUnit(cursor));
4396 }
4397
4398 return clang_getNullCursor();
4399}
4400
4401CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4402 if (clang_isDeclaration(cursor.kind)) {
4403 if (Decl *D = getCursorDecl(cursor)) {
4404 DeclContext *DC = D->getLexicalDeclContext();
4405 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4406 }
4407 }
4408
4409 // FIXME: Note that we can't easily compute the lexical context of a
4410 // statement or expression, so we return nothing.
4411 return clang_getNullCursor();
4412}
4413
Douglas Gregor9f592342010-10-01 20:25:15 +00004414static void CollectOverriddenMethods(DeclContext *Ctx,
4415 ObjCMethodDecl *Method,
4416 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4417 if (!Ctx)
4418 return;
4419
4420 // If we have a class or category implementation, jump straight to the
4421 // interface.
4422 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4423 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4424
4425 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4426 if (!Container)
4427 return;
4428
4429 // Check whether we have a matching method at this level.
4430 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4431 Method->isInstanceMethod()))
4432 if (Method != Overridden) {
4433 // We found an override at this level; there is no need to look
4434 // into other protocols or categories.
4435 Methods.push_back(Overridden);
4436 return;
4437 }
4438
4439 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4440 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4441 PEnd = Protocol->protocol_end();
4442 P != PEnd; ++P)
4443 CollectOverriddenMethods(*P, Method, Methods);
4444 }
4445
4446 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4447 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4448 PEnd = Category->protocol_end();
4449 P != PEnd; ++P)
4450 CollectOverriddenMethods(*P, Method, Methods);
4451 }
4452
4453 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4454 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4455 PEnd = Interface->protocol_end();
4456 P != PEnd; ++P)
4457 CollectOverriddenMethods(*P, Method, Methods);
4458
4459 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4460 Category; Category = Category->getNextClassCategory())
4461 CollectOverriddenMethods(Category, Method, Methods);
4462
4463 // We only look into the superclass if we haven't found anything yet.
4464 if (Methods.empty())
4465 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4466 return CollectOverriddenMethods(Super, Method, Methods);
4467 }
4468}
4469
4470void clang_getOverriddenCursors(CXCursor cursor,
4471 CXCursor **overridden,
4472 unsigned *num_overridden) {
4473 if (overridden)
4474 *overridden = 0;
4475 if (num_overridden)
4476 *num_overridden = 0;
4477 if (!overridden || !num_overridden)
4478 return;
4479
4480 if (!clang_isDeclaration(cursor.kind))
4481 return;
4482
4483 Decl *D = getCursorDecl(cursor);
4484 if (!D)
4485 return;
4486
4487 // Handle C++ member functions.
4488 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4489 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4490 *num_overridden = CXXMethod->size_overridden_methods();
4491 if (!*num_overridden)
4492 return;
4493
4494 *overridden = new CXCursor [*num_overridden];
4495 unsigned I = 0;
4496 for (CXXMethodDecl::method_iterator
4497 M = CXXMethod->begin_overridden_methods(),
4498 MEnd = CXXMethod->end_overridden_methods();
4499 M != MEnd; (void)++M, ++I)
4500 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4501 return;
4502 }
4503
4504 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4505 if (!Method)
4506 return;
4507
4508 // Handle Objective-C methods.
4509 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4510 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4511
4512 if (Methods.empty())
4513 return;
4514
4515 *num_overridden = Methods.size();
4516 *overridden = new CXCursor [Methods.size()];
4517 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4518 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4519}
4520
4521void clang_disposeOverriddenCursors(CXCursor *overridden) {
4522 delete [] overridden;
4523}
4524
Douglas Gregorecdcb882010-10-20 22:00:55 +00004525CXFile clang_getIncludedFile(CXCursor cursor) {
4526 if (cursor.kind != CXCursor_InclusionDirective)
4527 return 0;
4528
4529 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4530 return (void *)ID->getFile();
4531}
4532
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004533} // end: extern "C"
4534
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004535
4536//===----------------------------------------------------------------------===//
4537// C++ AST instrospection.
4538//===----------------------------------------------------------------------===//
4539
4540extern "C" {
4541unsigned clang_CXXMethod_isStatic(CXCursor C) {
4542 if (!clang_isDeclaration(C.kind))
4543 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004544
4545 CXXMethodDecl *Method = 0;
4546 Decl *D = cxcursor::getCursorDecl(C);
4547 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4548 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4549 else
4550 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4551 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004552}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004553
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004554} // end: extern "C"
4555
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004556//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004557// Attribute introspection.
4558//===----------------------------------------------------------------------===//
4559
4560extern "C" {
4561CXType clang_getIBOutletCollectionType(CXCursor C) {
4562 if (C.kind != CXCursor_IBOutletCollectionAttr)
4563 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4564
4565 IBOutletCollectionAttr *A =
4566 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4567
4568 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4569}
4570} // end: extern "C"
4571
4572//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004573// CXString Operations.
4574//===----------------------------------------------------------------------===//
4575
4576extern "C" {
4577const char *clang_getCString(CXString string) {
4578 return string.Spelling;
4579}
4580
4581void clang_disposeString(CXString string) {
4582 if (string.MustFreeString && string.Spelling)
4583 free((void*)string.Spelling);
4584}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004585
Ted Kremenekfb480492010-01-13 21:46:36 +00004586} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004587
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004588namespace clang { namespace cxstring {
4589CXString createCXString(const char *String, bool DupString){
4590 CXString Str;
4591 if (DupString) {
4592 Str.Spelling = strdup(String);
4593 Str.MustFreeString = 1;
4594 } else {
4595 Str.Spelling = String;
4596 Str.MustFreeString = 0;
4597 }
4598 return Str;
4599}
4600
4601CXString createCXString(llvm::StringRef String, bool DupString) {
4602 CXString Result;
4603 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4604 char *Spelling = (char *)malloc(String.size() + 1);
4605 memmove(Spelling, String.data(), String.size());
4606 Spelling[String.size()] = 0;
4607 Result.Spelling = Spelling;
4608 Result.MustFreeString = 1;
4609 } else {
4610 Result.Spelling = String.data();
4611 Result.MustFreeString = 0;
4612 }
4613 return Result;
4614}
4615}}
4616
Ted Kremenek04bb7162010-01-22 22:44:15 +00004617//===----------------------------------------------------------------------===//
4618// Misc. utility functions.
4619//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004620
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004621/// Default to using an 8 MB stack size on "safety" threads.
4622static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004623
4624namespace clang {
4625
4626bool RunSafely(llvm::CrashRecoveryContext &CRC,
4627 void (*Fn)(void*), void *UserData) {
4628 if (unsigned Size = GetSafetyThreadStackSize())
4629 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4630 return CRC.RunSafely(Fn, UserData);
4631}
4632
4633unsigned GetSafetyThreadStackSize() {
4634 return SafetyStackThreadSize;
4635}
4636
4637void SetSafetyThreadStackSize(unsigned Value) {
4638 SafetyStackThreadSize = Value;
4639}
4640
4641}
4642
Ted Kremenek04bb7162010-01-22 22:44:15 +00004643extern "C" {
4644
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004645CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004646 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004647}
4648
4649} // end: extern "C"