blob: da7f42dcd71f27989dfb920dabed5987994c82d2 [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) {
Ted Kremenekae3c2202010-11-12 18:27:01 +00001882 WLAddStmt(WL, C, *Child);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001883 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001884 if (size == WL.size())
1885 return;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001886 // Now reverse the entries we just added. This will match the DFS
1887 // ordering performed by the worklist.
1888 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1889 std::reverse(I, E);
1890 break;
Ted Kremenekf1107452010-11-12 18:26:56 +00001891 }
1892 case Stmt::CXXOperatorCallExprClass: {
1893 CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(S);
1894 // Note that we enqueue things in reverse order so that
1895 // they are visited correctly by the DFS.
Ted Kremenekf1107452010-11-12 18:26:56 +00001896 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
Ted Kremenekae3c2202010-11-12 18:27:01 +00001897 WLAddStmt(WL, C, CE->getArg(N-I));
Ted Kremenekf1107452010-11-12 18:26:56 +00001898
Ted Kremenekae3c2202010-11-12 18:27:01 +00001899 WLAddStmt(WL, C, CE->getCallee());
1900 WLAddStmt(WL, C, CE->getArg(0));
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001901 break;
1902 }
1903 case Stmt::BinaryOperatorClass: {
1904 BinaryOperator *B = cast<BinaryOperator>(S);
Ted Kremenekae3c2202010-11-12 18:27:01 +00001905 WLAddStmt(WL, C, B->getRHS());
1906 WLAddStmt(WL, C, B->getLHS());
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001907 break;
1908 }
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001909 case Stmt::IfStmtClass: {
1910 IfStmt *If = cast<IfStmt>(S);
1911 WLAddStmt(WL, C, If->getElse());
1912 WLAddStmt(WL, C, If->getThen());
1913 WLAddStmt(WL, C, If->getCond());
Ted Kremenekae3c2202010-11-12 18:27:01 +00001914 WLAddDecl(WL, C, If->getConditionVariable());
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001915 break;
1916 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001917 case Stmt::MemberExprClass: {
1918 MemberExpr *M = cast<MemberExpr>(S);
1919 WL.push_back(MemberExprParts(M, C));
Ted Kremenekae3c2202010-11-12 18:27:01 +00001920 WLAddStmt(WL, C, M->getBase());
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001921 break;
1922 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001923 case Stmt::ParenExprClass: {
Ted Kremenekae3c2202010-11-12 18:27:01 +00001924 WLAddStmt(WL, C, cast<ParenExpr>(S)->getSubExpr());
Ted Kremenekf1107452010-11-12 18:26:56 +00001925 break;
1926 }
1927 case Stmt::SwitchStmtClass: {
1928 SwitchStmt *SS = cast<SwitchStmt>(S);
Ted Kremenekae3c2202010-11-12 18:27:01 +00001929 WLAddStmt(WL, C, SS->getBody());
1930 WLAddStmt(WL, C, SS->getCond());
1931 WLAddDecl(WL, C, SS->getConditionVariable());
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001932 break;
1933 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001934 }
1935}
1936
1937bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1938 if (RegionOfInterest.isValid()) {
1939 SourceRange Range = getRawCursorExtent(C);
1940 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1941 return false;
1942 }
1943 return true;
1944}
1945
1946bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1947 while (!WL.empty()) {
1948 // Dequeue the worklist item.
1949 VisitorJob LI = WL.back(); WL.pop_back();
1950
1951 // Set the Parent field, then back to its old value once we're done.
1952 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1953
1954 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001955 case VisitorJob::DeclVisitKind: {
1956 Decl *D = cast<DeclVisit>(LI).get();
1957 if (!D)
1958 continue;
1959
1960 // For now, perform default visitation for Decls.
1961 if (Visit(MakeCXCursor(D, TU)))
1962 return true;
1963
1964 continue;
1965 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001966 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001967 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001968 if (!S)
1969 continue;
1970
Ted Kremenekf1107452010-11-12 18:26:56 +00001971 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001972 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1973
1974 switch (S->getStmtClass()) {
1975 default: {
1976 // Perform default visitation for other cases.
1977 if (Visit(Cursor))
1978 return true;
1979 continue;
1980 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001981 case Stmt::BinaryOperatorClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001982 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001983 case Stmt::CaseStmtClass:
1984 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001985 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001986 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001987 case Stmt::DefaultStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001988 case Stmt::IfStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001989 case Stmt::MemberExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001990 case Stmt::ParenExprClass:
1991 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00001992 case Stmt::UnaryOperatorClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001993 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001994 if (!IsInRegionOfInterest(Cursor))
1995 continue;
1996 switch (Visitor(Cursor, Parent, ClientData)) {
1997 case CXChildVisit_Break:
1998 return true;
1999 case CXChildVisit_Continue:
2000 break;
2001 case CXChildVisit_Recurse:
2002 EnqueueWorkList(WL, S);
2003 break;
2004 }
2005 }
2006 }
2007 continue;
2008 }
2009 case VisitorJob::MemberExprPartsKind: {
2010 // Handle the other pieces in the MemberExpr besides the base.
2011 MemberExpr *M = cast<MemberExprParts>(LI).get();
2012
2013 // Visit the nested-name-specifier
2014 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2015 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2016 return true;
2017
2018 // Visit the declaration name.
2019 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2020 return true;
2021
2022 // Visit the explicitly-specified template arguments, if any.
2023 if (M->hasExplicitTemplateArgs()) {
2024 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2025 *ArgEnd = Arg + M->getNumTemplateArgs();
2026 Arg != ArgEnd; ++Arg) {
2027 if (VisitTemplateArgumentLoc(*Arg))
2028 return true;
2029 }
2030 }
2031 continue;
2032 }
2033 }
2034 }
2035 return false;
2036}
2037
2038bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2039 VisitorWorkList WL;
2040 EnqueueWorkList(WL, S);
2041 return RunVisitorWorkList(WL);
2042}
2043
2044//===----------------------------------------------------------------------===//
2045// Misc. API hooks.
2046//===----------------------------------------------------------------------===//
2047
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002048static llvm::sys::Mutex EnableMultithreadingMutex;
2049static bool EnabledMultithreading;
2050
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002051extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002052CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2053 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002054 // Disable pretty stack trace functionality, which will otherwise be a very
2055 // poor citizen of the world and set up all sorts of signal handlers.
2056 llvm::DisablePrettyStackTrace = true;
2057
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002058 // We use crash recovery to make some of our APIs more reliable, implicitly
2059 // enable it.
2060 llvm::CrashRecoveryContext::Enable();
2061
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002062 // Enable support for multithreading in LLVM.
2063 {
2064 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2065 if (!EnabledMultithreading) {
2066 llvm::llvm_start_multithreaded();
2067 EnabledMultithreading = true;
2068 }
2069 }
2070
Douglas Gregora030b7c2010-01-22 20:35:53 +00002071 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002072 if (excludeDeclarationsFromPCH)
2073 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002074 if (displayDiagnostics)
2075 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002076 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002077}
2078
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002079void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002080 if (CIdx)
2081 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002082}
2083
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002084CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002085 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002086 if (!CIdx)
2087 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002088
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002089 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002090 FileSystemOptions FileSystemOpts;
2091 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002092
Douglas Gregor28019772010-04-05 23:52:57 +00002093 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002094 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002095 CXXIdx->getOnlyLocalDecls(),
2096 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002097}
2098
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002099unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002100 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002101 CXTranslationUnit_CacheCompletionResults |
2102 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002103}
2104
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002105CXTranslationUnit
2106clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2107 const char *source_filename,
2108 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002109 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002110 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002111 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002112 return clang_parseTranslationUnit(CIdx, source_filename,
2113 command_line_args, num_command_line_args,
2114 unsaved_files, num_unsaved_files,
2115 CXTranslationUnit_DetailedPreprocessingRecord);
2116}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002117
2118struct ParseTranslationUnitInfo {
2119 CXIndex CIdx;
2120 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002121 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002122 int num_command_line_args;
2123 struct CXUnsavedFile *unsaved_files;
2124 unsigned num_unsaved_files;
2125 unsigned options;
2126 CXTranslationUnit result;
2127};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002128static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002129 ParseTranslationUnitInfo *PTUI =
2130 static_cast<ParseTranslationUnitInfo*>(UserData);
2131 CXIndex CIdx = PTUI->CIdx;
2132 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002133 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002134 int num_command_line_args = PTUI->num_command_line_args;
2135 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2136 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2137 unsigned options = PTUI->options;
2138 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002139
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002140 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002141 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002142
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002143 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2144
Douglas Gregor44c181a2010-07-23 00:33:23 +00002145 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002146 bool CompleteTranslationUnit
2147 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002148 bool CacheCodeCompetionResults
2149 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002150 bool CXXPrecompilePreamble
2151 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2152 bool CXXChainedPCH
2153 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002154
Douglas Gregor5352ac02010-01-28 00:27:43 +00002155 // Configure the diagnostics.
2156 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002157 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2158 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002159
Douglas Gregor4db64a42010-01-23 00:14:00 +00002160 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2161 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002162 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002163 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002164 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002165 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2166 Buffer));
2167 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002168
Douglas Gregorb10daed2010-10-11 16:52:23 +00002169 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002170
Ted Kremenek139ba862009-10-22 00:03:57 +00002171 // The 'source_filename' argument is optional. If the caller does not
2172 // specify it then it is assumed that the source file is specified
2173 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002174 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002175 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002176
2177 // Since the Clang C library is primarily used by batch tools dealing with
2178 // (often very broken) source code, where spell-checking can have a
2179 // significant negative impact on performance (particularly when
2180 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002181 // Only do this if we haven't found a spell-checking-related argument.
2182 bool FoundSpellCheckingArgument = false;
2183 for (int I = 0; I != num_command_line_args; ++I) {
2184 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2185 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2186 FoundSpellCheckingArgument = true;
2187 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002188 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002189 }
2190 if (!FoundSpellCheckingArgument)
2191 Args.push_back("-fno-spell-checking");
2192
2193 Args.insert(Args.end(), command_line_args,
2194 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002195
Douglas Gregor44c181a2010-07-23 00:33:23 +00002196 // Do we need the detailed preprocessing record?
2197 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002198 Args.push_back("-Xclang");
2199 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002200 }
2201
Douglas Gregorb10daed2010-10-11 16:52:23 +00002202 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002203 llvm::OwningPtr<ASTUnit> Unit(
2204 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2205 Diags,
2206 CXXIdx->getClangResourcesPath(),
2207 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002208 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002209 RemappedFiles.data(),
2210 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002211 PrecompilePreamble,
2212 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002213 CacheCodeCompetionResults,
2214 CXXPrecompilePreamble,
2215 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002216
Douglas Gregorb10daed2010-10-11 16:52:23 +00002217 if (NumErrors != Diags->getNumErrors()) {
2218 // Make sure to check that 'Unit' is non-NULL.
2219 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2220 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2221 DEnd = Unit->stored_diag_end();
2222 D != DEnd; ++D) {
2223 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2224 CXString Msg = clang_formatDiagnostic(&Diag,
2225 clang_defaultDiagnosticDisplayOptions());
2226 fprintf(stderr, "%s\n", clang_getCString(Msg));
2227 clang_disposeString(Msg);
2228 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002229#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002230 // On Windows, force a flush, since there may be multiple copies of
2231 // stderr and stdout in the file system, all with different buffers
2232 // but writing to the same device.
2233 fflush(stderr);
2234#endif
2235 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002236 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002237
Douglas Gregorb10daed2010-10-11 16:52:23 +00002238 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002239}
2240CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2241 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002242 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002243 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002244 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002245 unsigned num_unsaved_files,
2246 unsigned options) {
2247 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002248 num_command_line_args, unsaved_files,
2249 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002250 llvm::CrashRecoveryContext CRC;
2251
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002252 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002253 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2254 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2255 fprintf(stderr, " 'command_line_args' : [");
2256 for (int i = 0; i != num_command_line_args; ++i) {
2257 if (i)
2258 fprintf(stderr, ", ");
2259 fprintf(stderr, "'%s'", command_line_args[i]);
2260 }
2261 fprintf(stderr, "],\n");
2262 fprintf(stderr, " 'unsaved_files' : [");
2263 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2264 if (i)
2265 fprintf(stderr, ", ");
2266 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2267 unsaved_files[i].Length);
2268 }
2269 fprintf(stderr, "],\n");
2270 fprintf(stderr, " 'options' : %d,\n", options);
2271 fprintf(stderr, "}\n");
2272
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002273 return 0;
2274 }
2275
2276 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002277}
2278
Douglas Gregor19998442010-08-13 15:35:05 +00002279unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2280 return CXSaveTranslationUnit_None;
2281}
2282
2283int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2284 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002285 if (!TU)
2286 return 1;
2287
2288 return static_cast<ASTUnit *>(TU)->Save(FileName);
2289}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002290
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002291void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002292 if (CTUnit) {
2293 // If the translation unit has been marked as unsafe to free, just discard
2294 // it.
2295 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2296 return;
2297
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002298 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002299 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002300}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002301
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002302unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2303 return CXReparse_None;
2304}
2305
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002306struct ReparseTranslationUnitInfo {
2307 CXTranslationUnit TU;
2308 unsigned num_unsaved_files;
2309 struct CXUnsavedFile *unsaved_files;
2310 unsigned options;
2311 int result;
2312};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002313
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002314static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002315 ReparseTranslationUnitInfo *RTUI =
2316 static_cast<ReparseTranslationUnitInfo*>(UserData);
2317 CXTranslationUnit TU = RTUI->TU;
2318 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2319 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2320 unsigned options = RTUI->options;
2321 (void) options;
2322 RTUI->result = 1;
2323
Douglas Gregorabc563f2010-07-19 21:46:24 +00002324 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002325 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002326
2327 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2328 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002329
2330 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2331 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2332 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2333 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002334 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002335 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2336 Buffer));
2337 }
2338
Douglas Gregor593b0c12010-09-23 18:47:53 +00002339 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2340 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002341}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002342
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002343int clang_reparseTranslationUnit(CXTranslationUnit TU,
2344 unsigned num_unsaved_files,
2345 struct CXUnsavedFile *unsaved_files,
2346 unsigned options) {
2347 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2348 options, 0 };
2349 llvm::CrashRecoveryContext CRC;
2350
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002351 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002352 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002353 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2354 return 1;
2355 }
2356
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002357
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002358 return RTUI.result;
2359}
2360
Douglas Gregordf95a132010-08-09 20:45:32 +00002361
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002362CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002363 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002364 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002365
Steve Naroff77accc12009-09-03 18:19:54 +00002366 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002367 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002368}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002369
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002370CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002371 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002372 return Result;
2373}
2374
Ted Kremenekfb480492010-01-13 21:46:36 +00002375} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002376
Ted Kremenekfb480492010-01-13 21:46:36 +00002377//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002378// CXSourceLocation and CXSourceRange Operations.
2379//===----------------------------------------------------------------------===//
2380
Douglas Gregorb9790342010-01-22 21:44:22 +00002381extern "C" {
2382CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002383 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002384 return Result;
2385}
2386
2387unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002388 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2389 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2390 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002391}
2392
2393CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2394 CXFile file,
2395 unsigned line,
2396 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002397 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002398 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002399
Douglas Gregorb9790342010-01-22 21:44:22 +00002400 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2401 SourceLocation SLoc
2402 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002403 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002404 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002405 if (SLoc.isInvalid()) return clang_getNullLocation();
2406
2407 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2408}
2409
2410CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2411 CXFile file,
2412 unsigned offset) {
2413 if (!tu || !file)
2414 return clang_getNullLocation();
2415
2416 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2417 SourceLocation Start
2418 = CXXUnit->getSourceManager().getLocation(
2419 static_cast<const FileEntry *>(file),
2420 1, 1);
2421 if (Start.isInvalid()) return clang_getNullLocation();
2422
2423 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2424
2425 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002426
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002427 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002428}
2429
Douglas Gregor5352ac02010-01-28 00:27:43 +00002430CXSourceRange clang_getNullRange() {
2431 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2432 return Result;
2433}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002434
Douglas Gregor5352ac02010-01-28 00:27:43 +00002435CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2436 if (begin.ptr_data[0] != end.ptr_data[0] ||
2437 begin.ptr_data[1] != end.ptr_data[1])
2438 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002439
2440 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002441 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002442 return Result;
2443}
2444
Douglas Gregor46766dc2010-01-26 19:19:08 +00002445void clang_getInstantiationLocation(CXSourceLocation location,
2446 CXFile *file,
2447 unsigned *line,
2448 unsigned *column,
2449 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002450 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2451
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002452 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002453 if (file)
2454 *file = 0;
2455 if (line)
2456 *line = 0;
2457 if (column)
2458 *column = 0;
2459 if (offset)
2460 *offset = 0;
2461 return;
2462 }
2463
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002464 const SourceManager &SM =
2465 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002466 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002467
2468 if (file)
2469 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2470 if (line)
2471 *line = SM.getInstantiationLineNumber(InstLoc);
2472 if (column)
2473 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002474 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002475 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002476}
2477
Douglas Gregora9b06d42010-11-09 06:24:54 +00002478void clang_getSpellingLocation(CXSourceLocation location,
2479 CXFile *file,
2480 unsigned *line,
2481 unsigned *column,
2482 unsigned *offset) {
2483 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2484
2485 if (!location.ptr_data[0] || Loc.isInvalid()) {
2486 if (file)
2487 *file = 0;
2488 if (line)
2489 *line = 0;
2490 if (column)
2491 *column = 0;
2492 if (offset)
2493 *offset = 0;
2494 return;
2495 }
2496
2497 const SourceManager &SM =
2498 *static_cast<const SourceManager*>(location.ptr_data[0]);
2499 SourceLocation SpellLoc = Loc;
2500 if (SpellLoc.isMacroID()) {
2501 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2502 if (SimpleSpellingLoc.isFileID() &&
2503 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2504 SpellLoc = SimpleSpellingLoc;
2505 else
2506 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2507 }
2508
2509 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2510 FileID FID = LocInfo.first;
2511 unsigned FileOffset = LocInfo.second;
2512
2513 if (file)
2514 *file = (void *)SM.getFileEntryForID(FID);
2515 if (line)
2516 *line = SM.getLineNumber(FID, FileOffset);
2517 if (column)
2518 *column = SM.getColumnNumber(FID, FileOffset);
2519 if (offset)
2520 *offset = FileOffset;
2521}
2522
Douglas Gregor1db19de2010-01-19 21:36:55 +00002523CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002524 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002525 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002526 return Result;
2527}
2528
2529CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002530 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002531 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002532 return Result;
2533}
2534
Douglas Gregorb9790342010-01-22 21:44:22 +00002535} // end: extern "C"
2536
Douglas Gregor1db19de2010-01-19 21:36:55 +00002537//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002538// CXFile Operations.
2539//===----------------------------------------------------------------------===//
2540
2541extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002542CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002543 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002544 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002545
Steve Naroff88145032009-10-27 14:35:18 +00002546 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002547 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002548}
2549
2550time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002551 if (!SFile)
2552 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002553
Steve Naroff88145032009-10-27 14:35:18 +00002554 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2555 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002556}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002557
Douglas Gregorb9790342010-01-22 21:44:22 +00002558CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2559 if (!tu)
2560 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002561
Douglas Gregorb9790342010-01-22 21:44:22 +00002562 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563
Douglas Gregorb9790342010-01-22 21:44:22 +00002564 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002565 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2566 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002567 return const_cast<FileEntry *>(File);
2568}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Ted Kremenekfb480492010-01-13 21:46:36 +00002570} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002571
Ted Kremenekfb480492010-01-13 21:46:36 +00002572//===----------------------------------------------------------------------===//
2573// CXCursor Operations.
2574//===----------------------------------------------------------------------===//
2575
Ted Kremenekfb480492010-01-13 21:46:36 +00002576static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002577 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2578 return getDeclFromExpr(CE->getSubExpr());
2579
Ted Kremenekfb480492010-01-13 21:46:36 +00002580 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2581 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002582 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2583 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002584 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2585 return ME->getMemberDecl();
2586 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2587 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002588 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2589 return PRE->getProperty();
2590
Ted Kremenekfb480492010-01-13 21:46:36 +00002591 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2592 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002593 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2594 if (!CE->isElidable())
2595 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002596 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2597 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Douglas Gregordb1314e2010-10-01 21:11:22 +00002599 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2600 return PE->getProtocol();
2601
Ted Kremenekfb480492010-01-13 21:46:36 +00002602 return 0;
2603}
2604
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002605static SourceLocation getLocationFromExpr(Expr *E) {
2606 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2607 return /*FIXME:*/Msg->getLeftLoc();
2608 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2609 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002610 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2611 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002612 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2613 return Member->getMemberLoc();
2614 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2615 return Ivar->getLocation();
2616 return E->getLocStart();
2617}
2618
Ted Kremenekfb480492010-01-13 21:46:36 +00002619extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002620
2621unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002622 CXCursorVisitor visitor,
2623 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002624 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002625
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002626 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2627 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002628 return CursorVis.VisitChildren(parent);
2629}
2630
David Chisnall3387c652010-11-03 14:12:26 +00002631#ifndef __has_feature
2632#define __has_feature(x) 0
2633#endif
2634#if __has_feature(blocks)
2635typedef enum CXChildVisitResult
2636 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2637
2638static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2639 CXClientData client_data) {
2640 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2641 return block(cursor, parent);
2642}
2643#else
2644// If we are compiled with a compiler that doesn't have native blocks support,
2645// define and call the block manually, so the
2646typedef struct _CXChildVisitResult
2647{
2648 void *isa;
2649 int flags;
2650 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002651 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2652 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002653} *CXCursorVisitorBlock;
2654
2655static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2656 CXClientData client_data) {
2657 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2658 return block->invoke(block, cursor, parent);
2659}
2660#endif
2661
2662
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002663unsigned clang_visitChildrenWithBlock(CXCursor parent,
2664 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002665 return clang_visitChildren(parent, visitWithBlock, block);
2666}
2667
Douglas Gregor78205d42010-01-20 21:45:58 +00002668static CXString getDeclSpelling(Decl *D) {
2669 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2670 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002671 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002672
Douglas Gregor78205d42010-01-20 21:45:58 +00002673 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002674 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002675
Douglas Gregor78205d42010-01-20 21:45:58 +00002676 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2677 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2678 // and returns different names. NamedDecl returns the class name and
2679 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002680 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002681
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002682 if (isa<UsingDirectiveDecl>(D))
2683 return createCXString("");
2684
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002685 llvm::SmallString<1024> S;
2686 llvm::raw_svector_ostream os(S);
2687 ND->printName(os);
2688
2689 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002690}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002691
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002692CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002693 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002694 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002695
Steve Narofff334b4e2009-09-02 18:26:48 +00002696 if (clang_isReference(C.kind)) {
2697 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002698 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002699 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002700 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002701 }
2702 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002703 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002704 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002705 }
2706 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002707 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002708 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002709 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002710 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002711 case CXCursor_CXXBaseSpecifier: {
2712 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2713 return createCXString(B->getType().getAsString());
2714 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002715 case CXCursor_TypeRef: {
2716 TypeDecl *Type = getCursorTypeRef(C).first;
2717 assert(Type && "Missing type decl");
2718
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002719 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2720 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002721 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002722 case CXCursor_TemplateRef: {
2723 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002724 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002725
2726 return createCXString(Template->getNameAsString());
2727 }
Douglas Gregor69319002010-08-31 23:48:11 +00002728
2729 case CXCursor_NamespaceRef: {
2730 NamedDecl *NS = getCursorNamespaceRef(C).first;
2731 assert(NS && "Missing namespace decl");
2732
2733 return createCXString(NS->getNameAsString());
2734 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002735
Douglas Gregora67e03f2010-09-09 21:42:20 +00002736 case CXCursor_MemberRef: {
2737 FieldDecl *Field = getCursorMemberRef(C).first;
2738 assert(Field && "Missing member decl");
2739
2740 return createCXString(Field->getNameAsString());
2741 }
2742
Douglas Gregor36897b02010-09-10 00:22:18 +00002743 case CXCursor_LabelRef: {
2744 LabelStmt *Label = getCursorLabelRef(C).first;
2745 assert(Label && "Missing label");
2746
2747 return createCXString(Label->getID()->getName());
2748 }
2749
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002750 case CXCursor_OverloadedDeclRef: {
2751 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2752 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2753 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2754 return createCXString(ND->getNameAsString());
2755 return createCXString("");
2756 }
2757 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2758 return createCXString(E->getName().getAsString());
2759 OverloadedTemplateStorage *Ovl
2760 = Storage.get<OverloadedTemplateStorage*>();
2761 if (Ovl->size() == 0)
2762 return createCXString("");
2763 return createCXString((*Ovl->begin())->getNameAsString());
2764 }
2765
Daniel Dunbaracca7252009-11-30 20:42:49 +00002766 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002767 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002768 }
2769 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002770
2771 if (clang_isExpression(C.kind)) {
2772 Decl *D = getDeclFromExpr(getCursorExpr(C));
2773 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002774 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002775 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002776 }
2777
Douglas Gregor36897b02010-09-10 00:22:18 +00002778 if (clang_isStatement(C.kind)) {
2779 Stmt *S = getCursorStmt(C);
2780 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2781 return createCXString(Label->getID()->getName());
2782
2783 return createCXString("");
2784 }
2785
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002786 if (C.kind == CXCursor_MacroInstantiation)
2787 return createCXString(getCursorMacroInstantiation(C)->getName()
2788 ->getNameStart());
2789
Douglas Gregor572feb22010-03-18 18:04:21 +00002790 if (C.kind == CXCursor_MacroDefinition)
2791 return createCXString(getCursorMacroDefinition(C)->getName()
2792 ->getNameStart());
2793
Douglas Gregorecdcb882010-10-20 22:00:55 +00002794 if (C.kind == CXCursor_InclusionDirective)
2795 return createCXString(getCursorInclusionDirective(C)->getFileName());
2796
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002797 if (clang_isDeclaration(C.kind))
2798 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002799
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002800 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002801}
2802
Douglas Gregor358559d2010-10-02 22:49:11 +00002803CXString clang_getCursorDisplayName(CXCursor C) {
2804 if (!clang_isDeclaration(C.kind))
2805 return clang_getCursorSpelling(C);
2806
2807 Decl *D = getCursorDecl(C);
2808 if (!D)
2809 return createCXString("");
2810
2811 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2812 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2813 D = FunTmpl->getTemplatedDecl();
2814
2815 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2816 llvm::SmallString<64> Str;
2817 llvm::raw_svector_ostream OS(Str);
2818 OS << Function->getNameAsString();
2819 if (Function->getPrimaryTemplate())
2820 OS << "<>";
2821 OS << "(";
2822 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2823 if (I)
2824 OS << ", ";
2825 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2826 }
2827
2828 if (Function->isVariadic()) {
2829 if (Function->getNumParams())
2830 OS << ", ";
2831 OS << "...";
2832 }
2833 OS << ")";
2834 return createCXString(OS.str());
2835 }
2836
2837 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2838 llvm::SmallString<64> Str;
2839 llvm::raw_svector_ostream OS(Str);
2840 OS << ClassTemplate->getNameAsString();
2841 OS << "<";
2842 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2843 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2844 if (I)
2845 OS << ", ";
2846
2847 NamedDecl *Param = Params->getParam(I);
2848 if (Param->getIdentifier()) {
2849 OS << Param->getIdentifier()->getName();
2850 continue;
2851 }
2852
2853 // There is no parameter name, which makes this tricky. Try to come up
2854 // with something useful that isn't too long.
2855 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2856 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2857 else if (NonTypeTemplateParmDecl *NTTP
2858 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2859 OS << NTTP->getType().getAsString(Policy);
2860 else
2861 OS << "template<...> class";
2862 }
2863
2864 OS << ">";
2865 return createCXString(OS.str());
2866 }
2867
2868 if (ClassTemplateSpecializationDecl *ClassSpec
2869 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2870 // If the type was explicitly written, use that.
2871 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2872 return createCXString(TSInfo->getType().getAsString(Policy));
2873
2874 llvm::SmallString<64> Str;
2875 llvm::raw_svector_ostream OS(Str);
2876 OS << ClassSpec->getNameAsString();
2877 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002878 ClassSpec->getTemplateArgs().data(),
2879 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002880 Policy);
2881 return createCXString(OS.str());
2882 }
2883
2884 return clang_getCursorSpelling(C);
2885}
2886
Ted Kremeneke68fff62010-02-17 00:41:32 +00002887CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002888 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002889 case CXCursor_FunctionDecl:
2890 return createCXString("FunctionDecl");
2891 case CXCursor_TypedefDecl:
2892 return createCXString("TypedefDecl");
2893 case CXCursor_EnumDecl:
2894 return createCXString("EnumDecl");
2895 case CXCursor_EnumConstantDecl:
2896 return createCXString("EnumConstantDecl");
2897 case CXCursor_StructDecl:
2898 return createCXString("StructDecl");
2899 case CXCursor_UnionDecl:
2900 return createCXString("UnionDecl");
2901 case CXCursor_ClassDecl:
2902 return createCXString("ClassDecl");
2903 case CXCursor_FieldDecl:
2904 return createCXString("FieldDecl");
2905 case CXCursor_VarDecl:
2906 return createCXString("VarDecl");
2907 case CXCursor_ParmDecl:
2908 return createCXString("ParmDecl");
2909 case CXCursor_ObjCInterfaceDecl:
2910 return createCXString("ObjCInterfaceDecl");
2911 case CXCursor_ObjCCategoryDecl:
2912 return createCXString("ObjCCategoryDecl");
2913 case CXCursor_ObjCProtocolDecl:
2914 return createCXString("ObjCProtocolDecl");
2915 case CXCursor_ObjCPropertyDecl:
2916 return createCXString("ObjCPropertyDecl");
2917 case CXCursor_ObjCIvarDecl:
2918 return createCXString("ObjCIvarDecl");
2919 case CXCursor_ObjCInstanceMethodDecl:
2920 return createCXString("ObjCInstanceMethodDecl");
2921 case CXCursor_ObjCClassMethodDecl:
2922 return createCXString("ObjCClassMethodDecl");
2923 case CXCursor_ObjCImplementationDecl:
2924 return createCXString("ObjCImplementationDecl");
2925 case CXCursor_ObjCCategoryImplDecl:
2926 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002927 case CXCursor_CXXMethod:
2928 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002929 case CXCursor_UnexposedDecl:
2930 return createCXString("UnexposedDecl");
2931 case CXCursor_ObjCSuperClassRef:
2932 return createCXString("ObjCSuperClassRef");
2933 case CXCursor_ObjCProtocolRef:
2934 return createCXString("ObjCProtocolRef");
2935 case CXCursor_ObjCClassRef:
2936 return createCXString("ObjCClassRef");
2937 case CXCursor_TypeRef:
2938 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002939 case CXCursor_TemplateRef:
2940 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002941 case CXCursor_NamespaceRef:
2942 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002943 case CXCursor_MemberRef:
2944 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002945 case CXCursor_LabelRef:
2946 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002947 case CXCursor_OverloadedDeclRef:
2948 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002949 case CXCursor_UnexposedExpr:
2950 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002951 case CXCursor_BlockExpr:
2952 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002953 case CXCursor_DeclRefExpr:
2954 return createCXString("DeclRefExpr");
2955 case CXCursor_MemberRefExpr:
2956 return createCXString("MemberRefExpr");
2957 case CXCursor_CallExpr:
2958 return createCXString("CallExpr");
2959 case CXCursor_ObjCMessageExpr:
2960 return createCXString("ObjCMessageExpr");
2961 case CXCursor_UnexposedStmt:
2962 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002963 case CXCursor_LabelStmt:
2964 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002965 case CXCursor_InvalidFile:
2966 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002967 case CXCursor_InvalidCode:
2968 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002969 case CXCursor_NoDeclFound:
2970 return createCXString("NoDeclFound");
2971 case CXCursor_NotImplemented:
2972 return createCXString("NotImplemented");
2973 case CXCursor_TranslationUnit:
2974 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002975 case CXCursor_UnexposedAttr:
2976 return createCXString("UnexposedAttr");
2977 case CXCursor_IBActionAttr:
2978 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002979 case CXCursor_IBOutletAttr:
2980 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002981 case CXCursor_IBOutletCollectionAttr:
2982 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002983 case CXCursor_PreprocessingDirective:
2984 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002985 case CXCursor_MacroDefinition:
2986 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002987 case CXCursor_MacroInstantiation:
2988 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002989 case CXCursor_InclusionDirective:
2990 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002991 case CXCursor_Namespace:
2992 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002993 case CXCursor_LinkageSpec:
2994 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002995 case CXCursor_CXXBaseSpecifier:
2996 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002997 case CXCursor_Constructor:
2998 return createCXString("CXXConstructor");
2999 case CXCursor_Destructor:
3000 return createCXString("CXXDestructor");
3001 case CXCursor_ConversionFunction:
3002 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003003 case CXCursor_TemplateTypeParameter:
3004 return createCXString("TemplateTypeParameter");
3005 case CXCursor_NonTypeTemplateParameter:
3006 return createCXString("NonTypeTemplateParameter");
3007 case CXCursor_TemplateTemplateParameter:
3008 return createCXString("TemplateTemplateParameter");
3009 case CXCursor_FunctionTemplate:
3010 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003011 case CXCursor_ClassTemplate:
3012 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003013 case CXCursor_ClassTemplatePartialSpecialization:
3014 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003015 case CXCursor_NamespaceAlias:
3016 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003017 case CXCursor_UsingDirective:
3018 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003019 case CXCursor_UsingDeclaration:
3020 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003021 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003022
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003023 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003024 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003025}
Steve Naroff89922f82009-08-31 00:59:03 +00003026
Ted Kremeneke68fff62010-02-17 00:41:32 +00003027enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3028 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003029 CXClientData client_data) {
3030 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003031
3032 // If our current best cursor is the construction of a temporary object,
3033 // don't replace that cursor with a type reference, because we want
3034 // clang_getCursor() to point at the constructor.
3035 if (clang_isExpression(BestCursor->kind) &&
3036 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3037 cursor.kind == CXCursor_TypeRef)
3038 return CXChildVisit_Recurse;
3039
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003040 *BestCursor = cursor;
3041 return CXChildVisit_Recurse;
3042}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003043
Douglas Gregorb9790342010-01-22 21:44:22 +00003044CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3045 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003046 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003047
Douglas Gregorb9790342010-01-22 21:44:22 +00003048 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003049 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3050
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003051 // Translate the given source location to make it point at the beginning of
3052 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003053 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003054
3055 // Guard against an invalid SourceLocation, or we may assert in one
3056 // of the following calls.
3057 if (SLoc.isInvalid())
3058 return clang_getNullCursor();
3059
Douglas Gregor40749ee2010-11-03 00:35:38 +00003060 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003061 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3062 CXXUnit->getASTContext().getLangOptions());
3063
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003064 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3065 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003066 // FIXME: Would be great to have a "hint" cursor, then walk from that
3067 // hint cursor upward until we find a cursor whose source range encloses
3068 // the region of interest, rather than starting from the translation unit.
3069 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003070 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003071 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003072 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003073 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003074
3075 if (Logging) {
3076 CXFile SearchFile;
3077 unsigned SearchLine, SearchColumn;
3078 CXFile ResultFile;
3079 unsigned ResultLine, ResultColumn;
3080 CXString SearchFileName, ResultFileName, KindSpelling;
3081 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3082
3083 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3084 0);
3085 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3086 &ResultColumn, 0);
3087 SearchFileName = clang_getFileName(SearchFile);
3088 ResultFileName = clang_getFileName(ResultFile);
3089 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3090 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3091 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3092 clang_getCString(KindSpelling),
3093 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3094 clang_disposeString(SearchFileName);
3095 clang_disposeString(ResultFileName);
3096 clang_disposeString(KindSpelling);
3097 }
3098
Ted Kremeneke68fff62010-02-17 00:41:32 +00003099 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003100}
3101
Ted Kremenek73885552009-11-17 19:28:59 +00003102CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003103 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003104}
3105
3106unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003107 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003108}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003109
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003110unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003111 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3112}
3113
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003114unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003115 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3116}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003117
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003118unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003119 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3120}
3121
Douglas Gregor97b98722010-01-19 23:20:36 +00003122unsigned clang_isExpression(enum CXCursorKind K) {
3123 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3124}
3125
3126unsigned clang_isStatement(enum CXCursorKind K) {
3127 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3128}
3129
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003130unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3131 return K == CXCursor_TranslationUnit;
3132}
3133
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003134unsigned clang_isPreprocessing(enum CXCursorKind K) {
3135 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3136}
3137
Ted Kremenekad6eff62010-03-08 21:17:29 +00003138unsigned clang_isUnexposed(enum CXCursorKind K) {
3139 switch (K) {
3140 case CXCursor_UnexposedDecl:
3141 case CXCursor_UnexposedExpr:
3142 case CXCursor_UnexposedStmt:
3143 case CXCursor_UnexposedAttr:
3144 return true;
3145 default:
3146 return false;
3147 }
3148}
3149
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003150CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003151 return C.kind;
3152}
3153
Douglas Gregor98258af2010-01-18 22:46:11 +00003154CXSourceLocation clang_getCursorLocation(CXCursor C) {
3155 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003156 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003157 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003158 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3159 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003160 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003161 }
3162
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003163 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003164 std::pair<ObjCProtocolDecl *, SourceLocation> P
3165 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003166 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003167 }
3168
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003169 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003170 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3171 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003172 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003173 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003174
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003175 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003176 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003177 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003178 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003179
3180 case CXCursor_TemplateRef: {
3181 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3182 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3183 }
3184
Douglas Gregor69319002010-08-31 23:48:11 +00003185 case CXCursor_NamespaceRef: {
3186 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3187 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3188 }
3189
Douglas Gregora67e03f2010-09-09 21:42:20 +00003190 case CXCursor_MemberRef: {
3191 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3192 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3193 }
3194
Ted Kremenek3064ef92010-08-27 21:34:58 +00003195 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003196 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3197 if (!BaseSpec)
3198 return clang_getNullLocation();
3199
3200 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3201 return cxloc::translateSourceLocation(getCursorContext(C),
3202 TSInfo->getTypeLoc().getBeginLoc());
3203
3204 return cxloc::translateSourceLocation(getCursorContext(C),
3205 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003206 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003207
Douglas Gregor36897b02010-09-10 00:22:18 +00003208 case CXCursor_LabelRef: {
3209 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3210 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3211 }
3212
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003213 case CXCursor_OverloadedDeclRef:
3214 return cxloc::translateSourceLocation(getCursorContext(C),
3215 getCursorOverloadedDeclRef(C).second);
3216
Douglas Gregorf46034a2010-01-18 23:41:10 +00003217 default:
3218 // FIXME: Need a way to enumerate all non-reference cases.
3219 llvm_unreachable("Missed a reference kind");
3220 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003221 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003222
3223 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003224 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003225 getLocationFromExpr(getCursorExpr(C)));
3226
Douglas Gregor36897b02010-09-10 00:22:18 +00003227 if (clang_isStatement(C.kind))
3228 return cxloc::translateSourceLocation(getCursorContext(C),
3229 getCursorStmt(C)->getLocStart());
3230
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003231 if (C.kind == CXCursor_PreprocessingDirective) {
3232 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3233 return cxloc::translateSourceLocation(getCursorContext(C), L);
3234 }
Douglas Gregor48072312010-03-18 15:23:44 +00003235
3236 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003237 SourceLocation L
3238 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003239 return cxloc::translateSourceLocation(getCursorContext(C), L);
3240 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003241
3242 if (C.kind == CXCursor_MacroDefinition) {
3243 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3244 return cxloc::translateSourceLocation(getCursorContext(C), L);
3245 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003246
3247 if (C.kind == CXCursor_InclusionDirective) {
3248 SourceLocation L
3249 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3250 return cxloc::translateSourceLocation(getCursorContext(C), L);
3251 }
3252
Ted Kremenek9a700d22010-05-12 06:16:13 +00003253 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003254 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003255
Douglas Gregorf46034a2010-01-18 23:41:10 +00003256 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003257 SourceLocation Loc = D->getLocation();
3258 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3259 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003260 // FIXME: Multiple variables declared in a single declaration
3261 // currently lack the information needed to correctly determine their
3262 // ranges when accounting for the type-specifier. We use context
3263 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3264 // and if so, whether it is the first decl.
3265 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3266 if (!cxcursor::isFirstInDeclGroup(C))
3267 Loc = VD->getLocation();
3268 }
3269
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003270 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003271}
Douglas Gregora7bde202010-01-19 00:34:46 +00003272
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003273} // end extern "C"
3274
3275static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003276 if (clang_isReference(C.kind)) {
3277 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003278 case CXCursor_ObjCSuperClassRef:
3279 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003280
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003281 case CXCursor_ObjCProtocolRef:
3282 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003283
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003284 case CXCursor_ObjCClassRef:
3285 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003286
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003287 case CXCursor_TypeRef:
3288 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003289
3290 case CXCursor_TemplateRef:
3291 return getCursorTemplateRef(C).second;
3292
Douglas Gregor69319002010-08-31 23:48:11 +00003293 case CXCursor_NamespaceRef:
3294 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003295
3296 case CXCursor_MemberRef:
3297 return getCursorMemberRef(C).second;
3298
Ted Kremenek3064ef92010-08-27 21:34:58 +00003299 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003300 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003301
Douglas Gregor36897b02010-09-10 00:22:18 +00003302 case CXCursor_LabelRef:
3303 return getCursorLabelRef(C).second;
3304
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003305 case CXCursor_OverloadedDeclRef:
3306 return getCursorOverloadedDeclRef(C).second;
3307
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003308 default:
3309 // FIXME: Need a way to enumerate all non-reference cases.
3310 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003311 }
3312 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003313
3314 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003315 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003316
3317 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003318 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003319
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003320 if (C.kind == CXCursor_PreprocessingDirective)
3321 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003322
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003323 if (C.kind == CXCursor_MacroInstantiation)
3324 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003325
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003326 if (C.kind == CXCursor_MacroDefinition)
3327 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003328
3329 if (C.kind == CXCursor_InclusionDirective)
3330 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3331
Ted Kremenek007a7c92010-11-01 23:26:51 +00003332 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3333 Decl *D = cxcursor::getCursorDecl(C);
3334 SourceRange R = D->getSourceRange();
3335 // FIXME: Multiple variables declared in a single declaration
3336 // currently lack the information needed to correctly determine their
3337 // ranges when accounting for the type-specifier. We use context
3338 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3339 // and if so, whether it is the first decl.
3340 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3341 if (!cxcursor::isFirstInDeclGroup(C))
3342 R.setBegin(VD->getLocation());
3343 }
3344 return R;
3345 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003346 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003347
3348extern "C" {
3349
3350CXSourceRange clang_getCursorExtent(CXCursor C) {
3351 SourceRange R = getRawCursorExtent(C);
3352 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003353 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003354
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003355 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003356}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003357
3358CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003359 if (clang_isInvalid(C.kind))
3360 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003361
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003362 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003363 if (clang_isDeclaration(C.kind)) {
3364 Decl *D = getCursorDecl(C);
3365 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3366 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3367 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3368 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3369 if (ObjCForwardProtocolDecl *Protocols
3370 = dyn_cast<ObjCForwardProtocolDecl>(D))
3371 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3372
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003373 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003374 }
3375
Douglas Gregor97b98722010-01-19 23:20:36 +00003376 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003377 Expr *E = getCursorExpr(C);
3378 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003379 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003380 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003381
3382 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3383 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3384
Douglas Gregor97b98722010-01-19 23:20:36 +00003385 return clang_getNullCursor();
3386 }
3387
Douglas Gregor36897b02010-09-10 00:22:18 +00003388 if (clang_isStatement(C.kind)) {
3389 Stmt *S = getCursorStmt(C);
3390 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3391 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3392 getCursorASTUnit(C));
3393
3394 return clang_getNullCursor();
3395 }
3396
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003397 if (C.kind == CXCursor_MacroInstantiation) {
3398 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3399 return MakeMacroDefinitionCursor(Def, CXXUnit);
3400 }
3401
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003402 if (!clang_isReference(C.kind))
3403 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003404
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003405 switch (C.kind) {
3406 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003407 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003408
3409 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003410 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003411
3412 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003413 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003414
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003415 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003416 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003417
3418 case CXCursor_TemplateRef:
3419 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3420
Douglas Gregor69319002010-08-31 23:48:11 +00003421 case CXCursor_NamespaceRef:
3422 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3423
Douglas Gregora67e03f2010-09-09 21:42:20 +00003424 case CXCursor_MemberRef:
3425 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3426
Ted Kremenek3064ef92010-08-27 21:34:58 +00003427 case CXCursor_CXXBaseSpecifier: {
3428 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3429 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3430 CXXUnit));
3431 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003432
Douglas Gregor36897b02010-09-10 00:22:18 +00003433 case CXCursor_LabelRef:
3434 // FIXME: We end up faking the "parent" declaration here because we
3435 // don't want to make CXCursor larger.
3436 return MakeCXCursor(getCursorLabelRef(C).first,
3437 CXXUnit->getASTContext().getTranslationUnitDecl(),
3438 CXXUnit);
3439
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003440 case CXCursor_OverloadedDeclRef:
3441 return C;
3442
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003443 default:
3444 // We would prefer to enumerate all non-reference cursor kinds here.
3445 llvm_unreachable("Unhandled reference cursor kind");
3446 break;
3447 }
3448 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003449
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003450 return clang_getNullCursor();
3451}
3452
Douglas Gregorb6998662010-01-19 19:34:47 +00003453CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003454 if (clang_isInvalid(C.kind))
3455 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003457 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003458
Douglas Gregorb6998662010-01-19 19:34:47 +00003459 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003460 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003461 C = clang_getCursorReferenced(C);
3462 WasReference = true;
3463 }
3464
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003465 if (C.kind == CXCursor_MacroInstantiation)
3466 return clang_getCursorReferenced(C);
3467
Douglas Gregorb6998662010-01-19 19:34:47 +00003468 if (!clang_isDeclaration(C.kind))
3469 return clang_getNullCursor();
3470
3471 Decl *D = getCursorDecl(C);
3472 if (!D)
3473 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003474
Douglas Gregorb6998662010-01-19 19:34:47 +00003475 switch (D->getKind()) {
3476 // Declaration kinds that don't really separate the notions of
3477 // declaration and definition.
3478 case Decl::Namespace:
3479 case Decl::Typedef:
3480 case Decl::TemplateTypeParm:
3481 case Decl::EnumConstant:
3482 case Decl::Field:
3483 case Decl::ObjCIvar:
3484 case Decl::ObjCAtDefsField:
3485 case Decl::ImplicitParam:
3486 case Decl::ParmVar:
3487 case Decl::NonTypeTemplateParm:
3488 case Decl::TemplateTemplateParm:
3489 case Decl::ObjCCategoryImpl:
3490 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003491 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003492 case Decl::LinkageSpec:
3493 case Decl::ObjCPropertyImpl:
3494 case Decl::FileScopeAsm:
3495 case Decl::StaticAssert:
3496 case Decl::Block:
3497 return C;
3498
3499 // Declaration kinds that don't make any sense here, but are
3500 // nonetheless harmless.
3501 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003502 break;
3503
3504 // Declaration kinds for which the definition is not resolvable.
3505 case Decl::UnresolvedUsingTypename:
3506 case Decl::UnresolvedUsingValue:
3507 break;
3508
3509 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003510 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3511 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003512
3513 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003514 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003515
3516 case Decl::Enum:
3517 case Decl::Record:
3518 case Decl::CXXRecord:
3519 case Decl::ClassTemplateSpecialization:
3520 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003521 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003522 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003523 return clang_getNullCursor();
3524
3525 case Decl::Function:
3526 case Decl::CXXMethod:
3527 case Decl::CXXConstructor:
3528 case Decl::CXXDestructor:
3529 case Decl::CXXConversion: {
3530 const FunctionDecl *Def = 0;
3531 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003532 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003533 return clang_getNullCursor();
3534 }
3535
3536 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003537 // Ask the variable if it has a definition.
3538 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3539 return MakeCXCursor(Def, CXXUnit);
3540 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003541 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003542
Douglas Gregorb6998662010-01-19 19:34:47 +00003543 case Decl::FunctionTemplate: {
3544 const FunctionDecl *Def = 0;
3545 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003546 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003547 return clang_getNullCursor();
3548 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003549
Douglas Gregorb6998662010-01-19 19:34:47 +00003550 case Decl::ClassTemplate: {
3551 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003552 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003553 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003554 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003555 return clang_getNullCursor();
3556 }
3557
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003558 case Decl::Using:
3559 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3560 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003561
3562 case Decl::UsingShadow:
3563 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003564 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003565 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003566
3567 case Decl::ObjCMethod: {
3568 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3569 if (Method->isThisDeclarationADefinition())
3570 return C;
3571
3572 // Dig out the method definition in the associated
3573 // @implementation, if we have it.
3574 // FIXME: The ASTs should make finding the definition easier.
3575 if (ObjCInterfaceDecl *Class
3576 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3577 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3578 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3579 Method->isInstanceMethod()))
3580 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003581 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003582
3583 return clang_getNullCursor();
3584 }
3585
3586 case Decl::ObjCCategory:
3587 if (ObjCCategoryImplDecl *Impl
3588 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003589 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003590 return clang_getNullCursor();
3591
3592 case Decl::ObjCProtocol:
3593 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3594 return C;
3595 return clang_getNullCursor();
3596
3597 case Decl::ObjCInterface:
3598 // There are two notions of a "definition" for an Objective-C
3599 // class: the interface and its implementation. When we resolved a
3600 // reference to an Objective-C class, produce the @interface as
3601 // the definition; when we were provided with the interface,
3602 // produce the @implementation as the definition.
3603 if (WasReference) {
3604 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3605 return C;
3606 } else if (ObjCImplementationDecl *Impl
3607 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003608 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003609 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003610
Douglas Gregorb6998662010-01-19 19:34:47 +00003611 case Decl::ObjCProperty:
3612 // FIXME: We don't really know where to find the
3613 // ObjCPropertyImplDecls that implement this property.
3614 return clang_getNullCursor();
3615
3616 case Decl::ObjCCompatibleAlias:
3617 if (ObjCInterfaceDecl *Class
3618 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3619 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003620 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003621
Douglas Gregorb6998662010-01-19 19:34:47 +00003622 return clang_getNullCursor();
3623
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003624 case Decl::ObjCForwardProtocol:
3625 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3626 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003627
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003628 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003629 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003630 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003631
3632 case Decl::Friend:
3633 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003634 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003635 return clang_getNullCursor();
3636
3637 case Decl::FriendTemplate:
3638 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003639 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003640 return clang_getNullCursor();
3641 }
3642
3643 return clang_getNullCursor();
3644}
3645
3646unsigned clang_isCursorDefinition(CXCursor C) {
3647 if (!clang_isDeclaration(C.kind))
3648 return 0;
3649
3650 return clang_getCursorDefinition(C) == C;
3651}
3652
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003653unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003654 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003655 return 0;
3656
3657 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3658 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3659 return E->getNumDecls();
3660
3661 if (OverloadedTemplateStorage *S
3662 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3663 return S->size();
3664
3665 Decl *D = Storage.get<Decl*>();
3666 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003667 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003668 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3669 return Classes->size();
3670 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3671 return Protocols->protocol_size();
3672
3673 return 0;
3674}
3675
3676CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003677 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003678 return clang_getNullCursor();
3679
3680 if (index >= clang_getNumOverloadedDecls(cursor))
3681 return clang_getNullCursor();
3682
3683 ASTUnit *Unit = getCursorASTUnit(cursor);
3684 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3685 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3686 return MakeCXCursor(E->decls_begin()[index], Unit);
3687
3688 if (OverloadedTemplateStorage *S
3689 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3690 return MakeCXCursor(S->begin()[index], Unit);
3691
3692 Decl *D = Storage.get<Decl*>();
3693 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3694 // FIXME: This is, unfortunately, linear time.
3695 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3696 std::advance(Pos, index);
3697 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3698 }
3699
3700 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3701 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3702
3703 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3704 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3705
3706 return clang_getNullCursor();
3707}
3708
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003709void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003710 const char **startBuf,
3711 const char **endBuf,
3712 unsigned *startLine,
3713 unsigned *startColumn,
3714 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003715 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003716 assert(getCursorDecl(C) && "CXCursor has null decl");
3717 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003718 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3719 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003720
Steve Naroff4ade6d62009-09-23 17:52:52 +00003721 SourceManager &SM = FD->getASTContext().getSourceManager();
3722 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3723 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3724 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3725 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3726 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3727 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3728}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003729
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003730void clang_enableStackTraces(void) {
3731 llvm::sys::PrintStackTraceOnErrorSignal();
3732}
3733
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003734void clang_executeOnThread(void (*fn)(void*), void *user_data,
3735 unsigned stack_size) {
3736 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3737}
3738
Ted Kremenekfb480492010-01-13 21:46:36 +00003739} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003740
Ted Kremenekfb480492010-01-13 21:46:36 +00003741//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003742// Token-based Operations.
3743//===----------------------------------------------------------------------===//
3744
3745/* CXToken layout:
3746 * int_data[0]: a CXTokenKind
3747 * int_data[1]: starting token location
3748 * int_data[2]: token length
3749 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003750 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003751 * otherwise unused.
3752 */
3753extern "C" {
3754
3755CXTokenKind clang_getTokenKind(CXToken CXTok) {
3756 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3757}
3758
3759CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3760 switch (clang_getTokenKind(CXTok)) {
3761 case CXToken_Identifier:
3762 case CXToken_Keyword:
3763 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003764 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3765 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003766
3767 case CXToken_Literal: {
3768 // We have stashed the starting pointer in the ptr_data field. Use it.
3769 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003770 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003771 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003772
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003773 case CXToken_Punctuation:
3774 case CXToken_Comment:
3775 break;
3776 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003777
3778 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003779 // deconstructing the source location.
3780 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3781 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003782 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003783
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003784 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3785 std::pair<FileID, unsigned> LocInfo
3786 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003787 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003788 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003789 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3790 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003791 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003792
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003793 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003794}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003795
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003796CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3797 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3798 if (!CXXUnit)
3799 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003800
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003801 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3802 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3803}
3804
3805CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3806 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003807 if (!CXXUnit)
3808 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003809
3810 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003811 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3812}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003813
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003814void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3815 CXToken **Tokens, unsigned *NumTokens) {
3816 if (Tokens)
3817 *Tokens = 0;
3818 if (NumTokens)
3819 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003820
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003821 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3822 if (!CXXUnit || !Tokens || !NumTokens)
3823 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003824
Douglas Gregorbdf60622010-03-05 21:16:25 +00003825 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3826
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003827 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003828 if (R.isInvalid())
3829 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003830
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003831 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3832 std::pair<FileID, unsigned> BeginLocInfo
3833 = SourceMgr.getDecomposedLoc(R.getBegin());
3834 std::pair<FileID, unsigned> EndLocInfo
3835 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837 // Cannot tokenize across files.
3838 if (BeginLocInfo.first != EndLocInfo.first)
3839 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003840
3841 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003842 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003843 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003844 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003845 if (Invalid)
3846 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003847
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003848 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3849 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003850 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003851 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003852
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003853 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003854 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855 llvm::SmallVector<CXToken, 32> CXTokens;
3856 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003857 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003858 do {
3859 // Lex the next token
3860 Lex.LexFromRawLexer(Tok);
3861 if (Tok.is(tok::eof))
3862 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 // Initialize the CXToken.
3865 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003866
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003867 // - Common fields
3868 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3869 CXTok.int_data[2] = Tok.getLength();
3870 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003871
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003872 // - Kind-specific fields
3873 if (Tok.isLiteral()) {
3874 CXTok.int_data[0] = CXToken_Literal;
3875 CXTok.ptr_data = (void *)Tok.getLiteralData();
3876 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003877 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 std::pair<FileID, unsigned> LocInfo
3879 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003880 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003881 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003882 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3883 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003884 return;
3885
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003886 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003887 IdentifierInfo *II
3888 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003889
David Chisnall096428b2010-10-13 21:44:48 +00003890 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003891 CXTok.int_data[0] = CXToken_Keyword;
3892 }
3893 else {
3894 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3895 CXToken_Identifier
3896 : CXToken_Keyword;
3897 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003898 CXTok.ptr_data = II;
3899 } else if (Tok.is(tok::comment)) {
3900 CXTok.int_data[0] = CXToken_Comment;
3901 CXTok.ptr_data = 0;
3902 } else {
3903 CXTok.int_data[0] = CXToken_Punctuation;
3904 CXTok.ptr_data = 0;
3905 }
3906 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003907 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003908 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003909
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003910 if (CXTokens.empty())
3911 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003912
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003913 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3914 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3915 *NumTokens = CXTokens.size();
3916}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003917
Ted Kremenek6db61092010-05-05 00:55:15 +00003918void clang_disposeTokens(CXTranslationUnit TU,
3919 CXToken *Tokens, unsigned NumTokens) {
3920 free(Tokens);
3921}
3922
3923} // end: extern "C"
3924
3925//===----------------------------------------------------------------------===//
3926// Token annotation APIs.
3927//===----------------------------------------------------------------------===//
3928
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003929typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003930static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3931 CXCursor parent,
3932 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003933namespace {
3934class AnnotateTokensWorker {
3935 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003936 CXToken *Tokens;
3937 CXCursor *Cursors;
3938 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003939 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003940 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003941 CursorVisitor AnnotateVis;
3942 SourceManager &SrcMgr;
3943
3944 bool MoreTokens() const { return TokIdx < NumTokens; }
3945 unsigned NextToken() const { return TokIdx; }
3946 void AdvanceToken() { ++TokIdx; }
3947 SourceLocation GetTokenLoc(unsigned tokI) {
3948 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3949 }
3950
Ted Kremenek6db61092010-05-05 00:55:15 +00003951public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003952 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003953 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3954 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003955 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003956 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003957 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3958 Decl::MaxPCHLevel, RegionOfInterest),
3959 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003960
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003961 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003962 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003963 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003964 void AnnotateTokens() {
3965 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3966 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003967};
3968}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003969
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003970void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3971 // Walk the AST within the region of interest, annotating tokens
3972 // along the way.
3973 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003974
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003975 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3976 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003977 if (Pos != Annotated.end() &&
3978 (clang_isInvalid(Cursors[I].kind) ||
3979 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003980 Cursors[I] = Pos->second;
3981 }
3982
3983 // Finish up annotating any tokens left.
3984 if (!MoreTokens())
3985 return;
3986
3987 const CXCursor &C = clang_getNullCursor();
3988 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3989 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3990 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003991 }
3992}
3993
Ted Kremenek6db61092010-05-05 00:55:15 +00003994enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003995AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003996 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003997 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003998 if (cursorRange.isInvalid())
3999 return CXChildVisit_Recurse;
4000
Douglas Gregor4419b672010-10-21 06:10:04 +00004001 if (clang_isPreprocessing(cursor.kind)) {
4002 // For macro instantiations, just note where the beginning of the macro
4003 // instantiation occurs.
4004 if (cursor.kind == CXCursor_MacroInstantiation) {
4005 Annotated[Loc.int_data] = cursor;
4006 return CXChildVisit_Recurse;
4007 }
4008
Douglas Gregor4419b672010-10-21 06:10:04 +00004009 // Items in the preprocessing record are kept separate from items in
4010 // declarations, so we keep a separate token index.
4011 unsigned SavedTokIdx = TokIdx;
4012 TokIdx = PreprocessingTokIdx;
4013
4014 // Skip tokens up until we catch up to the beginning of the preprocessing
4015 // entry.
4016 while (MoreTokens()) {
4017 const unsigned I = NextToken();
4018 SourceLocation TokLoc = GetTokenLoc(I);
4019 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4020 case RangeBefore:
4021 AdvanceToken();
4022 continue;
4023 case RangeAfter:
4024 case RangeOverlap:
4025 break;
4026 }
4027 break;
4028 }
4029
4030 // Look at all of the tokens within this range.
4031 while (MoreTokens()) {
4032 const unsigned I = NextToken();
4033 SourceLocation TokLoc = GetTokenLoc(I);
4034 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4035 case RangeBefore:
4036 assert(0 && "Infeasible");
4037 case RangeAfter:
4038 break;
4039 case RangeOverlap:
4040 Cursors[I] = cursor;
4041 AdvanceToken();
4042 continue;
4043 }
4044 break;
4045 }
4046
4047 // Save the preprocessing token index; restore the non-preprocessing
4048 // token index.
4049 PreprocessingTokIdx = TokIdx;
4050 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004051 return CXChildVisit_Recurse;
4052 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004053
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004054 if (cursorRange.isInvalid())
4055 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004056
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004057 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4058
Ted Kremeneka333c662010-05-12 05:29:33 +00004059 // Adjust the annotated range based specific declarations.
4060 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4061 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004062 Decl *D = cxcursor::getCursorDecl(cursor);
4063 // Don't visit synthesized ObjC methods, since they have no syntatic
4064 // representation in the source.
4065 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4066 if (MD->isSynthesized())
4067 return CXChildVisit_Continue;
4068 }
4069 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004070 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4071 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004072 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004073 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004074 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004075 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004076 }
4077 }
4078 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004079
Ted Kremenek3f404602010-08-14 01:14:06 +00004080 // If the location of the cursor occurs within a macro instantiation, record
4081 // the spelling location of the cursor in our annotation map. We can then
4082 // paper over the token labelings during a post-processing step to try and
4083 // get cursor mappings for tokens that are the *arguments* of a macro
4084 // instantiation.
4085 if (L.isMacroID()) {
4086 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4087 // Only invalidate the old annotation if it isn't part of a preprocessing
4088 // directive. Here we assume that the default construction of CXCursor
4089 // results in CXCursor.kind being an initialized value (i.e., 0). If
4090 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004091
Ted Kremenek3f404602010-08-14 01:14:06 +00004092 CXCursor &oldC = Annotated[rawEncoding];
4093 if (!clang_isPreprocessing(oldC.kind))
4094 oldC = cursor;
4095 }
4096
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004097 const enum CXCursorKind K = clang_getCursorKind(parent);
4098 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004099 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4100 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004101
4102 while (MoreTokens()) {
4103 const unsigned I = NextToken();
4104 SourceLocation TokLoc = GetTokenLoc(I);
4105 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4106 case RangeBefore:
4107 Cursors[I] = updateC;
4108 AdvanceToken();
4109 continue;
4110 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004111 case RangeOverlap:
4112 break;
4113 }
4114 break;
4115 }
4116
4117 // Visit children to get their cursor information.
4118 const unsigned BeforeChildren = NextToken();
4119 VisitChildren(cursor);
4120 const unsigned AfterChildren = NextToken();
4121
4122 // Adjust 'Last' to the last token within the extent of the cursor.
4123 while (MoreTokens()) {
4124 const unsigned I = NextToken();
4125 SourceLocation TokLoc = GetTokenLoc(I);
4126 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4127 case RangeBefore:
4128 assert(0 && "Infeasible");
4129 case RangeAfter:
4130 break;
4131 case RangeOverlap:
4132 Cursors[I] = updateC;
4133 AdvanceToken();
4134 continue;
4135 }
4136 break;
4137 }
4138 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004139
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004140 // Scan the tokens that are at the beginning of the cursor, but are not
4141 // capture by the child cursors.
4142
4143 // For AST elements within macros, rely on a post-annotate pass to
4144 // to correctly annotate the tokens with cursors. Otherwise we can
4145 // get confusing results of having tokens that map to cursors that really
4146 // are expanded by an instantiation.
4147 if (L.isMacroID())
4148 cursor = clang_getNullCursor();
4149
4150 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4151 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4152 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004153
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004154 Cursors[I] = cursor;
4155 }
4156 // Scan the tokens that are at the end of the cursor, but are not captured
4157 // but the child cursors.
4158 for (unsigned I = AfterChildren; I != Last; ++I)
4159 Cursors[I] = cursor;
4160
4161 TokIdx = Last;
4162 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004163}
4164
Ted Kremenek6db61092010-05-05 00:55:15 +00004165static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4166 CXCursor parent,
4167 CXClientData client_data) {
4168 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4169}
4170
Ted Kremenekab979612010-11-11 08:05:23 +00004171// This gets run a separate thread to avoid stack blowout.
4172static void runAnnotateTokensWorker(void *UserData) {
4173 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4174}
4175
Ted Kremenek6db61092010-05-05 00:55:15 +00004176extern "C" {
4177
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004178void clang_annotateTokens(CXTranslationUnit TU,
4179 CXToken *Tokens, unsigned NumTokens,
4180 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004181
4182 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004183 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004184
Douglas Gregor4419b672010-10-21 06:10:04 +00004185 // Any token we don't specifically annotate will have a NULL cursor.
4186 CXCursor C = clang_getNullCursor();
4187 for (unsigned I = 0; I != NumTokens; ++I)
4188 Cursors[I] = C;
4189
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004190 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004191 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004192 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004193
Douglas Gregorbdf60622010-03-05 21:16:25 +00004194 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004195
Douglas Gregor0396f462010-03-19 05:22:59 +00004196 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004197 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004198 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4199 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004200 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4201 clang_getTokenLocation(TU,
4202 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004203
Douglas Gregor0396f462010-03-19 05:22:59 +00004204 // A mapping from the source locations found when re-lexing or traversing the
4205 // region of interest to the corresponding cursors.
4206 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004207
4208 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004209 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004210 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4211 std::pair<FileID, unsigned> BeginLocInfo
4212 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4213 std::pair<FileID, unsigned> EndLocInfo
4214 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004215
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004216 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004217 bool Invalid = false;
4218 if (BeginLocInfo.first == EndLocInfo.first &&
4219 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4220 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004221 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4222 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004223 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004224 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004225 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004226
4227 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004228 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004229 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004230 Token Tok;
4231 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004233 reprocess:
4234 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4235 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004236 // don't see it while preprocessing these tokens later, but keep track
4237 // of all of the token locations inside this preprocessing directive so
4238 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004239 //
4240 // FIXME: Some simple tests here could identify macro definitions and
4241 // #undefs, to provide specific cursor kinds for those.
4242 std::vector<SourceLocation> Locations;
4243 do {
4244 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004245 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004246 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004247
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004248 using namespace cxcursor;
4249 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004250 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4251 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004252 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4254 Annotated[Locations[I].getRawEncoding()] = Cursor;
4255 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004256
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004257 if (Tok.isAtStartOfLine())
4258 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004259
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004260 continue;
4261 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004262
Douglas Gregor48072312010-03-18 15:23:44 +00004263 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004264 break;
4265 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004266 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004267
Douglas Gregor0396f462010-03-19 05:22:59 +00004268 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004269 // a specific cursor.
4270 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4271 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004272
4273 // Run the worker within a CrashRecoveryContext.
4274 llvm::CrashRecoveryContext CRC;
4275 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4276 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4277 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004278}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004279} // end: extern "C"
4280
4281//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004282// Operations for querying linkage of a cursor.
4283//===----------------------------------------------------------------------===//
4284
4285extern "C" {
4286CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004287 if (!clang_isDeclaration(cursor.kind))
4288 return CXLinkage_Invalid;
4289
Ted Kremenek16b42592010-03-03 06:36:57 +00004290 Decl *D = cxcursor::getCursorDecl(cursor);
4291 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4292 switch (ND->getLinkage()) {
4293 case NoLinkage: return CXLinkage_NoLinkage;
4294 case InternalLinkage: return CXLinkage_Internal;
4295 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4296 case ExternalLinkage: return CXLinkage_External;
4297 };
4298
4299 return CXLinkage_Invalid;
4300}
4301} // end: extern "C"
4302
4303//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004304// Operations for querying language of a cursor.
4305//===----------------------------------------------------------------------===//
4306
4307static CXLanguageKind getDeclLanguage(const Decl *D) {
4308 switch (D->getKind()) {
4309 default:
4310 break;
4311 case Decl::ImplicitParam:
4312 case Decl::ObjCAtDefsField:
4313 case Decl::ObjCCategory:
4314 case Decl::ObjCCategoryImpl:
4315 case Decl::ObjCClass:
4316 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004317 case Decl::ObjCForwardProtocol:
4318 case Decl::ObjCImplementation:
4319 case Decl::ObjCInterface:
4320 case Decl::ObjCIvar:
4321 case Decl::ObjCMethod:
4322 case Decl::ObjCProperty:
4323 case Decl::ObjCPropertyImpl:
4324 case Decl::ObjCProtocol:
4325 return CXLanguage_ObjC;
4326 case Decl::CXXConstructor:
4327 case Decl::CXXConversion:
4328 case Decl::CXXDestructor:
4329 case Decl::CXXMethod:
4330 case Decl::CXXRecord:
4331 case Decl::ClassTemplate:
4332 case Decl::ClassTemplatePartialSpecialization:
4333 case Decl::ClassTemplateSpecialization:
4334 case Decl::Friend:
4335 case Decl::FriendTemplate:
4336 case Decl::FunctionTemplate:
4337 case Decl::LinkageSpec:
4338 case Decl::Namespace:
4339 case Decl::NamespaceAlias:
4340 case Decl::NonTypeTemplateParm:
4341 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004342 case Decl::TemplateTemplateParm:
4343 case Decl::TemplateTypeParm:
4344 case Decl::UnresolvedUsingTypename:
4345 case Decl::UnresolvedUsingValue:
4346 case Decl::Using:
4347 case Decl::UsingDirective:
4348 case Decl::UsingShadow:
4349 return CXLanguage_CPlusPlus;
4350 }
4351
4352 return CXLanguage_C;
4353}
4354
4355extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004356
4357enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4358 if (clang_isDeclaration(cursor.kind))
4359 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4360 if (D->hasAttr<UnavailableAttr>() ||
4361 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4362 return CXAvailability_Available;
4363
4364 if (D->hasAttr<DeprecatedAttr>())
4365 return CXAvailability_Deprecated;
4366 }
4367
4368 return CXAvailability_Available;
4369}
4370
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004371CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4372 if (clang_isDeclaration(cursor.kind))
4373 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4374
4375 return CXLanguage_Invalid;
4376}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004377
4378CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4379 if (clang_isDeclaration(cursor.kind)) {
4380 if (Decl *D = getCursorDecl(cursor)) {
4381 DeclContext *DC = D->getDeclContext();
4382 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4383 }
4384 }
4385
4386 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4387 if (Decl *D = getCursorDecl(cursor))
4388 return MakeCXCursor(D, getCursorASTUnit(cursor));
4389 }
4390
4391 return clang_getNullCursor();
4392}
4393
4394CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4395 if (clang_isDeclaration(cursor.kind)) {
4396 if (Decl *D = getCursorDecl(cursor)) {
4397 DeclContext *DC = D->getLexicalDeclContext();
4398 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4399 }
4400 }
4401
4402 // FIXME: Note that we can't easily compute the lexical context of a
4403 // statement or expression, so we return nothing.
4404 return clang_getNullCursor();
4405}
4406
Douglas Gregor9f592342010-10-01 20:25:15 +00004407static void CollectOverriddenMethods(DeclContext *Ctx,
4408 ObjCMethodDecl *Method,
4409 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4410 if (!Ctx)
4411 return;
4412
4413 // If we have a class or category implementation, jump straight to the
4414 // interface.
4415 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4416 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4417
4418 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4419 if (!Container)
4420 return;
4421
4422 // Check whether we have a matching method at this level.
4423 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4424 Method->isInstanceMethod()))
4425 if (Method != Overridden) {
4426 // We found an override at this level; there is no need to look
4427 // into other protocols or categories.
4428 Methods.push_back(Overridden);
4429 return;
4430 }
4431
4432 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4433 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4434 PEnd = Protocol->protocol_end();
4435 P != PEnd; ++P)
4436 CollectOverriddenMethods(*P, Method, Methods);
4437 }
4438
4439 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4440 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4441 PEnd = Category->protocol_end();
4442 P != PEnd; ++P)
4443 CollectOverriddenMethods(*P, Method, Methods);
4444 }
4445
4446 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4447 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4448 PEnd = Interface->protocol_end();
4449 P != PEnd; ++P)
4450 CollectOverriddenMethods(*P, Method, Methods);
4451
4452 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4453 Category; Category = Category->getNextClassCategory())
4454 CollectOverriddenMethods(Category, Method, Methods);
4455
4456 // We only look into the superclass if we haven't found anything yet.
4457 if (Methods.empty())
4458 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4459 return CollectOverriddenMethods(Super, Method, Methods);
4460 }
4461}
4462
4463void clang_getOverriddenCursors(CXCursor cursor,
4464 CXCursor **overridden,
4465 unsigned *num_overridden) {
4466 if (overridden)
4467 *overridden = 0;
4468 if (num_overridden)
4469 *num_overridden = 0;
4470 if (!overridden || !num_overridden)
4471 return;
4472
4473 if (!clang_isDeclaration(cursor.kind))
4474 return;
4475
4476 Decl *D = getCursorDecl(cursor);
4477 if (!D)
4478 return;
4479
4480 // Handle C++ member functions.
4481 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4482 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4483 *num_overridden = CXXMethod->size_overridden_methods();
4484 if (!*num_overridden)
4485 return;
4486
4487 *overridden = new CXCursor [*num_overridden];
4488 unsigned I = 0;
4489 for (CXXMethodDecl::method_iterator
4490 M = CXXMethod->begin_overridden_methods(),
4491 MEnd = CXXMethod->end_overridden_methods();
4492 M != MEnd; (void)++M, ++I)
4493 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4494 return;
4495 }
4496
4497 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4498 if (!Method)
4499 return;
4500
4501 // Handle Objective-C methods.
4502 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4503 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4504
4505 if (Methods.empty())
4506 return;
4507
4508 *num_overridden = Methods.size();
4509 *overridden = new CXCursor [Methods.size()];
4510 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4511 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4512}
4513
4514void clang_disposeOverriddenCursors(CXCursor *overridden) {
4515 delete [] overridden;
4516}
4517
Douglas Gregorecdcb882010-10-20 22:00:55 +00004518CXFile clang_getIncludedFile(CXCursor cursor) {
4519 if (cursor.kind != CXCursor_InclusionDirective)
4520 return 0;
4521
4522 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4523 return (void *)ID->getFile();
4524}
4525
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004526} // end: extern "C"
4527
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004528
4529//===----------------------------------------------------------------------===//
4530// C++ AST instrospection.
4531//===----------------------------------------------------------------------===//
4532
4533extern "C" {
4534unsigned clang_CXXMethod_isStatic(CXCursor C) {
4535 if (!clang_isDeclaration(C.kind))
4536 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004537
4538 CXXMethodDecl *Method = 0;
4539 Decl *D = cxcursor::getCursorDecl(C);
4540 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4541 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4542 else
4543 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4544 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004545}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004546
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004547} // end: extern "C"
4548
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004549//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004550// Attribute introspection.
4551//===----------------------------------------------------------------------===//
4552
4553extern "C" {
4554CXType clang_getIBOutletCollectionType(CXCursor C) {
4555 if (C.kind != CXCursor_IBOutletCollectionAttr)
4556 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4557
4558 IBOutletCollectionAttr *A =
4559 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4560
4561 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4562}
4563} // end: extern "C"
4564
4565//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004566// CXString Operations.
4567//===----------------------------------------------------------------------===//
4568
4569extern "C" {
4570const char *clang_getCString(CXString string) {
4571 return string.Spelling;
4572}
4573
4574void clang_disposeString(CXString string) {
4575 if (string.MustFreeString && string.Spelling)
4576 free((void*)string.Spelling);
4577}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004578
Ted Kremenekfb480492010-01-13 21:46:36 +00004579} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004580
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004581namespace clang { namespace cxstring {
4582CXString createCXString(const char *String, bool DupString){
4583 CXString Str;
4584 if (DupString) {
4585 Str.Spelling = strdup(String);
4586 Str.MustFreeString = 1;
4587 } else {
4588 Str.Spelling = String;
4589 Str.MustFreeString = 0;
4590 }
4591 return Str;
4592}
4593
4594CXString createCXString(llvm::StringRef String, bool DupString) {
4595 CXString Result;
4596 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4597 char *Spelling = (char *)malloc(String.size() + 1);
4598 memmove(Spelling, String.data(), String.size());
4599 Spelling[String.size()] = 0;
4600 Result.Spelling = Spelling;
4601 Result.MustFreeString = 1;
4602 } else {
4603 Result.Spelling = String.data();
4604 Result.MustFreeString = 0;
4605 }
4606 return Result;
4607}
4608}}
4609
Ted Kremenek04bb7162010-01-22 22:44:15 +00004610//===----------------------------------------------------------------------===//
4611// Misc. utility functions.
4612//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004613
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004614/// Default to using an 8 MB stack size on "safety" threads.
4615static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004616
4617namespace clang {
4618
4619bool RunSafely(llvm::CrashRecoveryContext &CRC,
4620 void (*Fn)(void*), void *UserData) {
4621 if (unsigned Size = GetSafetyThreadStackSize())
4622 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4623 return CRC.RunSafely(Fn, UserData);
4624}
4625
4626unsigned GetSafetyThreadStackSize() {
4627 return SafetyStackThreadSize;
4628}
4629
4630void SetSafetyThreadStackSize(unsigned Value) {
4631 SafetyStackThreadSize = Value;
4632}
4633
4634}
4635
Ted Kremenek04bb7162010-01-22 22:44:15 +00004636extern "C" {
4637
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004638CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004639 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004640}
4641
4642} // end: extern "C"