blob: 680b4d1bccae3af6362bea1b8a213c707dbf5183 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000126
127class VisitorJob {
128public:
Ted Kremenekf1107452010-11-12 18:26:56 +0000129 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000130protected:
131 void *data;
132 CXCursor parent;
133 Kind K;
134 VisitorJob(void *d, CXCursor C, Kind k) : data(d), parent(C), K(k) {}
135public:
136 Kind getKind() const { return K; }
137 const CXCursor &getParent() const { return parent; }
138 static bool classof(VisitorJob *VJ) { return true; }
139};
140
141typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
142
143#define DEF_JOB(NAME, DATA, KIND)\
144class NAME : public VisitorJob {\
145public:\
146 NAME(DATA *d, CXCursor parent) : VisitorJob(d, parent, VisitorJob::KIND) {}\
147 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
148 DATA *get() const { return static_cast<DATA*>(data); }\
149};
150
Ted Kremenekf1107452010-11-12 18:26:56 +0000151DEF_JOB(DeclVisit, Decl, DeclVisitKind)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000152DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
153DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000154#undef DEF_JOB
155
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000156static inline void WLAddStmt(VisitorWorkList &WL, CXCursor Parent, Stmt *S) {
157 if (S)
158 WL.push_back(StmtVisit(S, Parent));
159}
160static inline void WLAddDecl(VisitorWorkList &WL, CXCursor Parent, Decl *D) {
161 if (D)
162 WL.push_back(DeclVisit(D, Parent));
163}
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000167 public TypeLocVisitor<CursorVisitor, bool>,
168 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000169{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000171 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176 /// \brief The declaration that serves at the parent of any statement or
177 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000178 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000183 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000186 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
187 // to the visitor. Declarations with a PCH level greater than this value will
188 // be suppressed.
189 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190
191 /// \brief When valid, a source range to which the cursor should restrict
192 /// its search.
193 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000194
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000195 // FIXME: Eventually remove. This part of a hack to support proper
196 // iteration over all Decls contained lexically within an ObjC container.
197 DeclContext::decl_iterator *DI_current;
198 DeclContext::decl_iterator DE_current;
199
Douglas Gregorb1373d02010-01-20 20:59:29 +0000200 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000201 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000202 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000203
204 /// \brief Determine whether this particular source range comes before, comes
205 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000206 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000207 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000208 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
209
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000210 class SetParentRAII {
211 CXCursor &Parent;
212 Decl *&StmtParent;
213 CXCursor OldParent;
214
215 public:
216 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
217 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
218 {
219 Parent = NewParent;
220 if (clang_isDeclaration(Parent.kind))
221 StmtParent = getCursorDecl(Parent);
222 }
223
224 ~SetParentRAII() {
225 Parent = OldParent;
226 if (clang_isDeclaration(Parent.kind))
227 StmtParent = getCursorDecl(Parent);
228 }
229 };
230
Steve Naroff89922f82009-08-31 00:59:03 +0000231public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000232 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
233 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000234 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000236 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
237 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000238 {
239 Parent.kind = CXCursor_NoDeclFound;
240 Parent.data[0] = 0;
241 Parent.data[1] = 0;
242 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000243 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000244 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000245
Ted Kremenekab979612010-11-11 08:05:23 +0000246 ASTUnit *getASTUnit() const { return TU; }
247
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000248 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000249
250 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
251 getPreprocessedEntities();
252
Douglas Gregorb1373d02010-01-20 20:59:29 +0000253 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000254
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000255 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000256 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000257 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000258 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000259 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000260 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000261 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
262 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000263 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000264 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000265 bool VisitClassTemplatePartialSpecializationDecl(
266 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000267 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000268 bool VisitEnumConstantDecl(EnumConstantDecl *D);
269 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
270 bool VisitFunctionDecl(FunctionDecl *ND);
271 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000272 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000273 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000274 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000275 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000276 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000277 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
278 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
279 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
280 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000281 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000282 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
283 bool VisitObjCImplDecl(ObjCImplDecl *D);
284 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
285 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000286 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
287 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
288 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000289 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000290 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000291 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000292 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000293 bool VisitUsingDecl(UsingDecl *D);
294 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
295 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000296
Douglas Gregor01829d32010-08-31 14:41:23 +0000297 // Name visitor
298 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000299 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000300
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000301 // Template visitors
302 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000303 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000304 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
305
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000306 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000307 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000308 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000309 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000310 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
311 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000312 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000313 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000314 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000315 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
316 bool VisitPointerTypeLoc(PointerTypeLoc TL);
317 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
318 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
319 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
320 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000321 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000323 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000324 // FIXME: Implement visitors here when the unimplemented TypeLocs get
325 // implemented
326 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
327 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000328
Douglas Gregora59e3902010-01-21 23:27:09 +0000329 // Statement visitors
330 bool VisitStmt(Stmt *S);
331 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000332 bool VisitGotoStmt(GotoStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000333
Douglas Gregor336fd812010-01-23 00:40:08 +0000334 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000335 bool VisitDeclRefExpr(DeclRefExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000336 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000337 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000338 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000339 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000340 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000341 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000342 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000343 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000344 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
345 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000346 bool VisitInitListExpr(InitListExpr *E);
347 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000348 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000349 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000350 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000351 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
352 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000353 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000354 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000355 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000356 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000357 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000358 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000359 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000360 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000361
362#define DATA_RECURSIVE_VISIT(NAME)\
363bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
364 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000365 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000366 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000367 DATA_RECURSIVE_VISIT(DoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000368 DATA_RECURSIVE_VISIT(IfStmt)
Ted Kremenekbb677132010-11-12 18:27:04 +0000369 DATA_RECURSIVE_VISIT(ForStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000370 DATA_RECURSIVE_VISIT(MemberExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000371 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekbb677132010-11-12 18:27:04 +0000372 DATA_RECURSIVE_VISIT(WhileStmt)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000373
374 // Data-recursive visitor functions.
375 bool IsInRegionOfInterest(CXCursor C);
376 bool RunVisitorWorkList(VisitorWorkList &WL);
377 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
378 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000379};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000380
Ted Kremenekab188932010-01-05 19:32:54 +0000381} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000382
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000383static SourceRange getRawCursorExtent(CXCursor C);
384
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000386 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
387}
388
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389/// \brief Visit the given cursor and, if requested by the visitor,
390/// its children.
391///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392/// \param Cursor the cursor to visit.
393///
394/// \param CheckRegionOfInterest if true, then the caller already checked that
395/// this cursor is within the region of interest.
396///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397/// \returns true if the visitation should be aborted, false if it
398/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000399bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 if (clang_isInvalid(Cursor.kind))
401 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403 if (clang_isDeclaration(Cursor.kind)) {
404 Decl *D = getCursorDecl(Cursor);
405 assert(D && "Invalid declaration cursor");
406 if (D->getPCHLevel() > MaxPCHLevel)
407 return false;
408
409 if (D->isImplicit())
410 return false;
411 }
412
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000413 // If we have a range of interest, and this cursor doesn't intersect with it,
414 // we're done.
415 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000416 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000417 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000418 return false;
419 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000420
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 switch (Visitor(Cursor, Parent, ClientData)) {
422 case CXChildVisit_Break:
423 return true;
424
425 case CXChildVisit_Continue:
426 return false;
427
428 case CXChildVisit_Recurse:
429 return VisitChildren(Cursor);
430 }
431
Douglas Gregorfd643772010-01-25 16:45:46 +0000432 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000433}
434
Douglas Gregor788f5a12010-03-20 00:41:21 +0000435std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
436CursorVisitor::getPreprocessedEntities() {
437 PreprocessingRecord &PPRec
438 = *TU->getPreprocessor().getPreprocessingRecord();
439
440 bool OnlyLocalDecls
441 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
442
443 // There is no region of interest; we have to walk everything.
444 if (RegionOfInterest.isInvalid())
445 return std::make_pair(PPRec.begin(OnlyLocalDecls),
446 PPRec.end(OnlyLocalDecls));
447
448 // Find the file in which the region of interest lands.
449 SourceManager &SM = TU->getSourceManager();
450 std::pair<FileID, unsigned> Begin
451 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
452 std::pair<FileID, unsigned> End
453 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
454
455 // The region of interest spans files; we have to walk everything.
456 if (Begin.first != End.first)
457 return std::make_pair(PPRec.begin(OnlyLocalDecls),
458 PPRec.end(OnlyLocalDecls));
459
460 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
461 = TU->getPreprocessedEntitiesByFile();
462 if (ByFileMap.empty()) {
463 // Build the mapping from files to sets of preprocessed entities.
464 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
465 EEnd = PPRec.end(OnlyLocalDecls);
466 E != EEnd; ++E) {
467 std::pair<FileID, unsigned> P
468 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
469 ByFileMap[P.first].push_back(*E);
470 }
471 }
472
473 return std::make_pair(ByFileMap[Begin.first].begin(),
474 ByFileMap[Begin.first].end());
475}
476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477/// \brief Visit the children of the given cursor.
478///
479/// \returns true if the visitation should be aborted, false if it
480/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000482 if (clang_isReference(Cursor.kind)) {
483 // By definition, references have no children.
484 return false;
485 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000486
487 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000489 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000490
Douglas Gregorb1373d02010-01-20 20:59:29 +0000491 if (clang_isDeclaration(Cursor.kind)) {
492 Decl *D = getCursorDecl(Cursor);
493 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000494 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000496
Douglas Gregora59e3902010-01-21 23:27:09 +0000497 if (clang_isStatement(Cursor.kind))
498 return Visit(getCursorStmt(Cursor));
499 if (clang_isExpression(Cursor.kind))
500 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000501
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000503 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000504 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
505 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000506 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
507 TLEnd = CXXUnit->top_level_end();
508 TL != TLEnd; ++TL) {
509 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000510 return true;
511 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 } else if (VisitDeclContext(
513 CXXUnit->getASTContext().getTranslationUnitDecl()))
514 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000515
Douglas Gregor0396f462010-03-19 05:22:59 +0000516 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000517 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 // FIXME: Once we have the ability to deserialize a preprocessing record,
519 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000520 PreprocessingRecord::iterator E, EEnd;
521 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000522 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
523 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
524 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000525
Douglas Gregor0396f462010-03-19 05:22:59 +0000526 continue;
527 }
528
529 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
530 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
531 return true;
532
533 continue;
534 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000535
536 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
537 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
538 return true;
539
540 continue;
541 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000542 }
543 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000544 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000545 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546
Douglas Gregorb1373d02010-01-20 20:59:29 +0000547 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000548 return false;
549}
550
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000551bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000552 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
553 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000554
Ted Kremenek664cffd2010-07-22 11:30:19 +0000555 if (Stmt *Body = B->getBody())
556 return Visit(MakeCXCursor(Body, StmtParent, TU));
557
558 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000559}
560
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000561llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
562 if (RegionOfInterest.isValid()) {
563 SourceRange Range = getRawCursorExtent(Cursor);
564 if (Range.isInvalid())
565 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000566
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000567 switch (CompareRegionOfInterest(Range)) {
568 case RangeBefore:
569 // This declaration comes before the region of interest; skip it.
570 return llvm::Optional<bool>();
571
572 case RangeAfter:
573 // This declaration comes after the region of interest; we're done.
574 return false;
575
576 case RangeOverlap:
577 // This declaration overlaps the region of interest; visit it.
578 break;
579 }
580 }
581 return true;
582}
583
584bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
585 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
586
587 // FIXME: Eventually remove. This part of a hack to support proper
588 // iteration over all Decls contained lexically within an ObjC container.
589 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
590 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
591
592 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000593 Decl *D = *I;
594 if (D->getLexicalDeclContext() != DC)
595 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000596 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000597 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
598 if (!V.hasValue())
599 continue;
600 if (!V.getValue())
601 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000602 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000603 return true;
604 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000606}
607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
609 llvm_unreachable("Translation units are visited directly by Visit()");
610 return false;
611}
612
613bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
614 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
615 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000616
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000617 return false;
618}
619
620bool CursorVisitor::VisitTagDecl(TagDecl *D) {
621 return VisitDeclContext(D);
622}
623
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000624bool CursorVisitor::VisitClassTemplateSpecializationDecl(
625 ClassTemplateSpecializationDecl *D) {
626 bool ShouldVisitBody = false;
627 switch (D->getSpecializationKind()) {
628 case TSK_Undeclared:
629 case TSK_ImplicitInstantiation:
630 // Nothing to visit
631 return false;
632
633 case TSK_ExplicitInstantiationDeclaration:
634 case TSK_ExplicitInstantiationDefinition:
635 break;
636
637 case TSK_ExplicitSpecialization:
638 ShouldVisitBody = true;
639 break;
640 }
641
642 // Visit the template arguments used in the specialization.
643 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
644 TypeLoc TL = SpecType->getTypeLoc();
645 if (TemplateSpecializationTypeLoc *TSTLoc
646 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
647 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
648 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
649 return true;
650 }
651 }
652
653 if (ShouldVisitBody && VisitCXXRecordDecl(D))
654 return true;
655
656 return false;
657}
658
Douglas Gregor74dbe642010-08-31 19:31:58 +0000659bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
660 ClassTemplatePartialSpecializationDecl *D) {
661 // FIXME: Visit the "outer" template parameter lists on the TagDecl
662 // before visiting these template parameters.
663 if (VisitTemplateParameters(D->getTemplateParameters()))
664 return true;
665
666 // Visit the partial specialization arguments.
667 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
668 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
669 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
670 return true;
671
672 return VisitCXXRecordDecl(D);
673}
674
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000675bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000676 // Visit the default argument.
677 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
678 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
679 if (Visit(DefArg->getTypeLoc()))
680 return true;
681
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000682 return false;
683}
684
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000685bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
686 if (Expr *Init = D->getInitExpr())
687 return Visit(MakeCXCursor(Init, StmtParent, TU));
688 return false;
689}
690
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000691bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
692 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
693 if (Visit(TSInfo->getTypeLoc()))
694 return true;
695
696 return false;
697}
698
Douglas Gregora67e03f2010-09-09 21:42:20 +0000699/// \brief Compare two base or member initializers based on their source order.
700static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
701 CXXBaseOrMemberInitializer const * const *X
702 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
703 CXXBaseOrMemberInitializer const * const *Y
704 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
705
706 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
707 return -1;
708 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
709 return 1;
710 else
711 return 0;
712}
713
Douglas Gregorb1373d02010-01-20 20:59:29 +0000714bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000715 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
716 // Visit the function declaration's syntactic components in the order
717 // written. This requires a bit of work.
718 TypeLoc TL = TSInfo->getTypeLoc();
719 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
720
721 // If we have a function declared directly (without the use of a typedef),
722 // visit just the return type. Otherwise, just visit the function's type
723 // now.
724 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
725 (!FTL && Visit(TL)))
726 return true;
727
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000728 // Visit the nested-name-specifier, if present.
729 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
730 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
731 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000732
733 // Visit the declaration name.
734 if (VisitDeclarationNameInfo(ND->getNameInfo()))
735 return true;
736
737 // FIXME: Visit explicitly-specified template arguments!
738
739 // Visit the function parameters, if we have a function type.
740 if (FTL && VisitFunctionTypeLoc(*FTL, true))
741 return true;
742
743 // FIXME: Attributes?
744 }
745
Douglas Gregora67e03f2010-09-09 21:42:20 +0000746 if (ND->isThisDeclarationADefinition()) {
747 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
748 // Find the initializers that were written in the source.
749 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
750 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
751 IEnd = Constructor->init_end();
752 I != IEnd; ++I) {
753 if (!(*I)->isWritten())
754 continue;
755
756 WrittenInits.push_back(*I);
757 }
758
759 // Sort the initializers in source order
760 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
761 &CompareCXXBaseOrMemberInitializers);
762
763 // Visit the initializers in source order
764 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
765 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
766 if (Init->isMemberInitializer()) {
767 if (Visit(MakeCursorMemberRef(Init->getMember(),
768 Init->getMemberLocation(), TU)))
769 return true;
770 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
771 if (Visit(BaseInfo->getTypeLoc()))
772 return true;
773 }
774
775 // Visit the initializer value.
776 if (Expr *Initializer = Init->getInit())
777 if (Visit(MakeCXCursor(Initializer, ND, TU)))
778 return true;
779 }
780 }
781
782 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
783 return true;
784 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregorb1373d02010-01-20 20:59:29 +0000786 return false;
787}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000788
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000789bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
790 if (VisitDeclaratorDecl(D))
791 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000792
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000793 if (Expr *BitWidth = D->getBitWidth())
794 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000795
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796 return false;
797}
798
799bool CursorVisitor::VisitVarDecl(VarDecl *D) {
800 if (VisitDeclaratorDecl(D))
801 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000803 if (Expr *Init = D->getInit())
804 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000806 return false;
807}
808
Douglas Gregor84b51d72010-09-01 20:16:53 +0000809bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
810 if (VisitDeclaratorDecl(D))
811 return true;
812
813 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
814 if (Expr *DefArg = D->getDefaultArgument())
815 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
816
817 return false;
818}
819
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000820bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
821 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
822 // before visiting these template parameters.
823 if (VisitTemplateParameters(D->getTemplateParameters()))
824 return true;
825
826 return VisitFunctionDecl(D->getTemplatedDecl());
827}
828
Douglas Gregor39d6f072010-08-31 19:02:00 +0000829bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
830 // FIXME: Visit the "outer" template parameter lists on the TagDecl
831 // before visiting these template parameters.
832 if (VisitTemplateParameters(D->getTemplateParameters()))
833 return true;
834
835 return VisitCXXRecordDecl(D->getTemplatedDecl());
836}
837
Douglas Gregor84b51d72010-09-01 20:16:53 +0000838bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
839 if (VisitTemplateParameters(D->getTemplateParameters()))
840 return true;
841
842 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
843 VisitTemplateArgumentLoc(D->getDefaultArgument()))
844 return true;
845
846 return false;
847}
848
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000850 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
851 if (Visit(TSInfo->getTypeLoc()))
852 return true;
853
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000854 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855 PEnd = ND->param_end();
856 P != PEnd; ++P) {
857 if (Visit(MakeCXCursor(*P, TU)))
858 return true;
859 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000860
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000861 if (ND->isThisDeclarationADefinition() &&
862 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
863 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000864
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000865 return false;
866}
867
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000868namespace {
869 struct ContainerDeclsSort {
870 SourceManager &SM;
871 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
872 bool operator()(Decl *A, Decl *B) {
873 SourceLocation L_A = A->getLocStart();
874 SourceLocation L_B = B->getLocStart();
875 assert(L_A.isValid() && L_B.isValid());
876 return SM.isBeforeInTranslationUnit(L_A, L_B);
877 }
878 };
879}
880
Douglas Gregora59e3902010-01-21 23:27:09 +0000881bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000882 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
883 // an @implementation can lexically contain Decls that are not properly
884 // nested in the AST. When we identify such cases, we need to retrofit
885 // this nesting here.
886 if (!DI_current)
887 return VisitDeclContext(D);
888
889 // Scan the Decls that immediately come after the container
890 // in the current DeclContext. If any fall within the
891 // container's lexical region, stash them into a vector
892 // for later processing.
893 llvm::SmallVector<Decl *, 24> DeclsInContainer;
894 SourceLocation EndLoc = D->getSourceRange().getEnd();
895 SourceManager &SM = TU->getSourceManager();
896 if (EndLoc.isValid()) {
897 DeclContext::decl_iterator next = *DI_current;
898 while (++next != DE_current) {
899 Decl *D_next = *next;
900 if (!D_next)
901 break;
902 SourceLocation L = D_next->getLocStart();
903 if (!L.isValid())
904 break;
905 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
906 *DI_current = next;
907 DeclsInContainer.push_back(D_next);
908 continue;
909 }
910 break;
911 }
912 }
913
914 // The common case.
915 if (DeclsInContainer.empty())
916 return VisitDeclContext(D);
917
918 // Get all the Decls in the DeclContext, and sort them with the
919 // additional ones we've collected. Then visit them.
920 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
921 I!=E; ++I) {
922 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000923 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
924 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000925 continue;
926 DeclsInContainer.push_back(subDecl);
927 }
928
929 // Now sort the Decls so that they appear in lexical order.
930 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
931 ContainerDeclsSort(SM));
932
933 // Now visit the decls.
934 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
935 E = DeclsInContainer.end(); I != E; ++I) {
936 CXCursor Cursor = MakeCXCursor(*I, TU);
937 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
938 if (!V.hasValue())
939 continue;
940 if (!V.getValue())
941 return false;
942 if (Visit(Cursor, true))
943 return true;
944 }
945 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000946}
947
Douglas Gregorb1373d02010-01-20 20:59:29 +0000948bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000949 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
950 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000951 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000952
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000953 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
954 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
955 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000956 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000957 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000958
Douglas Gregora59e3902010-01-21 23:27:09 +0000959 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000960}
961
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000962bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
963 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
964 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
965 E = PID->protocol_end(); I != E; ++I, ++PL)
966 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
967 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000968
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000969 return VisitObjCContainerDecl(PID);
970}
971
Ted Kremenek23173d72010-05-18 21:09:07 +0000972bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000973 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000974 return true;
975
Ted Kremenek23173d72010-05-18 21:09:07 +0000976 // FIXME: This implements a workaround with @property declarations also being
977 // installed in the DeclContext for the @interface. Eventually this code
978 // should be removed.
979 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
980 if (!CDecl || !CDecl->IsClassExtension())
981 return false;
982
983 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
984 if (!ID)
985 return false;
986
987 IdentifierInfo *PropertyId = PD->getIdentifier();
988 ObjCPropertyDecl *prevDecl =
989 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
990
991 if (!prevDecl)
992 return false;
993
994 // Visit synthesized methods since they will be skipped when visiting
995 // the @interface.
996 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000997 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000998 if (Visit(MakeCXCursor(MD, TU)))
999 return true;
1000
1001 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001002 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001003 if (Visit(MakeCXCursor(MD, TU)))
1004 return true;
1005
1006 return false;
1007}
1008
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001010 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001011 if (D->getSuperClass() &&
1012 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001014 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001017 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1018 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1019 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001020 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001021 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022
Douglas Gregora59e3902010-01-21 23:27:09 +00001023 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001024}
1025
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1027 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001028}
1029
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001030bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001031 // 'ID' could be null when dealing with invalid code.
1032 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1033 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1034 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001035
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001036 return VisitObjCImplDecl(D);
1037}
1038
1039bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1040#if 0
1041 // Issue callbacks for super class.
1042 // FIXME: No source location information!
1043 if (D->getSuperClass() &&
1044 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046 TU)))
1047 return true;
1048#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001050 return VisitObjCImplDecl(D);
1051}
1052
1053bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1054 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1055 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1056 E = D->protocol_end();
1057 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001058 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001059 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
1061 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001062}
1063
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001064bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1065 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1066 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1067 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001068
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001069 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001070}
1071
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001072bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1073 return VisitDeclContext(D);
1074}
1075
Douglas Gregor69319002010-08-31 23:48:11 +00001076bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
1078 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1079 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1080 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001081
1082 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1083 D->getTargetNameLoc(), TU));
1084}
1085
Douglas Gregor7e242562010-09-01 19:52:22 +00001086bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 // Visit nested-name-specifier.
1088 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1089 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1090 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001091
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001092 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1093 return true;
1094
Douglas Gregor7e242562010-09-01 19:52:22 +00001095 return VisitDeclarationNameInfo(D->getNameInfo());
1096}
1097
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001098bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001099 // Visit nested-name-specifier.
1100 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1101 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1102 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001103
1104 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1105 D->getIdentLocation(), TU));
1106}
1107
Douglas Gregor7e242562010-09-01 19:52:22 +00001108bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001109 // Visit nested-name-specifier.
1110 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1111 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1112 return true;
1113
Douglas Gregor7e242562010-09-01 19:52:22 +00001114 return VisitDeclarationNameInfo(D->getNameInfo());
1115}
1116
1117bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1118 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119 // Visit nested-name-specifier.
1120 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1121 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1122 return true;
1123
Douglas Gregor7e242562010-09-01 19:52:22 +00001124 return false;
1125}
1126
Douglas Gregor01829d32010-08-31 14:41:23 +00001127bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1128 switch (Name.getName().getNameKind()) {
1129 case clang::DeclarationName::Identifier:
1130 case clang::DeclarationName::CXXLiteralOperatorName:
1131 case clang::DeclarationName::CXXOperatorName:
1132 case clang::DeclarationName::CXXUsingDirective:
1133 return false;
1134
1135 case clang::DeclarationName::CXXConstructorName:
1136 case clang::DeclarationName::CXXDestructorName:
1137 case clang::DeclarationName::CXXConversionFunctionName:
1138 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1139 return Visit(TSInfo->getTypeLoc());
1140 return false;
1141
1142 case clang::DeclarationName::ObjCZeroArgSelector:
1143 case clang::DeclarationName::ObjCOneArgSelector:
1144 case clang::DeclarationName::ObjCMultiArgSelector:
1145 // FIXME: Per-identifier location info?
1146 return false;
1147 }
1148
1149 return false;
1150}
1151
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001152bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1153 SourceRange Range) {
1154 // FIXME: This whole routine is a hack to work around the lack of proper
1155 // source information in nested-name-specifiers (PR5791). Since we do have
1156 // a beginning source location, we can visit the first component of the
1157 // nested-name-specifier, if it's a single-token component.
1158 if (!NNS)
1159 return false;
1160
1161 // Get the first component in the nested-name-specifier.
1162 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1163 NNS = Prefix;
1164
1165 switch (NNS->getKind()) {
1166 case NestedNameSpecifier::Namespace:
1167 // FIXME: The token at this source location might actually have been a
1168 // namespace alias, but we don't model that. Lame!
1169 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1170 TU));
1171
1172 case NestedNameSpecifier::TypeSpec: {
1173 // If the type has a form where we know that the beginning of the source
1174 // range matches up with a reference cursor. Visit the appropriate reference
1175 // cursor.
1176 Type *T = NNS->getAsType();
1177 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1178 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1179 if (const TagType *Tag = dyn_cast<TagType>(T))
1180 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1181 if (const TemplateSpecializationType *TST
1182 = dyn_cast<TemplateSpecializationType>(T))
1183 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1184 break;
1185 }
1186
1187 case NestedNameSpecifier::TypeSpecWithTemplate:
1188 case NestedNameSpecifier::Global:
1189 case NestedNameSpecifier::Identifier:
1190 break;
1191 }
1192
1193 return false;
1194}
1195
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001196bool CursorVisitor::VisitTemplateParameters(
1197 const TemplateParameterList *Params) {
1198 if (!Params)
1199 return false;
1200
1201 for (TemplateParameterList::const_iterator P = Params->begin(),
1202 PEnd = Params->end();
1203 P != PEnd; ++P) {
1204 if (Visit(MakeCXCursor(*P, TU)))
1205 return true;
1206 }
1207
1208 return false;
1209}
1210
Douglas Gregor0b36e612010-08-31 20:37:03 +00001211bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1212 switch (Name.getKind()) {
1213 case TemplateName::Template:
1214 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1215
1216 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001217 // Visit the overloaded template set.
1218 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1219 return true;
1220
Douglas Gregor0b36e612010-08-31 20:37:03 +00001221 return false;
1222
1223 case TemplateName::DependentTemplate:
1224 // FIXME: Visit nested-name-specifier.
1225 return false;
1226
1227 case TemplateName::QualifiedTemplate:
1228 // FIXME: Visit nested-name-specifier.
1229 return Visit(MakeCursorTemplateRef(
1230 Name.getAsQualifiedTemplateName()->getDecl(),
1231 Loc, TU));
1232 }
1233
1234 return false;
1235}
1236
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001237bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1238 switch (TAL.getArgument().getKind()) {
1239 case TemplateArgument::Null:
1240 case TemplateArgument::Integral:
1241 return false;
1242
1243 case TemplateArgument::Pack:
1244 // FIXME: Implement when variadic templates come along.
1245 return false;
1246
1247 case TemplateArgument::Type:
1248 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1249 return Visit(TSInfo->getTypeLoc());
1250 return false;
1251
1252 case TemplateArgument::Declaration:
1253 if (Expr *E = TAL.getSourceDeclExpression())
1254 return Visit(MakeCXCursor(E, StmtParent, TU));
1255 return false;
1256
1257 case TemplateArgument::Expression:
1258 if (Expr *E = TAL.getSourceExpression())
1259 return Visit(MakeCXCursor(E, StmtParent, TU));
1260 return false;
1261
1262 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001263 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1264 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001265 }
1266
1267 return false;
1268}
1269
Ted Kremeneka0536d82010-05-07 01:04:29 +00001270bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1271 return VisitDeclContext(D);
1272}
1273
Douglas Gregor01829d32010-08-31 14:41:23 +00001274bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1275 return Visit(TL.getUnqualifiedLoc());
1276}
1277
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1279 ASTContext &Context = TU->getASTContext();
1280
1281 // Some builtin types (such as Objective-C's "id", "sel", and
1282 // "Class") have associated declarations. Create cursors for those.
1283 QualType VisitType;
1284 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001285 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001286 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001287 case BuiltinType::Char_U:
1288 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001289 case BuiltinType::Char16:
1290 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001291 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001292 case BuiltinType::UInt:
1293 case BuiltinType::ULong:
1294 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001295 case BuiltinType::UInt128:
1296 case BuiltinType::Char_S:
1297 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001298 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001299 case BuiltinType::Short:
1300 case BuiltinType::Int:
1301 case BuiltinType::Long:
1302 case BuiltinType::LongLong:
1303 case BuiltinType::Int128:
1304 case BuiltinType::Float:
1305 case BuiltinType::Double:
1306 case BuiltinType::LongDouble:
1307 case BuiltinType::NullPtr:
1308 case BuiltinType::Overload:
1309 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001310 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001311
1312 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001313 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001314
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001315 case BuiltinType::ObjCId:
1316 VisitType = Context.getObjCIdType();
1317 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001318
1319 case BuiltinType::ObjCClass:
1320 VisitType = Context.getObjCClassType();
1321 break;
1322
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323 case BuiltinType::ObjCSel:
1324 VisitType = Context.getObjCSelType();
1325 break;
1326 }
1327
1328 if (!VisitType.isNull()) {
1329 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001330 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331 TU));
1332 }
1333
1334 return false;
1335}
1336
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001337bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1338 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1339}
1340
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1342 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1343}
1344
1345bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1346 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1347}
1348
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001349bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001350 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001351 // no context information with which we can match up the depth/index in the
1352 // type to the appropriate
1353 return false;
1354}
1355
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001356bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1357 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1358 return true;
1359
John McCallc12c5bb2010-05-15 11:32:37 +00001360 return false;
1361}
1362
1363bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1364 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1365 return true;
1366
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1368 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1369 TU)))
1370 return true;
1371 }
1372
1373 return false;
1374}
1375
1376bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001377 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378}
1379
1380bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1381 return Visit(TL.getPointeeLoc());
1382}
1383
1384bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1385 return Visit(TL.getPointeeLoc());
1386}
1387
1388bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1389 return Visit(TL.getPointeeLoc());
1390}
1391
1392bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394}
1395
1396bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001397 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001398}
1399
Douglas Gregor01829d32010-08-31 14:41:23 +00001400bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1401 bool SkipResultType) {
1402 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001403 return true;
1404
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001405 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001406 if (Decl *D = TL.getArg(I))
1407 if (Visit(MakeCXCursor(D, TU)))
1408 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409
1410 return false;
1411}
1412
1413bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1414 if (Visit(TL.getElementLoc()))
1415 return true;
1416
1417 if (Expr *Size = TL.getSizeExpr())
1418 return Visit(MakeCXCursor(Size, StmtParent, TU));
1419
1420 return false;
1421}
1422
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001423bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1424 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001425 // Visit the template name.
1426 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1427 TL.getTemplateNameLoc()))
1428 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001429
1430 // Visit the template arguments.
1431 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1432 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1433 return true;
1434
1435 return false;
1436}
1437
Douglas Gregor2332c112010-01-21 20:48:56 +00001438bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1439 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1440}
1441
1442bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1443 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1444 return Visit(TSInfo->getTypeLoc());
1445
1446 return false;
1447}
1448
Douglas Gregora59e3902010-01-21 23:27:09 +00001449bool CursorVisitor::VisitStmt(Stmt *S) {
1450 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1451 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001452 if (Stmt *C = *Child)
1453 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1454 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001455 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001456
Douglas Gregora59e3902010-01-21 23:27:09 +00001457 return false;
1458}
1459
1460bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001461 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001462 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1463 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001464 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001465 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001466 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001468
Douglas Gregora59e3902010-01-21 23:27:09 +00001469 return false;
1470}
1471
Douglas Gregor36897b02010-09-10 00:22:18 +00001472bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1473 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1474}
1475
Douglas Gregor8947a752010-09-02 20:35:02 +00001476bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1477 // Visit nested-name-specifier, if present.
1478 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1479 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1480 return true;
1481
1482 // Visit declaration name.
1483 if (VisitDeclarationNameInfo(E->getNameInfo()))
1484 return true;
1485
1486 // Visit explicitly-specified template arguments.
1487 if (E->hasExplicitTemplateArgs()) {
1488 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1489 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1490 *ArgEnd = Arg + Args.NumTemplateArgs;
1491 Arg != ArgEnd; ++Arg)
1492 if (VisitTemplateArgumentLoc(*Arg))
1493 return true;
1494 }
1495
1496 return false;
1497}
1498
Ted Kremenek3064ef92010-08-27 21:34:58 +00001499bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1500 if (D->isDefinition()) {
1501 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1502 E = D->bases_end(); I != E; ++I) {
1503 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1504 return true;
1505 }
1506 }
1507
1508 return VisitTagDecl(D);
1509}
1510
1511
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001512bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1513 return Visit(B->getBlockDecl());
1514}
1515
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001516bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001517 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001518 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1519 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001520
1521 // Visit the components of the offsetof expression.
1522 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1523 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1524 const OffsetOfNode &Node = E->getComponent(I);
1525 switch (Node.getKind()) {
1526 case OffsetOfNode::Array:
1527 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1528 StmtParent, TU)))
1529 return true;
1530 break;
1531
1532 case OffsetOfNode::Field:
1533 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1534 TU)))
1535 return true;
1536 break;
1537
1538 case OffsetOfNode::Identifier:
1539 case OffsetOfNode::Base:
1540 continue;
1541 }
1542 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001543
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001544 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001545}
1546
Douglas Gregor336fd812010-01-23 00:40:08 +00001547bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1548 if (E->isArgumentType()) {
1549 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1550 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001551
Douglas Gregor336fd812010-01-23 00:40:08 +00001552 return false;
1553 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001554
Douglas Gregor336fd812010-01-23 00:40:08 +00001555 return VisitExpr(E);
1556}
1557
1558bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1559 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1560 if (Visit(TSInfo->getTypeLoc()))
1561 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001562
Douglas Gregor336fd812010-01-23 00:40:08 +00001563 return VisitCastExpr(E);
1564}
1565
1566bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1567 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1568 if (Visit(TSInfo->getTypeLoc()))
1569 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001570
Douglas Gregor336fd812010-01-23 00:40:08 +00001571 return VisitExpr(E);
1572}
1573
Douglas Gregor36897b02010-09-10 00:22:18 +00001574bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1575 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1576}
1577
Douglas Gregor648220e2010-08-10 15:02:34 +00001578bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1579 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1580 Visit(E->getArgTInfo2()->getTypeLoc());
1581}
1582
1583bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1584 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1585 return true;
1586
1587 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1588}
1589
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001590bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1591 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001592 if (InitListExpr *Syntactic = E->getSyntacticForm())
1593 return VisitExpr(Syntactic);
1594
1595 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001596}
1597
1598bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1599 // Visit the designators.
1600 typedef DesignatedInitExpr::Designator Designator;
1601 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1602 DEnd = E->designators_end();
1603 D != DEnd; ++D) {
1604 if (D->isFieldDesignator()) {
1605 if (FieldDecl *Field = D->getField())
1606 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1607 return true;
1608
1609 continue;
1610 }
1611
1612 if (D->isArrayDesignator()) {
1613 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1614 return true;
1615
1616 continue;
1617 }
1618
1619 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1620 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1621 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1622 return true;
1623 }
1624
1625 // Visit the initializer value itself.
1626 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1627}
1628
Douglas Gregor94802292010-09-02 21:20:16 +00001629bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1630 if (E->isTypeOperand()) {
1631 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1632 return Visit(TSInfo->getTypeLoc());
1633
1634 return false;
1635 }
1636
1637 return VisitExpr(E);
1638}
1639
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001640bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1641 if (E->isTypeOperand()) {
1642 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1643 return Visit(TSInfo->getTypeLoc());
1644
1645 return false;
1646 }
1647
1648 return VisitExpr(E);
1649}
1650
Douglas Gregorab6677e2010-09-08 00:15:04 +00001651bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1652 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001653 if (Visit(TSInfo->getTypeLoc()))
1654 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001655
1656 return VisitExpr(E);
1657}
1658
1659bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1660 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1661 return Visit(TSInfo->getTypeLoc());
1662
1663 return false;
1664}
1665
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001666bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1667 // Visit placement arguments.
1668 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1669 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1670 return true;
1671
1672 // Visit the allocated type.
1673 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1674 if (Visit(TSInfo->getTypeLoc()))
1675 return true;
1676
1677 // Visit the array size, if any.
1678 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1679 return true;
1680
1681 // Visit the initializer or constructor arguments.
1682 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1683 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1684 return true;
1685
1686 return false;
1687}
1688
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001689bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1690 // Visit base expression.
1691 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1692 return true;
1693
1694 // Visit the nested-name-specifier.
1695 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1696 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1697 return true;
1698
1699 // Visit the scope type that looks disturbingly like the nested-name-specifier
1700 // but isn't.
1701 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1702 if (Visit(TSInfo->getTypeLoc()))
1703 return true;
1704
1705 // Visit the name of the type being destroyed.
1706 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1707 if (Visit(TSInfo->getTypeLoc()))
1708 return true;
1709
1710 return false;
1711}
1712
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001713bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1714 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1715}
1716
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001717bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001718 // Visit the nested-name-specifier.
1719 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1720 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1721 return true;
1722
1723 // Visit the declaration name.
1724 if (VisitDeclarationNameInfo(E->getNameInfo()))
1725 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001726
1727 // Visit the overloaded declaration reference.
1728 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1729 return true;
1730
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001731 // Visit the explicitly-specified template arguments.
1732 if (const ExplicitTemplateArgumentList *ArgList
1733 = E->getOptionalExplicitTemplateArgs()) {
1734 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1735 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1736 Arg != ArgEnd; ++Arg) {
1737 if (VisitTemplateArgumentLoc(*Arg))
1738 return true;
1739 }
1740 }
1741
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001742 return false;
1743}
1744
Douglas Gregorbfebed22010-09-03 17:24:10 +00001745bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1746 DependentScopeDeclRefExpr *E) {
1747 // Visit the nested-name-specifier.
1748 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1749 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1750 return true;
1751
1752 // Visit the declaration name.
1753 if (VisitDeclarationNameInfo(E->getNameInfo()))
1754 return true;
1755
1756 // Visit the explicitly-specified template arguments.
1757 if (const ExplicitTemplateArgumentList *ArgList
1758 = E->getOptionalExplicitTemplateArgs()) {
1759 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1760 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1761 Arg != ArgEnd; ++Arg) {
1762 if (VisitTemplateArgumentLoc(*Arg))
1763 return true;
1764 }
1765 }
1766
1767 return false;
1768}
1769
Douglas Gregorab6677e2010-09-08 00:15:04 +00001770bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1771 CXXUnresolvedConstructExpr *E) {
1772 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1773 if (Visit(TSInfo->getTypeLoc()))
1774 return true;
1775
1776 return VisitExpr(E);
1777}
1778
Douglas Gregor25d63622010-09-03 17:35:34 +00001779bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1780 CXXDependentScopeMemberExpr *E) {
1781 // Visit the base expression, if there is one.
1782 if (!E->isImplicitAccess() &&
1783 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1784 return true;
1785
1786 // Visit the nested-name-specifier.
1787 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1788 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1789 return true;
1790
1791 // Visit the declaration name.
1792 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1793 return true;
1794
1795 // Visit the explicitly-specified template arguments.
1796 if (const ExplicitTemplateArgumentList *ArgList
1797 = E->getOptionalExplicitTemplateArgs()) {
1798 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1799 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1800 Arg != ArgEnd; ++Arg) {
1801 if (VisitTemplateArgumentLoc(*Arg))
1802 return true;
1803 }
1804 }
1805
1806 return false;
1807}
1808
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001809bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1810 // Visit the base expression, if there is one.
1811 if (!E->isImplicitAccess() &&
1812 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1813 return true;
1814
1815 return VisitOverloadExpr(E);
1816}
Douglas Gregor25d63622010-09-03 17:35:34 +00001817
Douglas Gregorc2350e52010-03-08 16:40:19 +00001818bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001819 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1820 if (Visit(TSInfo->getTypeLoc()))
1821 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001822
1823 return VisitExpr(E);
1824}
1825
Douglas Gregor81d34662010-04-20 15:39:42 +00001826bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1827 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1828}
1829
1830
Ted Kremenek09dfa372010-02-18 05:46:33 +00001831bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001832 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1833 i != e; ++i)
1834 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001835 return true;
1836
1837 return false;
1838}
1839
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001840//===----------------------------------------------------------------------===//
1841// Data-recursive visitor methods.
1842//===----------------------------------------------------------------------===//
1843
1844void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1845 CXCursor C = MakeCXCursor(S, StmtParent, TU);
1846 switch (S->getStmtClass()) {
1847 default: {
1848 unsigned size = WL.size();
1849 for (Stmt::child_iterator Child = S->child_begin(),
1850 ChildEnd = S->child_end(); Child != ChildEnd; ++Child) {
Ted Kremenekae3c2202010-11-12 18:27:01 +00001851 WLAddStmt(WL, C, *Child);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001852 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001853 if (size == WL.size())
1854 return;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001855 // Now reverse the entries we just added. This will match the DFS
1856 // ordering performed by the worklist.
1857 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1858 std::reverse(I, E);
1859 break;
Ted Kremenekf1107452010-11-12 18:26:56 +00001860 }
1861 case Stmt::CXXOperatorCallExprClass: {
1862 CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(S);
1863 // Note that we enqueue things in reverse order so that
1864 // they are visited correctly by the DFS.
Ted Kremenekf1107452010-11-12 18:26:56 +00001865 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
Ted Kremenekae3c2202010-11-12 18:27:01 +00001866 WLAddStmt(WL, C, CE->getArg(N-I));
Ted Kremenekf1107452010-11-12 18:26:56 +00001867
Ted Kremenekae3c2202010-11-12 18:27:01 +00001868 WLAddStmt(WL, C, CE->getCallee());
1869 WLAddStmt(WL, C, CE->getArg(0));
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001870 break;
1871 }
1872 case Stmt::BinaryOperatorClass: {
1873 BinaryOperator *B = cast<BinaryOperator>(S);
Ted Kremenekae3c2202010-11-12 18:27:01 +00001874 WLAddStmt(WL, C, B->getRHS());
1875 WLAddStmt(WL, C, B->getLHS());
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001876 break;
1877 }
Ted Kremenekbb677132010-11-12 18:27:04 +00001878 case Stmt::ForStmtClass: {
1879 ForStmt *FS = cast<ForStmt>(S);
1880 WLAddStmt(WL, C, FS->getBody());
1881 WLAddStmt(WL, C, FS->getInc());
1882 WLAddStmt(WL, C, FS->getCond());
1883 WLAddDecl(WL, C, FS->getConditionVariable());
1884 WLAddStmt(WL, C, FS->getInit());
1885 break;
1886 }
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001887 case Stmt::IfStmtClass: {
1888 IfStmt *If = cast<IfStmt>(S);
1889 WLAddStmt(WL, C, If->getElse());
1890 WLAddStmt(WL, C, If->getThen());
1891 WLAddStmt(WL, C, If->getCond());
Ted Kremenekae3c2202010-11-12 18:27:01 +00001892 WLAddDecl(WL, C, If->getConditionVariable());
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001893 break;
1894 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001895 case Stmt::MemberExprClass: {
1896 MemberExpr *M = cast<MemberExpr>(S);
1897 WL.push_back(MemberExprParts(M, C));
Ted Kremenekae3c2202010-11-12 18:27:01 +00001898 WLAddStmt(WL, C, M->getBase());
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001899 break;
1900 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001901 case Stmt::ParenExprClass: {
Ted Kremenekae3c2202010-11-12 18:27:01 +00001902 WLAddStmt(WL, C, cast<ParenExpr>(S)->getSubExpr());
Ted Kremenekf1107452010-11-12 18:26:56 +00001903 break;
1904 }
1905 case Stmt::SwitchStmtClass: {
1906 SwitchStmt *SS = cast<SwitchStmt>(S);
Ted Kremenekae3c2202010-11-12 18:27:01 +00001907 WLAddStmt(WL, C, SS->getBody());
1908 WLAddStmt(WL, C, SS->getCond());
1909 WLAddDecl(WL, C, SS->getConditionVariable());
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001910 break;
1911 }
Ted Kremenekbb677132010-11-12 18:27:04 +00001912 case Stmt::WhileStmtClass: {
1913 WhileStmt *W = cast<WhileStmt>(S);
1914 WLAddStmt(WL, C, W->getBody());
1915 WLAddStmt(WL, C, W->getCond());
1916 WLAddDecl(WL, C, W->getConditionVariable());
1917 break;
1918 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001919 }
1920}
1921
1922bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1923 if (RegionOfInterest.isValid()) {
1924 SourceRange Range = getRawCursorExtent(C);
1925 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1926 return false;
1927 }
1928 return true;
1929}
1930
1931bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1932 while (!WL.empty()) {
1933 // Dequeue the worklist item.
1934 VisitorJob LI = WL.back(); WL.pop_back();
1935
1936 // Set the Parent field, then back to its old value once we're done.
1937 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1938
1939 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001940 case VisitorJob::DeclVisitKind: {
1941 Decl *D = cast<DeclVisit>(LI).get();
1942 if (!D)
1943 continue;
1944
1945 // For now, perform default visitation for Decls.
1946 if (Visit(MakeCXCursor(D, TU)))
1947 return true;
1948
1949 continue;
1950 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001951 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001952 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001953 if (!S)
1954 continue;
1955
Ted Kremenekf1107452010-11-12 18:26:56 +00001956 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001957 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1958
1959 switch (S->getStmtClass()) {
1960 default: {
1961 // Perform default visitation for other cases.
1962 if (Visit(Cursor))
1963 return true;
1964 continue;
1965 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001966 case Stmt::BinaryOperatorClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001967 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001968 case Stmt::CaseStmtClass:
1969 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001970 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001971 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001972 case Stmt::DefaultStmtClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001973 case Stmt::DoStmtClass:
1974 case Stmt::ForStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001975 case Stmt::IfStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001976 case Stmt::MemberExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001977 case Stmt::ParenExprClass:
1978 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00001979 case Stmt::UnaryOperatorClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001980 case Stmt::WhileStmtClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001981 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001982 if (!IsInRegionOfInterest(Cursor))
1983 continue;
1984 switch (Visitor(Cursor, Parent, ClientData)) {
1985 case CXChildVisit_Break:
1986 return true;
1987 case CXChildVisit_Continue:
1988 break;
1989 case CXChildVisit_Recurse:
1990 EnqueueWorkList(WL, S);
1991 break;
1992 }
1993 }
1994 }
1995 continue;
1996 }
1997 case VisitorJob::MemberExprPartsKind: {
1998 // Handle the other pieces in the MemberExpr besides the base.
1999 MemberExpr *M = cast<MemberExprParts>(LI).get();
2000
2001 // Visit the nested-name-specifier
2002 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2003 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2004 return true;
2005
2006 // Visit the declaration name.
2007 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2008 return true;
2009
2010 // Visit the explicitly-specified template arguments, if any.
2011 if (M->hasExplicitTemplateArgs()) {
2012 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2013 *ArgEnd = Arg + M->getNumTemplateArgs();
2014 Arg != ArgEnd; ++Arg) {
2015 if (VisitTemplateArgumentLoc(*Arg))
2016 return true;
2017 }
2018 }
2019 continue;
2020 }
2021 }
2022 }
2023 return false;
2024}
2025
2026bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2027 VisitorWorkList WL;
2028 EnqueueWorkList(WL, S);
2029 return RunVisitorWorkList(WL);
2030}
2031
2032//===----------------------------------------------------------------------===//
2033// Misc. API hooks.
2034//===----------------------------------------------------------------------===//
2035
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002036static llvm::sys::Mutex EnableMultithreadingMutex;
2037static bool EnabledMultithreading;
2038
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002039extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002040CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2041 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002042 // Disable pretty stack trace functionality, which will otherwise be a very
2043 // poor citizen of the world and set up all sorts of signal handlers.
2044 llvm::DisablePrettyStackTrace = true;
2045
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002046 // We use crash recovery to make some of our APIs more reliable, implicitly
2047 // enable it.
2048 llvm::CrashRecoveryContext::Enable();
2049
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002050 // Enable support for multithreading in LLVM.
2051 {
2052 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2053 if (!EnabledMultithreading) {
2054 llvm::llvm_start_multithreaded();
2055 EnabledMultithreading = true;
2056 }
2057 }
2058
Douglas Gregora030b7c2010-01-22 20:35:53 +00002059 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002060 if (excludeDeclarationsFromPCH)
2061 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002062 if (displayDiagnostics)
2063 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002064 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002065}
2066
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002067void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002068 if (CIdx)
2069 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002070}
2071
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002072CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002073 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002074 if (!CIdx)
2075 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002076
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002077 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002078 FileSystemOptions FileSystemOpts;
2079 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002080
Douglas Gregor28019772010-04-05 23:52:57 +00002081 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002082 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002083 CXXIdx->getOnlyLocalDecls(),
2084 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002085}
2086
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002087unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002088 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002089 CXTranslationUnit_CacheCompletionResults |
2090 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002091}
2092
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002093CXTranslationUnit
2094clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2095 const char *source_filename,
2096 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002097 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002098 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002099 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002100 return clang_parseTranslationUnit(CIdx, source_filename,
2101 command_line_args, num_command_line_args,
2102 unsaved_files, num_unsaved_files,
2103 CXTranslationUnit_DetailedPreprocessingRecord);
2104}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002105
2106struct ParseTranslationUnitInfo {
2107 CXIndex CIdx;
2108 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002109 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002110 int num_command_line_args;
2111 struct CXUnsavedFile *unsaved_files;
2112 unsigned num_unsaved_files;
2113 unsigned options;
2114 CXTranslationUnit result;
2115};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002116static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002117 ParseTranslationUnitInfo *PTUI =
2118 static_cast<ParseTranslationUnitInfo*>(UserData);
2119 CXIndex CIdx = PTUI->CIdx;
2120 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002121 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002122 int num_command_line_args = PTUI->num_command_line_args;
2123 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2124 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2125 unsigned options = PTUI->options;
2126 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002127
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002128 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002129 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002130
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002131 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2132
Douglas Gregor44c181a2010-07-23 00:33:23 +00002133 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002134 bool CompleteTranslationUnit
2135 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002136 bool CacheCodeCompetionResults
2137 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002138 bool CXXPrecompilePreamble
2139 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2140 bool CXXChainedPCH
2141 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002142
Douglas Gregor5352ac02010-01-28 00:27:43 +00002143 // Configure the diagnostics.
2144 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002145 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2146 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002147
Douglas Gregor4db64a42010-01-23 00:14:00 +00002148 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2149 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002150 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002151 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002152 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002153 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2154 Buffer));
2155 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002156
Douglas Gregorb10daed2010-10-11 16:52:23 +00002157 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002158
Ted Kremenek139ba862009-10-22 00:03:57 +00002159 // The 'source_filename' argument is optional. If the caller does not
2160 // specify it then it is assumed that the source file is specified
2161 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002162 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002163 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002164
2165 // Since the Clang C library is primarily used by batch tools dealing with
2166 // (often very broken) source code, where spell-checking can have a
2167 // significant negative impact on performance (particularly when
2168 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002169 // Only do this if we haven't found a spell-checking-related argument.
2170 bool FoundSpellCheckingArgument = false;
2171 for (int I = 0; I != num_command_line_args; ++I) {
2172 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2173 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2174 FoundSpellCheckingArgument = true;
2175 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002176 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002177 }
2178 if (!FoundSpellCheckingArgument)
2179 Args.push_back("-fno-spell-checking");
2180
2181 Args.insert(Args.end(), command_line_args,
2182 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002183
Douglas Gregor44c181a2010-07-23 00:33:23 +00002184 // Do we need the detailed preprocessing record?
2185 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002186 Args.push_back("-Xclang");
2187 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002188 }
2189
Douglas Gregorb10daed2010-10-11 16:52:23 +00002190 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002191 llvm::OwningPtr<ASTUnit> Unit(
2192 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2193 Diags,
2194 CXXIdx->getClangResourcesPath(),
2195 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002196 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002197 RemappedFiles.data(),
2198 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002199 PrecompilePreamble,
2200 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002201 CacheCodeCompetionResults,
2202 CXXPrecompilePreamble,
2203 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002204
Douglas Gregorb10daed2010-10-11 16:52:23 +00002205 if (NumErrors != Diags->getNumErrors()) {
2206 // Make sure to check that 'Unit' is non-NULL.
2207 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2208 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2209 DEnd = Unit->stored_diag_end();
2210 D != DEnd; ++D) {
2211 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2212 CXString Msg = clang_formatDiagnostic(&Diag,
2213 clang_defaultDiagnosticDisplayOptions());
2214 fprintf(stderr, "%s\n", clang_getCString(Msg));
2215 clang_disposeString(Msg);
2216 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002217#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 // On Windows, force a flush, since there may be multiple copies of
2219 // stderr and stdout in the file system, all with different buffers
2220 // but writing to the same device.
2221 fflush(stderr);
2222#endif
2223 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002224 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002225
Douglas Gregorb10daed2010-10-11 16:52:23 +00002226 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002227}
2228CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2229 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002230 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002231 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002232 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002233 unsigned num_unsaved_files,
2234 unsigned options) {
2235 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002236 num_command_line_args, unsaved_files,
2237 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002238 llvm::CrashRecoveryContext CRC;
2239
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002240 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002241 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2242 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2243 fprintf(stderr, " 'command_line_args' : [");
2244 for (int i = 0; i != num_command_line_args; ++i) {
2245 if (i)
2246 fprintf(stderr, ", ");
2247 fprintf(stderr, "'%s'", command_line_args[i]);
2248 }
2249 fprintf(stderr, "],\n");
2250 fprintf(stderr, " 'unsaved_files' : [");
2251 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2252 if (i)
2253 fprintf(stderr, ", ");
2254 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2255 unsaved_files[i].Length);
2256 }
2257 fprintf(stderr, "],\n");
2258 fprintf(stderr, " 'options' : %d,\n", options);
2259 fprintf(stderr, "}\n");
2260
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002261 return 0;
2262 }
2263
2264 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002265}
2266
Douglas Gregor19998442010-08-13 15:35:05 +00002267unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2268 return CXSaveTranslationUnit_None;
2269}
2270
2271int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2272 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002273 if (!TU)
2274 return 1;
2275
2276 return static_cast<ASTUnit *>(TU)->Save(FileName);
2277}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002278
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002279void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002280 if (CTUnit) {
2281 // If the translation unit has been marked as unsafe to free, just discard
2282 // it.
2283 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2284 return;
2285
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002286 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002287 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002288}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002289
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002290unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2291 return CXReparse_None;
2292}
2293
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002294struct ReparseTranslationUnitInfo {
2295 CXTranslationUnit TU;
2296 unsigned num_unsaved_files;
2297 struct CXUnsavedFile *unsaved_files;
2298 unsigned options;
2299 int result;
2300};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002301
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002302static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002303 ReparseTranslationUnitInfo *RTUI =
2304 static_cast<ReparseTranslationUnitInfo*>(UserData);
2305 CXTranslationUnit TU = RTUI->TU;
2306 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2307 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2308 unsigned options = RTUI->options;
2309 (void) options;
2310 RTUI->result = 1;
2311
Douglas Gregorabc563f2010-07-19 21:46:24 +00002312 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002313 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002314
2315 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2316 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002317
2318 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2319 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2320 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2321 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002322 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002323 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2324 Buffer));
2325 }
2326
Douglas Gregor593b0c12010-09-23 18:47:53 +00002327 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2328 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002329}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002330
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002331int clang_reparseTranslationUnit(CXTranslationUnit TU,
2332 unsigned num_unsaved_files,
2333 struct CXUnsavedFile *unsaved_files,
2334 unsigned options) {
2335 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2336 options, 0 };
2337 llvm::CrashRecoveryContext CRC;
2338
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002339 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002340 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002341 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2342 return 1;
2343 }
2344
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002345
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002346 return RTUI.result;
2347}
2348
Douglas Gregordf95a132010-08-09 20:45:32 +00002349
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002350CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002351 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002352 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002353
Steve Naroff77accc12009-09-03 18:19:54 +00002354 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002355 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002356}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002357
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002358CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002359 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002360 return Result;
2361}
2362
Ted Kremenekfb480492010-01-13 21:46:36 +00002363} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002364
Ted Kremenekfb480492010-01-13 21:46:36 +00002365//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002366// CXSourceLocation and CXSourceRange Operations.
2367//===----------------------------------------------------------------------===//
2368
Douglas Gregorb9790342010-01-22 21:44:22 +00002369extern "C" {
2370CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002371 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002372 return Result;
2373}
2374
2375unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002376 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2377 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2378 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002379}
2380
2381CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2382 CXFile file,
2383 unsigned line,
2384 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002385 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002386 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002387
Douglas Gregorb9790342010-01-22 21:44:22 +00002388 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2389 SourceLocation SLoc
2390 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002391 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002392 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002393 if (SLoc.isInvalid()) return clang_getNullLocation();
2394
2395 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2396}
2397
2398CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2399 CXFile file,
2400 unsigned offset) {
2401 if (!tu || !file)
2402 return clang_getNullLocation();
2403
2404 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2405 SourceLocation Start
2406 = CXXUnit->getSourceManager().getLocation(
2407 static_cast<const FileEntry *>(file),
2408 1, 1);
2409 if (Start.isInvalid()) return clang_getNullLocation();
2410
2411 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2412
2413 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002414
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002415 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002416}
2417
Douglas Gregor5352ac02010-01-28 00:27:43 +00002418CXSourceRange clang_getNullRange() {
2419 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2420 return Result;
2421}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002422
Douglas Gregor5352ac02010-01-28 00:27:43 +00002423CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2424 if (begin.ptr_data[0] != end.ptr_data[0] ||
2425 begin.ptr_data[1] != end.ptr_data[1])
2426 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427
2428 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002429 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002430 return Result;
2431}
2432
Douglas Gregor46766dc2010-01-26 19:19:08 +00002433void clang_getInstantiationLocation(CXSourceLocation location,
2434 CXFile *file,
2435 unsigned *line,
2436 unsigned *column,
2437 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002438 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2439
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002440 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002441 if (file)
2442 *file = 0;
2443 if (line)
2444 *line = 0;
2445 if (column)
2446 *column = 0;
2447 if (offset)
2448 *offset = 0;
2449 return;
2450 }
2451
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002452 const SourceManager &SM =
2453 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002454 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002455
2456 if (file)
2457 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2458 if (line)
2459 *line = SM.getInstantiationLineNumber(InstLoc);
2460 if (column)
2461 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002462 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002463 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002464}
2465
Douglas Gregora9b06d42010-11-09 06:24:54 +00002466void clang_getSpellingLocation(CXSourceLocation location,
2467 CXFile *file,
2468 unsigned *line,
2469 unsigned *column,
2470 unsigned *offset) {
2471 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2472
2473 if (!location.ptr_data[0] || Loc.isInvalid()) {
2474 if (file)
2475 *file = 0;
2476 if (line)
2477 *line = 0;
2478 if (column)
2479 *column = 0;
2480 if (offset)
2481 *offset = 0;
2482 return;
2483 }
2484
2485 const SourceManager &SM =
2486 *static_cast<const SourceManager*>(location.ptr_data[0]);
2487 SourceLocation SpellLoc = Loc;
2488 if (SpellLoc.isMacroID()) {
2489 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2490 if (SimpleSpellingLoc.isFileID() &&
2491 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2492 SpellLoc = SimpleSpellingLoc;
2493 else
2494 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2495 }
2496
2497 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2498 FileID FID = LocInfo.first;
2499 unsigned FileOffset = LocInfo.second;
2500
2501 if (file)
2502 *file = (void *)SM.getFileEntryForID(FID);
2503 if (line)
2504 *line = SM.getLineNumber(FID, FileOffset);
2505 if (column)
2506 *column = SM.getColumnNumber(FID, FileOffset);
2507 if (offset)
2508 *offset = FileOffset;
2509}
2510
Douglas Gregor1db19de2010-01-19 21:36:55 +00002511CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002512 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002513 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002514 return Result;
2515}
2516
2517CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002518 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002519 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002520 return Result;
2521}
2522
Douglas Gregorb9790342010-01-22 21:44:22 +00002523} // end: extern "C"
2524
Douglas Gregor1db19de2010-01-19 21:36:55 +00002525//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002526// CXFile Operations.
2527//===----------------------------------------------------------------------===//
2528
2529extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002530CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002531 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002532 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002533
Steve Naroff88145032009-10-27 14:35:18 +00002534 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002535 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002536}
2537
2538time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002539 if (!SFile)
2540 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002541
Steve Naroff88145032009-10-27 14:35:18 +00002542 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2543 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002544}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002545
Douglas Gregorb9790342010-01-22 21:44:22 +00002546CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2547 if (!tu)
2548 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002549
Douglas Gregorb9790342010-01-22 21:44:22 +00002550 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002551
Douglas Gregorb9790342010-01-22 21:44:22 +00002552 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002553 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2554 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002555 return const_cast<FileEntry *>(File);
2556}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002557
Ted Kremenekfb480492010-01-13 21:46:36 +00002558} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002559
Ted Kremenekfb480492010-01-13 21:46:36 +00002560//===----------------------------------------------------------------------===//
2561// CXCursor Operations.
2562//===----------------------------------------------------------------------===//
2563
Ted Kremenekfb480492010-01-13 21:46:36 +00002564static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002565 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2566 return getDeclFromExpr(CE->getSubExpr());
2567
Ted Kremenekfb480492010-01-13 21:46:36 +00002568 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2569 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002570 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2571 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002572 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2573 return ME->getMemberDecl();
2574 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2575 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002576 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2577 return PRE->getProperty();
2578
Ted Kremenekfb480492010-01-13 21:46:36 +00002579 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2580 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002581 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2582 if (!CE->isElidable())
2583 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002584 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2585 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002586
Douglas Gregordb1314e2010-10-01 21:11:22 +00002587 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2588 return PE->getProtocol();
2589
Ted Kremenekfb480492010-01-13 21:46:36 +00002590 return 0;
2591}
2592
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002593static SourceLocation getLocationFromExpr(Expr *E) {
2594 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2595 return /*FIXME:*/Msg->getLeftLoc();
2596 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2597 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002598 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2599 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002600 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2601 return Member->getMemberLoc();
2602 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2603 return Ivar->getLocation();
2604 return E->getLocStart();
2605}
2606
Ted Kremenekfb480492010-01-13 21:46:36 +00002607extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002608
2609unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002610 CXCursorVisitor visitor,
2611 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002612 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002613
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002614 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2615 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002616 return CursorVis.VisitChildren(parent);
2617}
2618
David Chisnall3387c652010-11-03 14:12:26 +00002619#ifndef __has_feature
2620#define __has_feature(x) 0
2621#endif
2622#if __has_feature(blocks)
2623typedef enum CXChildVisitResult
2624 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2625
2626static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2627 CXClientData client_data) {
2628 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2629 return block(cursor, parent);
2630}
2631#else
2632// If we are compiled with a compiler that doesn't have native blocks support,
2633// define and call the block manually, so the
2634typedef struct _CXChildVisitResult
2635{
2636 void *isa;
2637 int flags;
2638 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002639 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2640 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002641} *CXCursorVisitorBlock;
2642
2643static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2644 CXClientData client_data) {
2645 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2646 return block->invoke(block, cursor, parent);
2647}
2648#endif
2649
2650
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002651unsigned clang_visitChildrenWithBlock(CXCursor parent,
2652 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002653 return clang_visitChildren(parent, visitWithBlock, block);
2654}
2655
Douglas Gregor78205d42010-01-20 21:45:58 +00002656static CXString getDeclSpelling(Decl *D) {
2657 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2658 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002659 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002660
Douglas Gregor78205d42010-01-20 21:45:58 +00002661 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002662 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002663
Douglas Gregor78205d42010-01-20 21:45:58 +00002664 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2665 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2666 // and returns different names. NamedDecl returns the class name and
2667 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002668 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002669
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002670 if (isa<UsingDirectiveDecl>(D))
2671 return createCXString("");
2672
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002673 llvm::SmallString<1024> S;
2674 llvm::raw_svector_ostream os(S);
2675 ND->printName(os);
2676
2677 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002678}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002679
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002680CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002681 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002682 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002683
Steve Narofff334b4e2009-09-02 18:26:48 +00002684 if (clang_isReference(C.kind)) {
2685 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002686 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002687 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002688 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002689 }
2690 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002691 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002692 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002693 }
2694 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002695 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002696 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002697 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002698 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002699 case CXCursor_CXXBaseSpecifier: {
2700 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2701 return createCXString(B->getType().getAsString());
2702 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002703 case CXCursor_TypeRef: {
2704 TypeDecl *Type = getCursorTypeRef(C).first;
2705 assert(Type && "Missing type decl");
2706
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002707 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2708 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002709 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002710 case CXCursor_TemplateRef: {
2711 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002712 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002713
2714 return createCXString(Template->getNameAsString());
2715 }
Douglas Gregor69319002010-08-31 23:48:11 +00002716
2717 case CXCursor_NamespaceRef: {
2718 NamedDecl *NS = getCursorNamespaceRef(C).first;
2719 assert(NS && "Missing namespace decl");
2720
2721 return createCXString(NS->getNameAsString());
2722 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002723
Douglas Gregora67e03f2010-09-09 21:42:20 +00002724 case CXCursor_MemberRef: {
2725 FieldDecl *Field = getCursorMemberRef(C).first;
2726 assert(Field && "Missing member decl");
2727
2728 return createCXString(Field->getNameAsString());
2729 }
2730
Douglas Gregor36897b02010-09-10 00:22:18 +00002731 case CXCursor_LabelRef: {
2732 LabelStmt *Label = getCursorLabelRef(C).first;
2733 assert(Label && "Missing label");
2734
2735 return createCXString(Label->getID()->getName());
2736 }
2737
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002738 case CXCursor_OverloadedDeclRef: {
2739 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2740 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2741 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2742 return createCXString(ND->getNameAsString());
2743 return createCXString("");
2744 }
2745 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2746 return createCXString(E->getName().getAsString());
2747 OverloadedTemplateStorage *Ovl
2748 = Storage.get<OverloadedTemplateStorage*>();
2749 if (Ovl->size() == 0)
2750 return createCXString("");
2751 return createCXString((*Ovl->begin())->getNameAsString());
2752 }
2753
Daniel Dunbaracca7252009-11-30 20:42:49 +00002754 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002755 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002756 }
2757 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002758
2759 if (clang_isExpression(C.kind)) {
2760 Decl *D = getDeclFromExpr(getCursorExpr(C));
2761 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002762 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002763 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002764 }
2765
Douglas Gregor36897b02010-09-10 00:22:18 +00002766 if (clang_isStatement(C.kind)) {
2767 Stmt *S = getCursorStmt(C);
2768 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2769 return createCXString(Label->getID()->getName());
2770
2771 return createCXString("");
2772 }
2773
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002774 if (C.kind == CXCursor_MacroInstantiation)
2775 return createCXString(getCursorMacroInstantiation(C)->getName()
2776 ->getNameStart());
2777
Douglas Gregor572feb22010-03-18 18:04:21 +00002778 if (C.kind == CXCursor_MacroDefinition)
2779 return createCXString(getCursorMacroDefinition(C)->getName()
2780 ->getNameStart());
2781
Douglas Gregorecdcb882010-10-20 22:00:55 +00002782 if (C.kind == CXCursor_InclusionDirective)
2783 return createCXString(getCursorInclusionDirective(C)->getFileName());
2784
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002785 if (clang_isDeclaration(C.kind))
2786 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002787
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002788 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002789}
2790
Douglas Gregor358559d2010-10-02 22:49:11 +00002791CXString clang_getCursorDisplayName(CXCursor C) {
2792 if (!clang_isDeclaration(C.kind))
2793 return clang_getCursorSpelling(C);
2794
2795 Decl *D = getCursorDecl(C);
2796 if (!D)
2797 return createCXString("");
2798
2799 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2800 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2801 D = FunTmpl->getTemplatedDecl();
2802
2803 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2804 llvm::SmallString<64> Str;
2805 llvm::raw_svector_ostream OS(Str);
2806 OS << Function->getNameAsString();
2807 if (Function->getPrimaryTemplate())
2808 OS << "<>";
2809 OS << "(";
2810 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2811 if (I)
2812 OS << ", ";
2813 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2814 }
2815
2816 if (Function->isVariadic()) {
2817 if (Function->getNumParams())
2818 OS << ", ";
2819 OS << "...";
2820 }
2821 OS << ")";
2822 return createCXString(OS.str());
2823 }
2824
2825 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2826 llvm::SmallString<64> Str;
2827 llvm::raw_svector_ostream OS(Str);
2828 OS << ClassTemplate->getNameAsString();
2829 OS << "<";
2830 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2831 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2832 if (I)
2833 OS << ", ";
2834
2835 NamedDecl *Param = Params->getParam(I);
2836 if (Param->getIdentifier()) {
2837 OS << Param->getIdentifier()->getName();
2838 continue;
2839 }
2840
2841 // There is no parameter name, which makes this tricky. Try to come up
2842 // with something useful that isn't too long.
2843 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2844 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2845 else if (NonTypeTemplateParmDecl *NTTP
2846 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2847 OS << NTTP->getType().getAsString(Policy);
2848 else
2849 OS << "template<...> class";
2850 }
2851
2852 OS << ">";
2853 return createCXString(OS.str());
2854 }
2855
2856 if (ClassTemplateSpecializationDecl *ClassSpec
2857 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2858 // If the type was explicitly written, use that.
2859 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2860 return createCXString(TSInfo->getType().getAsString(Policy));
2861
2862 llvm::SmallString<64> Str;
2863 llvm::raw_svector_ostream OS(Str);
2864 OS << ClassSpec->getNameAsString();
2865 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002866 ClassSpec->getTemplateArgs().data(),
2867 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002868 Policy);
2869 return createCXString(OS.str());
2870 }
2871
2872 return clang_getCursorSpelling(C);
2873}
2874
Ted Kremeneke68fff62010-02-17 00:41:32 +00002875CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002876 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002877 case CXCursor_FunctionDecl:
2878 return createCXString("FunctionDecl");
2879 case CXCursor_TypedefDecl:
2880 return createCXString("TypedefDecl");
2881 case CXCursor_EnumDecl:
2882 return createCXString("EnumDecl");
2883 case CXCursor_EnumConstantDecl:
2884 return createCXString("EnumConstantDecl");
2885 case CXCursor_StructDecl:
2886 return createCXString("StructDecl");
2887 case CXCursor_UnionDecl:
2888 return createCXString("UnionDecl");
2889 case CXCursor_ClassDecl:
2890 return createCXString("ClassDecl");
2891 case CXCursor_FieldDecl:
2892 return createCXString("FieldDecl");
2893 case CXCursor_VarDecl:
2894 return createCXString("VarDecl");
2895 case CXCursor_ParmDecl:
2896 return createCXString("ParmDecl");
2897 case CXCursor_ObjCInterfaceDecl:
2898 return createCXString("ObjCInterfaceDecl");
2899 case CXCursor_ObjCCategoryDecl:
2900 return createCXString("ObjCCategoryDecl");
2901 case CXCursor_ObjCProtocolDecl:
2902 return createCXString("ObjCProtocolDecl");
2903 case CXCursor_ObjCPropertyDecl:
2904 return createCXString("ObjCPropertyDecl");
2905 case CXCursor_ObjCIvarDecl:
2906 return createCXString("ObjCIvarDecl");
2907 case CXCursor_ObjCInstanceMethodDecl:
2908 return createCXString("ObjCInstanceMethodDecl");
2909 case CXCursor_ObjCClassMethodDecl:
2910 return createCXString("ObjCClassMethodDecl");
2911 case CXCursor_ObjCImplementationDecl:
2912 return createCXString("ObjCImplementationDecl");
2913 case CXCursor_ObjCCategoryImplDecl:
2914 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002915 case CXCursor_CXXMethod:
2916 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002917 case CXCursor_UnexposedDecl:
2918 return createCXString("UnexposedDecl");
2919 case CXCursor_ObjCSuperClassRef:
2920 return createCXString("ObjCSuperClassRef");
2921 case CXCursor_ObjCProtocolRef:
2922 return createCXString("ObjCProtocolRef");
2923 case CXCursor_ObjCClassRef:
2924 return createCXString("ObjCClassRef");
2925 case CXCursor_TypeRef:
2926 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002927 case CXCursor_TemplateRef:
2928 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002929 case CXCursor_NamespaceRef:
2930 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002931 case CXCursor_MemberRef:
2932 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002933 case CXCursor_LabelRef:
2934 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002935 case CXCursor_OverloadedDeclRef:
2936 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002937 case CXCursor_UnexposedExpr:
2938 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002939 case CXCursor_BlockExpr:
2940 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002941 case CXCursor_DeclRefExpr:
2942 return createCXString("DeclRefExpr");
2943 case CXCursor_MemberRefExpr:
2944 return createCXString("MemberRefExpr");
2945 case CXCursor_CallExpr:
2946 return createCXString("CallExpr");
2947 case CXCursor_ObjCMessageExpr:
2948 return createCXString("ObjCMessageExpr");
2949 case CXCursor_UnexposedStmt:
2950 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002951 case CXCursor_LabelStmt:
2952 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002953 case CXCursor_InvalidFile:
2954 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002955 case CXCursor_InvalidCode:
2956 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002957 case CXCursor_NoDeclFound:
2958 return createCXString("NoDeclFound");
2959 case CXCursor_NotImplemented:
2960 return createCXString("NotImplemented");
2961 case CXCursor_TranslationUnit:
2962 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002963 case CXCursor_UnexposedAttr:
2964 return createCXString("UnexposedAttr");
2965 case CXCursor_IBActionAttr:
2966 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002967 case CXCursor_IBOutletAttr:
2968 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002969 case CXCursor_IBOutletCollectionAttr:
2970 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002971 case CXCursor_PreprocessingDirective:
2972 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002973 case CXCursor_MacroDefinition:
2974 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002975 case CXCursor_MacroInstantiation:
2976 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002977 case CXCursor_InclusionDirective:
2978 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002979 case CXCursor_Namespace:
2980 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002981 case CXCursor_LinkageSpec:
2982 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002983 case CXCursor_CXXBaseSpecifier:
2984 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002985 case CXCursor_Constructor:
2986 return createCXString("CXXConstructor");
2987 case CXCursor_Destructor:
2988 return createCXString("CXXDestructor");
2989 case CXCursor_ConversionFunction:
2990 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002991 case CXCursor_TemplateTypeParameter:
2992 return createCXString("TemplateTypeParameter");
2993 case CXCursor_NonTypeTemplateParameter:
2994 return createCXString("NonTypeTemplateParameter");
2995 case CXCursor_TemplateTemplateParameter:
2996 return createCXString("TemplateTemplateParameter");
2997 case CXCursor_FunctionTemplate:
2998 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002999 case CXCursor_ClassTemplate:
3000 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003001 case CXCursor_ClassTemplatePartialSpecialization:
3002 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003003 case CXCursor_NamespaceAlias:
3004 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003005 case CXCursor_UsingDirective:
3006 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003007 case CXCursor_UsingDeclaration:
3008 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003009 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003010
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003011 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003012 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003013}
Steve Naroff89922f82009-08-31 00:59:03 +00003014
Ted Kremeneke68fff62010-02-17 00:41:32 +00003015enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3016 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003017 CXClientData client_data) {
3018 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003019
3020 // If our current best cursor is the construction of a temporary object,
3021 // don't replace that cursor with a type reference, because we want
3022 // clang_getCursor() to point at the constructor.
3023 if (clang_isExpression(BestCursor->kind) &&
3024 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3025 cursor.kind == CXCursor_TypeRef)
3026 return CXChildVisit_Recurse;
3027
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003028 *BestCursor = cursor;
3029 return CXChildVisit_Recurse;
3030}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003031
Douglas Gregorb9790342010-01-22 21:44:22 +00003032CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3033 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003034 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003035
Douglas Gregorb9790342010-01-22 21:44:22 +00003036 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003037 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3038
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003039 // Translate the given source location to make it point at the beginning of
3040 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003041 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003042
3043 // Guard against an invalid SourceLocation, or we may assert in one
3044 // of the following calls.
3045 if (SLoc.isInvalid())
3046 return clang_getNullCursor();
3047
Douglas Gregor40749ee2010-11-03 00:35:38 +00003048 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003049 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3050 CXXUnit->getASTContext().getLangOptions());
3051
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003052 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3053 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003054 // FIXME: Would be great to have a "hint" cursor, then walk from that
3055 // hint cursor upward until we find a cursor whose source range encloses
3056 // the region of interest, rather than starting from the translation unit.
3057 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003058 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003059 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003060 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003061 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003062
3063 if (Logging) {
3064 CXFile SearchFile;
3065 unsigned SearchLine, SearchColumn;
3066 CXFile ResultFile;
3067 unsigned ResultLine, ResultColumn;
3068 CXString SearchFileName, ResultFileName, KindSpelling;
3069 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3070
3071 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3072 0);
3073 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3074 &ResultColumn, 0);
3075 SearchFileName = clang_getFileName(SearchFile);
3076 ResultFileName = clang_getFileName(ResultFile);
3077 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3078 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3079 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3080 clang_getCString(KindSpelling),
3081 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3082 clang_disposeString(SearchFileName);
3083 clang_disposeString(ResultFileName);
3084 clang_disposeString(KindSpelling);
3085 }
3086
Ted Kremeneke68fff62010-02-17 00:41:32 +00003087 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003088}
3089
Ted Kremenek73885552009-11-17 19:28:59 +00003090CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003091 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003092}
3093
3094unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003095 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003096}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003097
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003098unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003099 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3100}
3101
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003102unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003103 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3104}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003105
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003106unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003107 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3108}
3109
Douglas Gregor97b98722010-01-19 23:20:36 +00003110unsigned clang_isExpression(enum CXCursorKind K) {
3111 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3112}
3113
3114unsigned clang_isStatement(enum CXCursorKind K) {
3115 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3116}
3117
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003118unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3119 return K == CXCursor_TranslationUnit;
3120}
3121
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003122unsigned clang_isPreprocessing(enum CXCursorKind K) {
3123 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3124}
3125
Ted Kremenekad6eff62010-03-08 21:17:29 +00003126unsigned clang_isUnexposed(enum CXCursorKind K) {
3127 switch (K) {
3128 case CXCursor_UnexposedDecl:
3129 case CXCursor_UnexposedExpr:
3130 case CXCursor_UnexposedStmt:
3131 case CXCursor_UnexposedAttr:
3132 return true;
3133 default:
3134 return false;
3135 }
3136}
3137
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003138CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003139 return C.kind;
3140}
3141
Douglas Gregor98258af2010-01-18 22:46:11 +00003142CXSourceLocation clang_getCursorLocation(CXCursor C) {
3143 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003144 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003145 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003146 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3147 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003148 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003149 }
3150
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003151 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003152 std::pair<ObjCProtocolDecl *, SourceLocation> P
3153 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003154 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003155 }
3156
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003157 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003158 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3159 = getCursorObjCClassRef(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 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003162
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003163 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003164 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003165 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003166 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003167
3168 case CXCursor_TemplateRef: {
3169 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3170 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3171 }
3172
Douglas Gregor69319002010-08-31 23:48:11 +00003173 case CXCursor_NamespaceRef: {
3174 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3175 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3176 }
3177
Douglas Gregora67e03f2010-09-09 21:42:20 +00003178 case CXCursor_MemberRef: {
3179 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3180 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3181 }
3182
Ted Kremenek3064ef92010-08-27 21:34:58 +00003183 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003184 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3185 if (!BaseSpec)
3186 return clang_getNullLocation();
3187
3188 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3189 return cxloc::translateSourceLocation(getCursorContext(C),
3190 TSInfo->getTypeLoc().getBeginLoc());
3191
3192 return cxloc::translateSourceLocation(getCursorContext(C),
3193 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003194 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003195
Douglas Gregor36897b02010-09-10 00:22:18 +00003196 case CXCursor_LabelRef: {
3197 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3198 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3199 }
3200
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003201 case CXCursor_OverloadedDeclRef:
3202 return cxloc::translateSourceLocation(getCursorContext(C),
3203 getCursorOverloadedDeclRef(C).second);
3204
Douglas Gregorf46034a2010-01-18 23:41:10 +00003205 default:
3206 // FIXME: Need a way to enumerate all non-reference cases.
3207 llvm_unreachable("Missed a reference kind");
3208 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003209 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003210
3211 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003212 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003213 getLocationFromExpr(getCursorExpr(C)));
3214
Douglas Gregor36897b02010-09-10 00:22:18 +00003215 if (clang_isStatement(C.kind))
3216 return cxloc::translateSourceLocation(getCursorContext(C),
3217 getCursorStmt(C)->getLocStart());
3218
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003219 if (C.kind == CXCursor_PreprocessingDirective) {
3220 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3221 return cxloc::translateSourceLocation(getCursorContext(C), L);
3222 }
Douglas Gregor48072312010-03-18 15:23:44 +00003223
3224 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003225 SourceLocation L
3226 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003227 return cxloc::translateSourceLocation(getCursorContext(C), L);
3228 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003229
3230 if (C.kind == CXCursor_MacroDefinition) {
3231 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3232 return cxloc::translateSourceLocation(getCursorContext(C), L);
3233 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003234
3235 if (C.kind == CXCursor_InclusionDirective) {
3236 SourceLocation L
3237 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3238 return cxloc::translateSourceLocation(getCursorContext(C), L);
3239 }
3240
Ted Kremenek9a700d22010-05-12 06:16:13 +00003241 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003242 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003243
Douglas Gregorf46034a2010-01-18 23:41:10 +00003244 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003245 SourceLocation Loc = D->getLocation();
3246 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3247 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003248 // FIXME: Multiple variables declared in a single declaration
3249 // currently lack the information needed to correctly determine their
3250 // ranges when accounting for the type-specifier. We use context
3251 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3252 // and if so, whether it is the first decl.
3253 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3254 if (!cxcursor::isFirstInDeclGroup(C))
3255 Loc = VD->getLocation();
3256 }
3257
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003258 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003259}
Douglas Gregora7bde202010-01-19 00:34:46 +00003260
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003261} // end extern "C"
3262
3263static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003264 if (clang_isReference(C.kind)) {
3265 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003266 case CXCursor_ObjCSuperClassRef:
3267 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003268
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003269 case CXCursor_ObjCProtocolRef:
3270 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003271
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003272 case CXCursor_ObjCClassRef:
3273 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003274
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003275 case CXCursor_TypeRef:
3276 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003277
3278 case CXCursor_TemplateRef:
3279 return getCursorTemplateRef(C).second;
3280
Douglas Gregor69319002010-08-31 23:48:11 +00003281 case CXCursor_NamespaceRef:
3282 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003283
3284 case CXCursor_MemberRef:
3285 return getCursorMemberRef(C).second;
3286
Ted Kremenek3064ef92010-08-27 21:34:58 +00003287 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003288 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003289
Douglas Gregor36897b02010-09-10 00:22:18 +00003290 case CXCursor_LabelRef:
3291 return getCursorLabelRef(C).second;
3292
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003293 case CXCursor_OverloadedDeclRef:
3294 return getCursorOverloadedDeclRef(C).second;
3295
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003296 default:
3297 // FIXME: Need a way to enumerate all non-reference cases.
3298 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003299 }
3300 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003301
3302 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003303 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003304
3305 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003306 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003307
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003308 if (C.kind == CXCursor_PreprocessingDirective)
3309 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003310
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003311 if (C.kind == CXCursor_MacroInstantiation)
3312 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003313
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003314 if (C.kind == CXCursor_MacroDefinition)
3315 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003316
3317 if (C.kind == CXCursor_InclusionDirective)
3318 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3319
Ted Kremenek007a7c92010-11-01 23:26:51 +00003320 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3321 Decl *D = cxcursor::getCursorDecl(C);
3322 SourceRange R = D->getSourceRange();
3323 // FIXME: Multiple variables declared in a single declaration
3324 // currently lack the information needed to correctly determine their
3325 // ranges when accounting for the type-specifier. We use context
3326 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3327 // and if so, whether it is the first decl.
3328 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3329 if (!cxcursor::isFirstInDeclGroup(C))
3330 R.setBegin(VD->getLocation());
3331 }
3332 return R;
3333 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003334 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003335
3336extern "C" {
3337
3338CXSourceRange clang_getCursorExtent(CXCursor C) {
3339 SourceRange R = getRawCursorExtent(C);
3340 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003341 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003342
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003343 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003344}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003345
3346CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003347 if (clang_isInvalid(C.kind))
3348 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003349
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003350 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003351 if (clang_isDeclaration(C.kind)) {
3352 Decl *D = getCursorDecl(C);
3353 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3354 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3355 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3356 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3357 if (ObjCForwardProtocolDecl *Protocols
3358 = dyn_cast<ObjCForwardProtocolDecl>(D))
3359 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3360
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003361 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003362 }
3363
Douglas Gregor97b98722010-01-19 23:20:36 +00003364 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003365 Expr *E = getCursorExpr(C);
3366 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003367 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003368 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003369
3370 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3371 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3372
Douglas Gregor97b98722010-01-19 23:20:36 +00003373 return clang_getNullCursor();
3374 }
3375
Douglas Gregor36897b02010-09-10 00:22:18 +00003376 if (clang_isStatement(C.kind)) {
3377 Stmt *S = getCursorStmt(C);
3378 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3379 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3380 getCursorASTUnit(C));
3381
3382 return clang_getNullCursor();
3383 }
3384
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003385 if (C.kind == CXCursor_MacroInstantiation) {
3386 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3387 return MakeMacroDefinitionCursor(Def, CXXUnit);
3388 }
3389
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003390 if (!clang_isReference(C.kind))
3391 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003392
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003393 switch (C.kind) {
3394 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003395 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003396
3397 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003398 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003399
3400 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003401 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003402
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003403 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003404 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003405
3406 case CXCursor_TemplateRef:
3407 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3408
Douglas Gregor69319002010-08-31 23:48:11 +00003409 case CXCursor_NamespaceRef:
3410 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3411
Douglas Gregora67e03f2010-09-09 21:42:20 +00003412 case CXCursor_MemberRef:
3413 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3414
Ted Kremenek3064ef92010-08-27 21:34:58 +00003415 case CXCursor_CXXBaseSpecifier: {
3416 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3417 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3418 CXXUnit));
3419 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003420
Douglas Gregor36897b02010-09-10 00:22:18 +00003421 case CXCursor_LabelRef:
3422 // FIXME: We end up faking the "parent" declaration here because we
3423 // don't want to make CXCursor larger.
3424 return MakeCXCursor(getCursorLabelRef(C).first,
3425 CXXUnit->getASTContext().getTranslationUnitDecl(),
3426 CXXUnit);
3427
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003428 case CXCursor_OverloadedDeclRef:
3429 return C;
3430
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003431 default:
3432 // We would prefer to enumerate all non-reference cursor kinds here.
3433 llvm_unreachable("Unhandled reference cursor kind");
3434 break;
3435 }
3436 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003437
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003438 return clang_getNullCursor();
3439}
3440
Douglas Gregorb6998662010-01-19 19:34:47 +00003441CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003442 if (clang_isInvalid(C.kind))
3443 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003444
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003445 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003446
Douglas Gregorb6998662010-01-19 19:34:47 +00003447 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003448 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003449 C = clang_getCursorReferenced(C);
3450 WasReference = true;
3451 }
3452
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003453 if (C.kind == CXCursor_MacroInstantiation)
3454 return clang_getCursorReferenced(C);
3455
Douglas Gregorb6998662010-01-19 19:34:47 +00003456 if (!clang_isDeclaration(C.kind))
3457 return clang_getNullCursor();
3458
3459 Decl *D = getCursorDecl(C);
3460 if (!D)
3461 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003462
Douglas Gregorb6998662010-01-19 19:34:47 +00003463 switch (D->getKind()) {
3464 // Declaration kinds that don't really separate the notions of
3465 // declaration and definition.
3466 case Decl::Namespace:
3467 case Decl::Typedef:
3468 case Decl::TemplateTypeParm:
3469 case Decl::EnumConstant:
3470 case Decl::Field:
3471 case Decl::ObjCIvar:
3472 case Decl::ObjCAtDefsField:
3473 case Decl::ImplicitParam:
3474 case Decl::ParmVar:
3475 case Decl::NonTypeTemplateParm:
3476 case Decl::TemplateTemplateParm:
3477 case Decl::ObjCCategoryImpl:
3478 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003479 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003480 case Decl::LinkageSpec:
3481 case Decl::ObjCPropertyImpl:
3482 case Decl::FileScopeAsm:
3483 case Decl::StaticAssert:
3484 case Decl::Block:
3485 return C;
3486
3487 // Declaration kinds that don't make any sense here, but are
3488 // nonetheless harmless.
3489 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003490 break;
3491
3492 // Declaration kinds for which the definition is not resolvable.
3493 case Decl::UnresolvedUsingTypename:
3494 case Decl::UnresolvedUsingValue:
3495 break;
3496
3497 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003498 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3499 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003500
3501 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003502 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003503
3504 case Decl::Enum:
3505 case Decl::Record:
3506 case Decl::CXXRecord:
3507 case Decl::ClassTemplateSpecialization:
3508 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003509 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003510 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003511 return clang_getNullCursor();
3512
3513 case Decl::Function:
3514 case Decl::CXXMethod:
3515 case Decl::CXXConstructor:
3516 case Decl::CXXDestructor:
3517 case Decl::CXXConversion: {
3518 const FunctionDecl *Def = 0;
3519 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003520 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003521 return clang_getNullCursor();
3522 }
3523
3524 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003525 // Ask the variable if it has a definition.
3526 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3527 return MakeCXCursor(Def, CXXUnit);
3528 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003529 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003530
Douglas Gregorb6998662010-01-19 19:34:47 +00003531 case Decl::FunctionTemplate: {
3532 const FunctionDecl *Def = 0;
3533 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003534 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003535 return clang_getNullCursor();
3536 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003537
Douglas Gregorb6998662010-01-19 19:34:47 +00003538 case Decl::ClassTemplate: {
3539 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003540 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003541 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003542 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003543 return clang_getNullCursor();
3544 }
3545
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003546 case Decl::Using:
3547 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3548 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003549
3550 case Decl::UsingShadow:
3551 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003552 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003553 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003554
3555 case Decl::ObjCMethod: {
3556 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3557 if (Method->isThisDeclarationADefinition())
3558 return C;
3559
3560 // Dig out the method definition in the associated
3561 // @implementation, if we have it.
3562 // FIXME: The ASTs should make finding the definition easier.
3563 if (ObjCInterfaceDecl *Class
3564 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3565 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3566 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3567 Method->isInstanceMethod()))
3568 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003569 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003570
3571 return clang_getNullCursor();
3572 }
3573
3574 case Decl::ObjCCategory:
3575 if (ObjCCategoryImplDecl *Impl
3576 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003577 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 return clang_getNullCursor();
3579
3580 case Decl::ObjCProtocol:
3581 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3582 return C;
3583 return clang_getNullCursor();
3584
3585 case Decl::ObjCInterface:
3586 // There are two notions of a "definition" for an Objective-C
3587 // class: the interface and its implementation. When we resolved a
3588 // reference to an Objective-C class, produce the @interface as
3589 // the definition; when we were provided with the interface,
3590 // produce the @implementation as the definition.
3591 if (WasReference) {
3592 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3593 return C;
3594 } else if (ObjCImplementationDecl *Impl
3595 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003596 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003597 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003598
Douglas Gregorb6998662010-01-19 19:34:47 +00003599 case Decl::ObjCProperty:
3600 // FIXME: We don't really know where to find the
3601 // ObjCPropertyImplDecls that implement this property.
3602 return clang_getNullCursor();
3603
3604 case Decl::ObjCCompatibleAlias:
3605 if (ObjCInterfaceDecl *Class
3606 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3607 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003608 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003609
Douglas Gregorb6998662010-01-19 19:34:47 +00003610 return clang_getNullCursor();
3611
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003612 case Decl::ObjCForwardProtocol:
3613 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3614 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003615
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003616 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003617 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003618 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003619
3620 case Decl::Friend:
3621 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003622 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003623 return clang_getNullCursor();
3624
3625 case Decl::FriendTemplate:
3626 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003627 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003628 return clang_getNullCursor();
3629 }
3630
3631 return clang_getNullCursor();
3632}
3633
3634unsigned clang_isCursorDefinition(CXCursor C) {
3635 if (!clang_isDeclaration(C.kind))
3636 return 0;
3637
3638 return clang_getCursorDefinition(C) == C;
3639}
3640
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003641unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003642 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003643 return 0;
3644
3645 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3646 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3647 return E->getNumDecls();
3648
3649 if (OverloadedTemplateStorage *S
3650 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3651 return S->size();
3652
3653 Decl *D = Storage.get<Decl*>();
3654 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003655 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003656 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3657 return Classes->size();
3658 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3659 return Protocols->protocol_size();
3660
3661 return 0;
3662}
3663
3664CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003665 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003666 return clang_getNullCursor();
3667
3668 if (index >= clang_getNumOverloadedDecls(cursor))
3669 return clang_getNullCursor();
3670
3671 ASTUnit *Unit = getCursorASTUnit(cursor);
3672 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3673 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3674 return MakeCXCursor(E->decls_begin()[index], Unit);
3675
3676 if (OverloadedTemplateStorage *S
3677 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3678 return MakeCXCursor(S->begin()[index], Unit);
3679
3680 Decl *D = Storage.get<Decl*>();
3681 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3682 // FIXME: This is, unfortunately, linear time.
3683 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3684 std::advance(Pos, index);
3685 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3686 }
3687
3688 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3689 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3690
3691 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3692 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3693
3694 return clang_getNullCursor();
3695}
3696
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003697void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003698 const char **startBuf,
3699 const char **endBuf,
3700 unsigned *startLine,
3701 unsigned *startColumn,
3702 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003703 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003704 assert(getCursorDecl(C) && "CXCursor has null decl");
3705 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003706 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3707 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003708
Steve Naroff4ade6d62009-09-23 17:52:52 +00003709 SourceManager &SM = FD->getASTContext().getSourceManager();
3710 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3711 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3712 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3713 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3714 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3715 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3716}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003717
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003718void clang_enableStackTraces(void) {
3719 llvm::sys::PrintStackTraceOnErrorSignal();
3720}
3721
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003722void clang_executeOnThread(void (*fn)(void*), void *user_data,
3723 unsigned stack_size) {
3724 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3725}
3726
Ted Kremenekfb480492010-01-13 21:46:36 +00003727} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003728
Ted Kremenekfb480492010-01-13 21:46:36 +00003729//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003730// Token-based Operations.
3731//===----------------------------------------------------------------------===//
3732
3733/* CXToken layout:
3734 * int_data[0]: a CXTokenKind
3735 * int_data[1]: starting token location
3736 * int_data[2]: token length
3737 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003738 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003739 * otherwise unused.
3740 */
3741extern "C" {
3742
3743CXTokenKind clang_getTokenKind(CXToken CXTok) {
3744 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3745}
3746
3747CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3748 switch (clang_getTokenKind(CXTok)) {
3749 case CXToken_Identifier:
3750 case CXToken_Keyword:
3751 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003752 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3753 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003754
3755 case CXToken_Literal: {
3756 // We have stashed the starting pointer in the ptr_data field. Use it.
3757 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003758 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003759 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003760
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003761 case CXToken_Punctuation:
3762 case CXToken_Comment:
3763 break;
3764 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003765
3766 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003767 // deconstructing the source location.
3768 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3769 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003770 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003771
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003772 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3773 std::pair<FileID, unsigned> LocInfo
3774 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003775 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003776 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003777 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3778 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003779 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003780
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003781 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003782}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003783
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003784CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3785 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3786 if (!CXXUnit)
3787 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003788
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003789 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3790 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3791}
3792
3793CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3794 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003795 if (!CXXUnit)
3796 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003797
3798 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003799 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3800}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003801
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3803 CXToken **Tokens, unsigned *NumTokens) {
3804 if (Tokens)
3805 *Tokens = 0;
3806 if (NumTokens)
3807 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003808
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003809 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3810 if (!CXXUnit || !Tokens || !NumTokens)
3811 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003812
Douglas Gregorbdf60622010-03-05 21:16:25 +00003813 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3814
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003815 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003816 if (R.isInvalid())
3817 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003818
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003819 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3820 std::pair<FileID, unsigned> BeginLocInfo
3821 = SourceMgr.getDecomposedLoc(R.getBegin());
3822 std::pair<FileID, unsigned> EndLocInfo
3823 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003824
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003825 // Cannot tokenize across files.
3826 if (BeginLocInfo.first != EndLocInfo.first)
3827 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003828
3829 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003830 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003831 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003832 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003833 if (Invalid)
3834 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003836 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3837 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003838 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003839 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003840
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003841 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003842 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003843 llvm::SmallVector<CXToken, 32> CXTokens;
3844 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003845 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003846 do {
3847 // Lex the next token
3848 Lex.LexFromRawLexer(Tok);
3849 if (Tok.is(tok::eof))
3850 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003852 // Initialize the CXToken.
3853 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003854
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855 // - Common fields
3856 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3857 CXTok.int_data[2] = Tok.getLength();
3858 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003860 // - Kind-specific fields
3861 if (Tok.isLiteral()) {
3862 CXTok.int_data[0] = CXToken_Literal;
3863 CXTok.ptr_data = (void *)Tok.getLiteralData();
3864 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003865 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003866 std::pair<FileID, unsigned> LocInfo
3867 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003868 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003869 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003870 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3871 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003872 return;
3873
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003874 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003875 IdentifierInfo *II
3876 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003877
David Chisnall096428b2010-10-13 21:44:48 +00003878 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003879 CXTok.int_data[0] = CXToken_Keyword;
3880 }
3881 else {
3882 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3883 CXToken_Identifier
3884 : CXToken_Keyword;
3885 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003886 CXTok.ptr_data = II;
3887 } else if (Tok.is(tok::comment)) {
3888 CXTok.int_data[0] = CXToken_Comment;
3889 CXTok.ptr_data = 0;
3890 } else {
3891 CXTok.int_data[0] = CXToken_Punctuation;
3892 CXTok.ptr_data = 0;
3893 }
3894 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003895 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003896 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003897
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003898 if (CXTokens.empty())
3899 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003900
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003901 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3902 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3903 *NumTokens = CXTokens.size();
3904}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003905
Ted Kremenek6db61092010-05-05 00:55:15 +00003906void clang_disposeTokens(CXTranslationUnit TU,
3907 CXToken *Tokens, unsigned NumTokens) {
3908 free(Tokens);
3909}
3910
3911} // end: extern "C"
3912
3913//===----------------------------------------------------------------------===//
3914// Token annotation APIs.
3915//===----------------------------------------------------------------------===//
3916
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003917typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003918static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3919 CXCursor parent,
3920 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003921namespace {
3922class AnnotateTokensWorker {
3923 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003924 CXToken *Tokens;
3925 CXCursor *Cursors;
3926 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003927 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003928 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003929 CursorVisitor AnnotateVis;
3930 SourceManager &SrcMgr;
3931
3932 bool MoreTokens() const { return TokIdx < NumTokens; }
3933 unsigned NextToken() const { return TokIdx; }
3934 void AdvanceToken() { ++TokIdx; }
3935 SourceLocation GetTokenLoc(unsigned tokI) {
3936 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3937 }
3938
Ted Kremenek6db61092010-05-05 00:55:15 +00003939public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003940 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003941 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3942 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003943 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003944 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003945 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3946 Decl::MaxPCHLevel, RegionOfInterest),
3947 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003948
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003949 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003950 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003951 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003952 void AnnotateTokens() {
3953 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3954 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003955};
3956}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003957
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003958void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3959 // Walk the AST within the region of interest, annotating tokens
3960 // along the way.
3961 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003962
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003963 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3964 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003965 if (Pos != Annotated.end() &&
3966 (clang_isInvalid(Cursors[I].kind) ||
3967 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003968 Cursors[I] = Pos->second;
3969 }
3970
3971 // Finish up annotating any tokens left.
3972 if (!MoreTokens())
3973 return;
3974
3975 const CXCursor &C = clang_getNullCursor();
3976 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3977 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3978 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003979 }
3980}
3981
Ted Kremenek6db61092010-05-05 00:55:15 +00003982enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003983AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003984 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003985 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003986 if (cursorRange.isInvalid())
3987 return CXChildVisit_Recurse;
3988
Douglas Gregor4419b672010-10-21 06:10:04 +00003989 if (clang_isPreprocessing(cursor.kind)) {
3990 // For macro instantiations, just note where the beginning of the macro
3991 // instantiation occurs.
3992 if (cursor.kind == CXCursor_MacroInstantiation) {
3993 Annotated[Loc.int_data] = cursor;
3994 return CXChildVisit_Recurse;
3995 }
3996
Douglas Gregor4419b672010-10-21 06:10:04 +00003997 // Items in the preprocessing record are kept separate from items in
3998 // declarations, so we keep a separate token index.
3999 unsigned SavedTokIdx = TokIdx;
4000 TokIdx = PreprocessingTokIdx;
4001
4002 // Skip tokens up until we catch up to the beginning of the preprocessing
4003 // entry.
4004 while (MoreTokens()) {
4005 const unsigned I = NextToken();
4006 SourceLocation TokLoc = GetTokenLoc(I);
4007 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4008 case RangeBefore:
4009 AdvanceToken();
4010 continue;
4011 case RangeAfter:
4012 case RangeOverlap:
4013 break;
4014 }
4015 break;
4016 }
4017
4018 // Look at all of the tokens within this range.
4019 while (MoreTokens()) {
4020 const unsigned I = NextToken();
4021 SourceLocation TokLoc = GetTokenLoc(I);
4022 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4023 case RangeBefore:
4024 assert(0 && "Infeasible");
4025 case RangeAfter:
4026 break;
4027 case RangeOverlap:
4028 Cursors[I] = cursor;
4029 AdvanceToken();
4030 continue;
4031 }
4032 break;
4033 }
4034
4035 // Save the preprocessing token index; restore the non-preprocessing
4036 // token index.
4037 PreprocessingTokIdx = TokIdx;
4038 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004039 return CXChildVisit_Recurse;
4040 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004041
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004042 if (cursorRange.isInvalid())
4043 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004044
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004045 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4046
Ted Kremeneka333c662010-05-12 05:29:33 +00004047 // Adjust the annotated range based specific declarations.
4048 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4049 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004050 Decl *D = cxcursor::getCursorDecl(cursor);
4051 // Don't visit synthesized ObjC methods, since they have no syntatic
4052 // representation in the source.
4053 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4054 if (MD->isSynthesized())
4055 return CXChildVisit_Continue;
4056 }
4057 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004058 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4059 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004060 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004061 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004062 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004063 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004064 }
4065 }
4066 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004067
Ted Kremenek3f404602010-08-14 01:14:06 +00004068 // If the location of the cursor occurs within a macro instantiation, record
4069 // the spelling location of the cursor in our annotation map. We can then
4070 // paper over the token labelings during a post-processing step to try and
4071 // get cursor mappings for tokens that are the *arguments* of a macro
4072 // instantiation.
4073 if (L.isMacroID()) {
4074 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4075 // Only invalidate the old annotation if it isn't part of a preprocessing
4076 // directive. Here we assume that the default construction of CXCursor
4077 // results in CXCursor.kind being an initialized value (i.e., 0). If
4078 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004079
Ted Kremenek3f404602010-08-14 01:14:06 +00004080 CXCursor &oldC = Annotated[rawEncoding];
4081 if (!clang_isPreprocessing(oldC.kind))
4082 oldC = cursor;
4083 }
4084
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004085 const enum CXCursorKind K = clang_getCursorKind(parent);
4086 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004087 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4088 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004089
4090 while (MoreTokens()) {
4091 const unsigned I = NextToken();
4092 SourceLocation TokLoc = GetTokenLoc(I);
4093 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4094 case RangeBefore:
4095 Cursors[I] = updateC;
4096 AdvanceToken();
4097 continue;
4098 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004099 case RangeOverlap:
4100 break;
4101 }
4102 break;
4103 }
4104
4105 // Visit children to get their cursor information.
4106 const unsigned BeforeChildren = NextToken();
4107 VisitChildren(cursor);
4108 const unsigned AfterChildren = NextToken();
4109
4110 // Adjust 'Last' to the last token within the extent of the cursor.
4111 while (MoreTokens()) {
4112 const unsigned I = NextToken();
4113 SourceLocation TokLoc = GetTokenLoc(I);
4114 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4115 case RangeBefore:
4116 assert(0 && "Infeasible");
4117 case RangeAfter:
4118 break;
4119 case RangeOverlap:
4120 Cursors[I] = updateC;
4121 AdvanceToken();
4122 continue;
4123 }
4124 break;
4125 }
4126 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004127
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004128 // Scan the tokens that are at the beginning of the cursor, but are not
4129 // capture by the child cursors.
4130
4131 // For AST elements within macros, rely on a post-annotate pass to
4132 // to correctly annotate the tokens with cursors. Otherwise we can
4133 // get confusing results of having tokens that map to cursors that really
4134 // are expanded by an instantiation.
4135 if (L.isMacroID())
4136 cursor = clang_getNullCursor();
4137
4138 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4139 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4140 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004141
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004142 Cursors[I] = cursor;
4143 }
4144 // Scan the tokens that are at the end of the cursor, but are not captured
4145 // but the child cursors.
4146 for (unsigned I = AfterChildren; I != Last; ++I)
4147 Cursors[I] = cursor;
4148
4149 TokIdx = Last;
4150 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004151}
4152
Ted Kremenek6db61092010-05-05 00:55:15 +00004153static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4154 CXCursor parent,
4155 CXClientData client_data) {
4156 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4157}
4158
Ted Kremenekab979612010-11-11 08:05:23 +00004159// This gets run a separate thread to avoid stack blowout.
4160static void runAnnotateTokensWorker(void *UserData) {
4161 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4162}
4163
Ted Kremenek6db61092010-05-05 00:55:15 +00004164extern "C" {
4165
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004166void clang_annotateTokens(CXTranslationUnit TU,
4167 CXToken *Tokens, unsigned NumTokens,
4168 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004169
4170 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004171 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004172
Douglas Gregor4419b672010-10-21 06:10:04 +00004173 // Any token we don't specifically annotate will have a NULL cursor.
4174 CXCursor C = clang_getNullCursor();
4175 for (unsigned I = 0; I != NumTokens; ++I)
4176 Cursors[I] = C;
4177
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004178 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004179 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004180 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004181
Douglas Gregorbdf60622010-03-05 21:16:25 +00004182 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004183
Douglas Gregor0396f462010-03-19 05:22:59 +00004184 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004185 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004186 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4187 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004188 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4189 clang_getTokenLocation(TU,
4190 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004191
Douglas Gregor0396f462010-03-19 05:22:59 +00004192 // A mapping from the source locations found when re-lexing or traversing the
4193 // region of interest to the corresponding cursors.
4194 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004195
4196 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004197 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004198 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4199 std::pair<FileID, unsigned> BeginLocInfo
4200 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4201 std::pair<FileID, unsigned> EndLocInfo
4202 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004203
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004204 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004205 bool Invalid = false;
4206 if (BeginLocInfo.first == EndLocInfo.first &&
4207 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4208 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004209 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4210 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004211 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004212 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004213 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004214
4215 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004216 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004217 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004218 Token Tok;
4219 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004220
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004221 reprocess:
4222 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4223 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004224 // don't see it while preprocessing these tokens later, but keep track
4225 // of all of the token locations inside this preprocessing directive so
4226 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004227 //
4228 // FIXME: Some simple tests here could identify macro definitions and
4229 // #undefs, to provide specific cursor kinds for those.
4230 std::vector<SourceLocation> Locations;
4231 do {
4232 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004233 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004234 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004235
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004236 using namespace cxcursor;
4237 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4239 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004240 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004241 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4242 Annotated[Locations[I].getRawEncoding()] = Cursor;
4243 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004244
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 if (Tok.isAtStartOfLine())
4246 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004247
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004248 continue;
4249 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004250
Douglas Gregor48072312010-03-18 15:23:44 +00004251 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004252 break;
4253 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004254 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004255
Douglas Gregor0396f462010-03-19 05:22:59 +00004256 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004257 // a specific cursor.
4258 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4259 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004260
4261 // Run the worker within a CrashRecoveryContext.
4262 llvm::CrashRecoveryContext CRC;
4263 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4264 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4265 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004266}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004267} // end: extern "C"
4268
4269//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004270// Operations for querying linkage of a cursor.
4271//===----------------------------------------------------------------------===//
4272
4273extern "C" {
4274CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004275 if (!clang_isDeclaration(cursor.kind))
4276 return CXLinkage_Invalid;
4277
Ted Kremenek16b42592010-03-03 06:36:57 +00004278 Decl *D = cxcursor::getCursorDecl(cursor);
4279 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4280 switch (ND->getLinkage()) {
4281 case NoLinkage: return CXLinkage_NoLinkage;
4282 case InternalLinkage: return CXLinkage_Internal;
4283 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4284 case ExternalLinkage: return CXLinkage_External;
4285 };
4286
4287 return CXLinkage_Invalid;
4288}
4289} // end: extern "C"
4290
4291//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004292// Operations for querying language of a cursor.
4293//===----------------------------------------------------------------------===//
4294
4295static CXLanguageKind getDeclLanguage(const Decl *D) {
4296 switch (D->getKind()) {
4297 default:
4298 break;
4299 case Decl::ImplicitParam:
4300 case Decl::ObjCAtDefsField:
4301 case Decl::ObjCCategory:
4302 case Decl::ObjCCategoryImpl:
4303 case Decl::ObjCClass:
4304 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004305 case Decl::ObjCForwardProtocol:
4306 case Decl::ObjCImplementation:
4307 case Decl::ObjCInterface:
4308 case Decl::ObjCIvar:
4309 case Decl::ObjCMethod:
4310 case Decl::ObjCProperty:
4311 case Decl::ObjCPropertyImpl:
4312 case Decl::ObjCProtocol:
4313 return CXLanguage_ObjC;
4314 case Decl::CXXConstructor:
4315 case Decl::CXXConversion:
4316 case Decl::CXXDestructor:
4317 case Decl::CXXMethod:
4318 case Decl::CXXRecord:
4319 case Decl::ClassTemplate:
4320 case Decl::ClassTemplatePartialSpecialization:
4321 case Decl::ClassTemplateSpecialization:
4322 case Decl::Friend:
4323 case Decl::FriendTemplate:
4324 case Decl::FunctionTemplate:
4325 case Decl::LinkageSpec:
4326 case Decl::Namespace:
4327 case Decl::NamespaceAlias:
4328 case Decl::NonTypeTemplateParm:
4329 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004330 case Decl::TemplateTemplateParm:
4331 case Decl::TemplateTypeParm:
4332 case Decl::UnresolvedUsingTypename:
4333 case Decl::UnresolvedUsingValue:
4334 case Decl::Using:
4335 case Decl::UsingDirective:
4336 case Decl::UsingShadow:
4337 return CXLanguage_CPlusPlus;
4338 }
4339
4340 return CXLanguage_C;
4341}
4342
4343extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004344
4345enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4346 if (clang_isDeclaration(cursor.kind))
4347 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4348 if (D->hasAttr<UnavailableAttr>() ||
4349 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4350 return CXAvailability_Available;
4351
4352 if (D->hasAttr<DeprecatedAttr>())
4353 return CXAvailability_Deprecated;
4354 }
4355
4356 return CXAvailability_Available;
4357}
4358
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004359CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4360 if (clang_isDeclaration(cursor.kind))
4361 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4362
4363 return CXLanguage_Invalid;
4364}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004365
4366CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4367 if (clang_isDeclaration(cursor.kind)) {
4368 if (Decl *D = getCursorDecl(cursor)) {
4369 DeclContext *DC = D->getDeclContext();
4370 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4371 }
4372 }
4373
4374 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4375 if (Decl *D = getCursorDecl(cursor))
4376 return MakeCXCursor(D, getCursorASTUnit(cursor));
4377 }
4378
4379 return clang_getNullCursor();
4380}
4381
4382CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4383 if (clang_isDeclaration(cursor.kind)) {
4384 if (Decl *D = getCursorDecl(cursor)) {
4385 DeclContext *DC = D->getLexicalDeclContext();
4386 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4387 }
4388 }
4389
4390 // FIXME: Note that we can't easily compute the lexical context of a
4391 // statement or expression, so we return nothing.
4392 return clang_getNullCursor();
4393}
4394
Douglas Gregor9f592342010-10-01 20:25:15 +00004395static void CollectOverriddenMethods(DeclContext *Ctx,
4396 ObjCMethodDecl *Method,
4397 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4398 if (!Ctx)
4399 return;
4400
4401 // If we have a class or category implementation, jump straight to the
4402 // interface.
4403 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4404 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4405
4406 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4407 if (!Container)
4408 return;
4409
4410 // Check whether we have a matching method at this level.
4411 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4412 Method->isInstanceMethod()))
4413 if (Method != Overridden) {
4414 // We found an override at this level; there is no need to look
4415 // into other protocols or categories.
4416 Methods.push_back(Overridden);
4417 return;
4418 }
4419
4420 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4421 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4422 PEnd = Protocol->protocol_end();
4423 P != PEnd; ++P)
4424 CollectOverriddenMethods(*P, Method, Methods);
4425 }
4426
4427 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4428 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4429 PEnd = Category->protocol_end();
4430 P != PEnd; ++P)
4431 CollectOverriddenMethods(*P, Method, Methods);
4432 }
4433
4434 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4435 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4436 PEnd = Interface->protocol_end();
4437 P != PEnd; ++P)
4438 CollectOverriddenMethods(*P, Method, Methods);
4439
4440 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4441 Category; Category = Category->getNextClassCategory())
4442 CollectOverriddenMethods(Category, Method, Methods);
4443
4444 // We only look into the superclass if we haven't found anything yet.
4445 if (Methods.empty())
4446 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4447 return CollectOverriddenMethods(Super, Method, Methods);
4448 }
4449}
4450
4451void clang_getOverriddenCursors(CXCursor cursor,
4452 CXCursor **overridden,
4453 unsigned *num_overridden) {
4454 if (overridden)
4455 *overridden = 0;
4456 if (num_overridden)
4457 *num_overridden = 0;
4458 if (!overridden || !num_overridden)
4459 return;
4460
4461 if (!clang_isDeclaration(cursor.kind))
4462 return;
4463
4464 Decl *D = getCursorDecl(cursor);
4465 if (!D)
4466 return;
4467
4468 // Handle C++ member functions.
4469 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4470 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4471 *num_overridden = CXXMethod->size_overridden_methods();
4472 if (!*num_overridden)
4473 return;
4474
4475 *overridden = new CXCursor [*num_overridden];
4476 unsigned I = 0;
4477 for (CXXMethodDecl::method_iterator
4478 M = CXXMethod->begin_overridden_methods(),
4479 MEnd = CXXMethod->end_overridden_methods();
4480 M != MEnd; (void)++M, ++I)
4481 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4482 return;
4483 }
4484
4485 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4486 if (!Method)
4487 return;
4488
4489 // Handle Objective-C methods.
4490 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4491 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4492
4493 if (Methods.empty())
4494 return;
4495
4496 *num_overridden = Methods.size();
4497 *overridden = new CXCursor [Methods.size()];
4498 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4499 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4500}
4501
4502void clang_disposeOverriddenCursors(CXCursor *overridden) {
4503 delete [] overridden;
4504}
4505
Douglas Gregorecdcb882010-10-20 22:00:55 +00004506CXFile clang_getIncludedFile(CXCursor cursor) {
4507 if (cursor.kind != CXCursor_InclusionDirective)
4508 return 0;
4509
4510 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4511 return (void *)ID->getFile();
4512}
4513
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004514} // end: extern "C"
4515
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004516
4517//===----------------------------------------------------------------------===//
4518// C++ AST instrospection.
4519//===----------------------------------------------------------------------===//
4520
4521extern "C" {
4522unsigned clang_CXXMethod_isStatic(CXCursor C) {
4523 if (!clang_isDeclaration(C.kind))
4524 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004525
4526 CXXMethodDecl *Method = 0;
4527 Decl *D = cxcursor::getCursorDecl(C);
4528 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4529 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4530 else
4531 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4532 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004533}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004534
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004535} // end: extern "C"
4536
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004537//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004538// Attribute introspection.
4539//===----------------------------------------------------------------------===//
4540
4541extern "C" {
4542CXType clang_getIBOutletCollectionType(CXCursor C) {
4543 if (C.kind != CXCursor_IBOutletCollectionAttr)
4544 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4545
4546 IBOutletCollectionAttr *A =
4547 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4548
4549 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4550}
4551} // end: extern "C"
4552
4553//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004554// CXString Operations.
4555//===----------------------------------------------------------------------===//
4556
4557extern "C" {
4558const char *clang_getCString(CXString string) {
4559 return string.Spelling;
4560}
4561
4562void clang_disposeString(CXString string) {
4563 if (string.MustFreeString && string.Spelling)
4564 free((void*)string.Spelling);
4565}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004566
Ted Kremenekfb480492010-01-13 21:46:36 +00004567} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004568
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004569namespace clang { namespace cxstring {
4570CXString createCXString(const char *String, bool DupString){
4571 CXString Str;
4572 if (DupString) {
4573 Str.Spelling = strdup(String);
4574 Str.MustFreeString = 1;
4575 } else {
4576 Str.Spelling = String;
4577 Str.MustFreeString = 0;
4578 }
4579 return Str;
4580}
4581
4582CXString createCXString(llvm::StringRef String, bool DupString) {
4583 CXString Result;
4584 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4585 char *Spelling = (char *)malloc(String.size() + 1);
4586 memmove(Spelling, String.data(), String.size());
4587 Spelling[String.size()] = 0;
4588 Result.Spelling = Spelling;
4589 Result.MustFreeString = 1;
4590 } else {
4591 Result.Spelling = String.data();
4592 Result.MustFreeString = 0;
4593 }
4594 return Result;
4595}
4596}}
4597
Ted Kremenek04bb7162010-01-22 22:44:15 +00004598//===----------------------------------------------------------------------===//
4599// Misc. utility functions.
4600//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004601
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004602/// Default to using an 8 MB stack size on "safety" threads.
4603static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004604
4605namespace clang {
4606
4607bool RunSafely(llvm::CrashRecoveryContext &CRC,
4608 void (*Fn)(void*), void *UserData) {
4609 if (unsigned Size = GetSafetyThreadStackSize())
4610 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4611 return CRC.RunSafely(Fn, UserData);
4612}
4613
4614unsigned GetSafetyThreadStackSize() {
4615 return SafetyStackThreadSize;
4616}
4617
4618void SetSafetyThreadStackSize(unsigned Value) {
4619 SafetyStackThreadSize = Value;
4620}
4621
4622}
4623
Ted Kremenek04bb7162010-01-22 22:44:15 +00004624extern "C" {
4625
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004626CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004627 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004628}
4629
4630} // end: extern "C"