blob: de28875de8c952ee7a4ec70dadaeee39e45e5166 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000126
127class VisitorJob {
128public:
129 enum Kind { StmtVisitKind, MemberExprPartsKind };
130protected:
131 void *data;
132 CXCursor parent;
133 Kind K;
134 VisitorJob(void *d, CXCursor C, Kind k) : data(d), parent(C), K(k) {}
135public:
136 Kind getKind() const { return K; }
137 const CXCursor &getParent() const { return parent; }
138 static bool classof(VisitorJob *VJ) { return true; }
139};
140
141typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
142
143#define DEF_JOB(NAME, DATA, KIND)\
144class NAME : public VisitorJob {\
145public:\
146 NAME(DATA *d, CXCursor parent) : VisitorJob(d, parent, VisitorJob::KIND) {}\
147 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
148 DATA *get() const { return static_cast<DATA*>(data); }\
149};
150
151DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
152DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
153
154#undef DEF_JOB
155
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000156
Douglas Gregorb1373d02010-01-20 20:59:29 +0000157// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000158class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000159 public TypeLocVisitor<CursorVisitor, bool>,
160 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000161{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000162 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000163 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000167
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 /// \brief The declaration that serves at the parent of any statement or
169 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000170 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000171
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000176 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000178 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
179 // to the visitor. Declarations with a PCH level greater than this value will
180 // be suppressed.
181 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182
183 /// \brief When valid, a source range to which the cursor should restrict
184 /// its search.
185 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000186
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000187 // FIXME: Eventually remove. This part of a hack to support proper
188 // iteration over all Decls contained lexically within an ObjC container.
189 DeclContext::decl_iterator *DI_current;
190 DeclContext::decl_iterator DE_current;
191
Douglas Gregorb1373d02010-01-20 20:59:29 +0000192 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000193 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000194 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000195
196 /// \brief Determine whether this particular source range comes before, comes
197 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000198 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000199 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000200 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
201
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000202 class SetParentRAII {
203 CXCursor &Parent;
204 Decl *&StmtParent;
205 CXCursor OldParent;
206
207 public:
208 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
209 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
210 {
211 Parent = NewParent;
212 if (clang_isDeclaration(Parent.kind))
213 StmtParent = getCursorDecl(Parent);
214 }
215
216 ~SetParentRAII() {
217 Parent = OldParent;
218 if (clang_isDeclaration(Parent.kind))
219 StmtParent = getCursorDecl(Parent);
220 }
221 };
222
Steve Naroff89922f82009-08-31 00:59:03 +0000223public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000224 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
225 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000226 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000227 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000228 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
229 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000230 {
231 Parent.kind = CXCursor_NoDeclFound;
232 Parent.data[0] = 0;
233 Parent.data[1] = 0;
234 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000235 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000236 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000237
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000238 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000239
240 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
241 getPreprocessedEntities();
242
Douglas Gregorb1373d02010-01-20 20:59:29 +0000243 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000244
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000245 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000246 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000247 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000248 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000249 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000250 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000251 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
252 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000253 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000254 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000255 bool VisitClassTemplatePartialSpecializationDecl(
256 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000257 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000258 bool VisitEnumConstantDecl(EnumConstantDecl *D);
259 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
260 bool VisitFunctionDecl(FunctionDecl *ND);
261 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000262 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000263 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000264 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000265 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000266 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000267 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
268 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
269 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
270 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000271 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000272 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
273 bool VisitObjCImplDecl(ObjCImplDecl *D);
274 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
275 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000276 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
277 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
278 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000279 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000280 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000281 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000282 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000283 bool VisitUsingDecl(UsingDecl *D);
284 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
285 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000286
Douglas Gregor01829d32010-08-31 14:41:23 +0000287 // Name visitor
288 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000289 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000290
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000291 // Template visitors
292 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000293 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000294 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
295
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000296 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000297 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000298 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000299 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000300 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
301 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000302 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000303 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000304 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000305 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
306 bool VisitPointerTypeLoc(PointerTypeLoc TL);
307 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
308 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
309 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
310 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000311 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000312 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000313 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000314 // FIXME: Implement visitors here when the unimplemented TypeLocs get
315 // implemented
316 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
317 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000318
Douglas Gregora59e3902010-01-21 23:27:09 +0000319 // Statement visitors
320 bool VisitStmt(Stmt *S);
321 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000322 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000323 bool VisitIfStmt(IfStmt *S);
324 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000325 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000326 bool VisitWhileStmt(WhileStmt *S);
327 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000328
Douglas Gregor336fd812010-01-23 00:40:08 +0000329 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000330 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000331 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000332 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000333 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000334 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000335 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000336 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000337 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000338 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000339 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000340 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
341 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000342 bool VisitInitListExpr(InitListExpr *E);
343 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000344 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000345 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000346 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000347 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
348 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000349 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000350 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000351 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000352 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000353 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000354 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000355 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000356 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000357
358#define DATA_RECURSIVE_VISIT(NAME)\
359bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
360 DATA_RECURSIVE_VISIT(BinaryOperator)
361 DATA_RECURSIVE_VISIT(MemberExpr)
362 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
363
364 // Data-recursive visitor functions.
365 bool IsInRegionOfInterest(CXCursor C);
366 bool RunVisitorWorkList(VisitorWorkList &WL);
367 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
368 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000369};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000370
Ted Kremenekab188932010-01-05 19:32:54 +0000371} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000372
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000373static SourceRange getRawCursorExtent(CXCursor C);
374
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000375RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000376 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
377}
378
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379/// \brief Visit the given cursor and, if requested by the visitor,
380/// its children.
381///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000382/// \param Cursor the cursor to visit.
383///
384/// \param CheckRegionOfInterest if true, then the caller already checked that
385/// this cursor is within the region of interest.
386///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000387/// \returns true if the visitation should be aborted, false if it
388/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000389bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000390 if (clang_isInvalid(Cursor.kind))
391 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000392
Douglas Gregorb1373d02010-01-20 20:59:29 +0000393 if (clang_isDeclaration(Cursor.kind)) {
394 Decl *D = getCursorDecl(Cursor);
395 assert(D && "Invalid declaration cursor");
396 if (D->getPCHLevel() > MaxPCHLevel)
397 return false;
398
399 if (D->isImplicit())
400 return false;
401 }
402
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000403 // If we have a range of interest, and this cursor doesn't intersect with it,
404 // we're done.
405 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000406 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000407 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408 return false;
409 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000410
Douglas Gregorb1373d02010-01-20 20:59:29 +0000411 switch (Visitor(Cursor, Parent, ClientData)) {
412 case CXChildVisit_Break:
413 return true;
414
415 case CXChildVisit_Continue:
416 return false;
417
418 case CXChildVisit_Recurse:
419 return VisitChildren(Cursor);
420 }
421
Douglas Gregorfd643772010-01-25 16:45:46 +0000422 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000423}
424
Douglas Gregor788f5a12010-03-20 00:41:21 +0000425std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
426CursorVisitor::getPreprocessedEntities() {
427 PreprocessingRecord &PPRec
428 = *TU->getPreprocessor().getPreprocessingRecord();
429
430 bool OnlyLocalDecls
431 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
432
433 // There is no region of interest; we have to walk everything.
434 if (RegionOfInterest.isInvalid())
435 return std::make_pair(PPRec.begin(OnlyLocalDecls),
436 PPRec.end(OnlyLocalDecls));
437
438 // Find the file in which the region of interest lands.
439 SourceManager &SM = TU->getSourceManager();
440 std::pair<FileID, unsigned> Begin
441 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
442 std::pair<FileID, unsigned> End
443 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
444
445 // The region of interest spans files; we have to walk everything.
446 if (Begin.first != End.first)
447 return std::make_pair(PPRec.begin(OnlyLocalDecls),
448 PPRec.end(OnlyLocalDecls));
449
450 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
451 = TU->getPreprocessedEntitiesByFile();
452 if (ByFileMap.empty()) {
453 // Build the mapping from files to sets of preprocessed entities.
454 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
455 EEnd = PPRec.end(OnlyLocalDecls);
456 E != EEnd; ++E) {
457 std::pair<FileID, unsigned> P
458 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
459 ByFileMap[P.first].push_back(*E);
460 }
461 }
462
463 return std::make_pair(ByFileMap[Begin.first].begin(),
464 ByFileMap[Begin.first].end());
465}
466
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467/// \brief Visit the children of the given cursor.
468///
469/// \returns true if the visitation should be aborted, false if it
470/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000472 if (clang_isReference(Cursor.kind)) {
473 // By definition, references have no children.
474 return false;
475 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
477 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000478 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000479 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000480
Douglas Gregorb1373d02010-01-20 20:59:29 +0000481 if (clang_isDeclaration(Cursor.kind)) {
482 Decl *D = getCursorDecl(Cursor);
483 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000484 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000485 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000486
Douglas Gregora59e3902010-01-21 23:27:09 +0000487 if (clang_isStatement(Cursor.kind))
488 return Visit(getCursorStmt(Cursor));
489 if (clang_isExpression(Cursor.kind))
490 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000491
Douglas Gregorb1373d02010-01-20 20:59:29 +0000492 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000493 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000494 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
495 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000496 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
497 TLEnd = CXXUnit->top_level_end();
498 TL != TLEnd; ++TL) {
499 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000500 return true;
501 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 } else if (VisitDeclContext(
503 CXXUnit->getASTContext().getTranslationUnitDecl()))
504 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000505
Douglas Gregor0396f462010-03-19 05:22:59 +0000506 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000507 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 // FIXME: Once we have the ability to deserialize a preprocessing record,
509 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000510 PreprocessingRecord::iterator E, EEnd;
511 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
513 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
514 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000515
Douglas Gregor0396f462010-03-19 05:22:59 +0000516 continue;
517 }
518
519 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
520 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
521 return true;
522
523 continue;
524 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000525
526 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
527 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
528 return true;
529
530 continue;
531 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000532 }
533 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000534 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000535 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000536
Douglas Gregorb1373d02010-01-20 20:59:29 +0000537 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000538 return false;
539}
540
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000541bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000542 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
543 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000544
Ted Kremenek664cffd2010-07-22 11:30:19 +0000545 if (Stmt *Body = B->getBody())
546 return Visit(MakeCXCursor(Body, StmtParent, TU));
547
548 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000549}
550
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000551llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
552 if (RegionOfInterest.isValid()) {
553 SourceRange Range = getRawCursorExtent(Cursor);
554 if (Range.isInvalid())
555 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000556
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000557 switch (CompareRegionOfInterest(Range)) {
558 case RangeBefore:
559 // This declaration comes before the region of interest; skip it.
560 return llvm::Optional<bool>();
561
562 case RangeAfter:
563 // This declaration comes after the region of interest; we're done.
564 return false;
565
566 case RangeOverlap:
567 // This declaration overlaps the region of interest; visit it.
568 break;
569 }
570 }
571 return true;
572}
573
574bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
575 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
576
577 // FIXME: Eventually remove. This part of a hack to support proper
578 // iteration over all Decls contained lexically within an ObjC container.
579 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
580 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
581
582 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000583 Decl *D = *I;
584 if (D->getLexicalDeclContext() != DC)
585 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000586 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000587 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
588 if (!V.hasValue())
589 continue;
590 if (!V.getValue())
591 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000592 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000593 return true;
594 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000596}
597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
599 llvm_unreachable("Translation units are visited directly by Visit()");
600 return false;
601}
602
603bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
604 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
605 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607 return false;
608}
609
610bool CursorVisitor::VisitTagDecl(TagDecl *D) {
611 return VisitDeclContext(D);
612}
613
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000614bool CursorVisitor::VisitClassTemplateSpecializationDecl(
615 ClassTemplateSpecializationDecl *D) {
616 bool ShouldVisitBody = false;
617 switch (D->getSpecializationKind()) {
618 case TSK_Undeclared:
619 case TSK_ImplicitInstantiation:
620 // Nothing to visit
621 return false;
622
623 case TSK_ExplicitInstantiationDeclaration:
624 case TSK_ExplicitInstantiationDefinition:
625 break;
626
627 case TSK_ExplicitSpecialization:
628 ShouldVisitBody = true;
629 break;
630 }
631
632 // Visit the template arguments used in the specialization.
633 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
634 TypeLoc TL = SpecType->getTypeLoc();
635 if (TemplateSpecializationTypeLoc *TSTLoc
636 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
637 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
638 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
639 return true;
640 }
641 }
642
643 if (ShouldVisitBody && VisitCXXRecordDecl(D))
644 return true;
645
646 return false;
647}
648
Douglas Gregor74dbe642010-08-31 19:31:58 +0000649bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
650 ClassTemplatePartialSpecializationDecl *D) {
651 // FIXME: Visit the "outer" template parameter lists on the TagDecl
652 // before visiting these template parameters.
653 if (VisitTemplateParameters(D->getTemplateParameters()))
654 return true;
655
656 // Visit the partial specialization arguments.
657 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
658 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
659 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
660 return true;
661
662 return VisitCXXRecordDecl(D);
663}
664
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000665bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000666 // Visit the default argument.
667 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
668 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
669 if (Visit(DefArg->getTypeLoc()))
670 return true;
671
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000672 return false;
673}
674
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000675bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
676 if (Expr *Init = D->getInitExpr())
677 return Visit(MakeCXCursor(Init, StmtParent, TU));
678 return false;
679}
680
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000681bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
682 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
683 if (Visit(TSInfo->getTypeLoc()))
684 return true;
685
686 return false;
687}
688
Douglas Gregora67e03f2010-09-09 21:42:20 +0000689/// \brief Compare two base or member initializers based on their source order.
690static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
691 CXXBaseOrMemberInitializer const * const *X
692 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
693 CXXBaseOrMemberInitializer const * const *Y
694 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
695
696 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
697 return -1;
698 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
699 return 1;
700 else
701 return 0;
702}
703
Douglas Gregorb1373d02010-01-20 20:59:29 +0000704bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000705 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
706 // Visit the function declaration's syntactic components in the order
707 // written. This requires a bit of work.
708 TypeLoc TL = TSInfo->getTypeLoc();
709 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
710
711 // If we have a function declared directly (without the use of a typedef),
712 // visit just the return type. Otherwise, just visit the function's type
713 // now.
714 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
715 (!FTL && Visit(TL)))
716 return true;
717
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000718 // Visit the nested-name-specifier, if present.
719 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
720 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
721 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000722
723 // Visit the declaration name.
724 if (VisitDeclarationNameInfo(ND->getNameInfo()))
725 return true;
726
727 // FIXME: Visit explicitly-specified template arguments!
728
729 // Visit the function parameters, if we have a function type.
730 if (FTL && VisitFunctionTypeLoc(*FTL, true))
731 return true;
732
733 // FIXME: Attributes?
734 }
735
Douglas Gregora67e03f2010-09-09 21:42:20 +0000736 if (ND->isThisDeclarationADefinition()) {
737 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
738 // Find the initializers that were written in the source.
739 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
740 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
741 IEnd = Constructor->init_end();
742 I != IEnd; ++I) {
743 if (!(*I)->isWritten())
744 continue;
745
746 WrittenInits.push_back(*I);
747 }
748
749 // Sort the initializers in source order
750 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
751 &CompareCXXBaseOrMemberInitializers);
752
753 // Visit the initializers in source order
754 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
755 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
756 if (Init->isMemberInitializer()) {
757 if (Visit(MakeCursorMemberRef(Init->getMember(),
758 Init->getMemberLocation(), TU)))
759 return true;
760 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
761 if (Visit(BaseInfo->getTypeLoc()))
762 return true;
763 }
764
765 // Visit the initializer value.
766 if (Expr *Initializer = Init->getInit())
767 if (Visit(MakeCXCursor(Initializer, ND, TU)))
768 return true;
769 }
770 }
771
772 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
773 return true;
774 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000775
Douglas Gregorb1373d02010-01-20 20:59:29 +0000776 return false;
777}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000778
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000779bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
780 if (VisitDeclaratorDecl(D))
781 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000783 if (Expr *BitWidth = D->getBitWidth())
784 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000786 return false;
787}
788
789bool CursorVisitor::VisitVarDecl(VarDecl *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 *Init = D->getInit())
794 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000795
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796 return false;
797}
798
Douglas Gregor84b51d72010-09-01 20:16:53 +0000799bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
800 if (VisitDeclaratorDecl(D))
801 return true;
802
803 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
804 if (Expr *DefArg = D->getDefaultArgument())
805 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
806
807 return false;
808}
809
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000810bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
811 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
812 // before visiting these template parameters.
813 if (VisitTemplateParameters(D->getTemplateParameters()))
814 return true;
815
816 return VisitFunctionDecl(D->getTemplatedDecl());
817}
818
Douglas Gregor39d6f072010-08-31 19:02:00 +0000819bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
820 // FIXME: Visit the "outer" template parameter lists on the TagDecl
821 // before visiting these template parameters.
822 if (VisitTemplateParameters(D->getTemplateParameters()))
823 return true;
824
825 return VisitCXXRecordDecl(D->getTemplatedDecl());
826}
827
Douglas Gregor84b51d72010-09-01 20:16:53 +0000828bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
829 if (VisitTemplateParameters(D->getTemplateParameters()))
830 return true;
831
832 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
833 VisitTemplateArgumentLoc(D->getDefaultArgument()))
834 return true;
835
836 return false;
837}
838
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000840 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
841 if (Visit(TSInfo->getTypeLoc()))
842 return true;
843
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000844 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000845 PEnd = ND->param_end();
846 P != PEnd; ++P) {
847 if (Visit(MakeCXCursor(*P, TU)))
848 return true;
849 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000851 if (ND->isThisDeclarationADefinition() &&
852 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
853 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000854
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855 return false;
856}
857
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000858namespace {
859 struct ContainerDeclsSort {
860 SourceManager &SM;
861 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
862 bool operator()(Decl *A, Decl *B) {
863 SourceLocation L_A = A->getLocStart();
864 SourceLocation L_B = B->getLocStart();
865 assert(L_A.isValid() && L_B.isValid());
866 return SM.isBeforeInTranslationUnit(L_A, L_B);
867 }
868 };
869}
870
Douglas Gregora59e3902010-01-21 23:27:09 +0000871bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000872 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
873 // an @implementation can lexically contain Decls that are not properly
874 // nested in the AST. When we identify such cases, we need to retrofit
875 // this nesting here.
876 if (!DI_current)
877 return VisitDeclContext(D);
878
879 // Scan the Decls that immediately come after the container
880 // in the current DeclContext. If any fall within the
881 // container's lexical region, stash them into a vector
882 // for later processing.
883 llvm::SmallVector<Decl *, 24> DeclsInContainer;
884 SourceLocation EndLoc = D->getSourceRange().getEnd();
885 SourceManager &SM = TU->getSourceManager();
886 if (EndLoc.isValid()) {
887 DeclContext::decl_iterator next = *DI_current;
888 while (++next != DE_current) {
889 Decl *D_next = *next;
890 if (!D_next)
891 break;
892 SourceLocation L = D_next->getLocStart();
893 if (!L.isValid())
894 break;
895 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
896 *DI_current = next;
897 DeclsInContainer.push_back(D_next);
898 continue;
899 }
900 break;
901 }
902 }
903
904 // The common case.
905 if (DeclsInContainer.empty())
906 return VisitDeclContext(D);
907
908 // Get all the Decls in the DeclContext, and sort them with the
909 // additional ones we've collected. Then visit them.
910 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
911 I!=E; ++I) {
912 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000913 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
914 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000915 continue;
916 DeclsInContainer.push_back(subDecl);
917 }
918
919 // Now sort the Decls so that they appear in lexical order.
920 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
921 ContainerDeclsSort(SM));
922
923 // Now visit the decls.
924 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
925 E = DeclsInContainer.end(); I != E; ++I) {
926 CXCursor Cursor = MakeCXCursor(*I, TU);
927 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
928 if (!V.hasValue())
929 continue;
930 if (!V.getValue())
931 return false;
932 if (Visit(Cursor, true))
933 return true;
934 }
935 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000936}
937
Douglas Gregorb1373d02010-01-20 20:59:29 +0000938bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000939 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
940 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000943 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
944 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
945 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000946 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregora59e3902010-01-21 23:27:09 +0000949 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000950}
951
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000952bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
953 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
954 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
955 E = PID->protocol_end(); I != E; ++I, ++PL)
956 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
957 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000958
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000959 return VisitObjCContainerDecl(PID);
960}
961
Ted Kremenek23173d72010-05-18 21:09:07 +0000962bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000963 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000964 return true;
965
Ted Kremenek23173d72010-05-18 21:09:07 +0000966 // FIXME: This implements a workaround with @property declarations also being
967 // installed in the DeclContext for the @interface. Eventually this code
968 // should be removed.
969 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
970 if (!CDecl || !CDecl->IsClassExtension())
971 return false;
972
973 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
974 if (!ID)
975 return false;
976
977 IdentifierInfo *PropertyId = PD->getIdentifier();
978 ObjCPropertyDecl *prevDecl =
979 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
980
981 if (!prevDecl)
982 return false;
983
984 // Visit synthesized methods since they will be skipped when visiting
985 // the @interface.
986 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000987 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000988 if (Visit(MakeCXCursor(MD, TU)))
989 return true;
990
991 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000992 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000993 if (Visit(MakeCXCursor(MD, TU)))
994 return true;
995
996 return false;
997}
998
Douglas Gregorb1373d02010-01-20 20:59:29 +0000999bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001000 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001001 if (D->getSuperClass() &&
1002 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001003 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001004 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001005 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001007 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1008 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1009 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001010 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregora59e3902010-01-21 23:27:09 +00001013 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001014}
1015
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001016bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1017 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001018}
1019
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001020bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001021 // 'ID' could be null when dealing with invalid code.
1022 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1023 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1024 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026 return VisitObjCImplDecl(D);
1027}
1028
1029bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1030#if 0
1031 // Issue callbacks for super class.
1032 // FIXME: No source location information!
1033 if (D->getSuperClass() &&
1034 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001035 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001036 TU)))
1037 return true;
1038#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001040 return VisitObjCImplDecl(D);
1041}
1042
1043bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1044 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1045 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1046 E = D->protocol_end();
1047 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001048 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001049 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001050
1051 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001052}
1053
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001054bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1055 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1056 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1057 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001058
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001059 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001060}
1061
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001062bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1063 return VisitDeclContext(D);
1064}
1065
Douglas Gregor69319002010-08-31 23:48:11 +00001066bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001067 // Visit nested-name-specifier.
1068 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1069 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1070 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001071
1072 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1073 D->getTargetNameLoc(), TU));
1074}
1075
Douglas Gregor7e242562010-09-01 19:52:22 +00001076bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
1078 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1079 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1080 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001081
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001082 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1083 return true;
1084
Douglas Gregor7e242562010-09-01 19:52:22 +00001085 return VisitDeclarationNameInfo(D->getNameInfo());
1086}
1087
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001088bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001089 // Visit nested-name-specifier.
1090 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1091 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1092 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001093
1094 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1095 D->getIdentLocation(), TU));
1096}
1097
Douglas Gregor7e242562010-09-01 19:52:22 +00001098bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001099 // Visit nested-name-specifier.
1100 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1101 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1102 return true;
1103
Douglas Gregor7e242562010-09-01 19:52:22 +00001104 return VisitDeclarationNameInfo(D->getNameInfo());
1105}
1106
1107bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1108 UnresolvedUsingTypenameDecl *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 false;
1115}
1116
Douglas Gregor01829d32010-08-31 14:41:23 +00001117bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1118 switch (Name.getName().getNameKind()) {
1119 case clang::DeclarationName::Identifier:
1120 case clang::DeclarationName::CXXLiteralOperatorName:
1121 case clang::DeclarationName::CXXOperatorName:
1122 case clang::DeclarationName::CXXUsingDirective:
1123 return false;
1124
1125 case clang::DeclarationName::CXXConstructorName:
1126 case clang::DeclarationName::CXXDestructorName:
1127 case clang::DeclarationName::CXXConversionFunctionName:
1128 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1129 return Visit(TSInfo->getTypeLoc());
1130 return false;
1131
1132 case clang::DeclarationName::ObjCZeroArgSelector:
1133 case clang::DeclarationName::ObjCOneArgSelector:
1134 case clang::DeclarationName::ObjCMultiArgSelector:
1135 // FIXME: Per-identifier location info?
1136 return false;
1137 }
1138
1139 return false;
1140}
1141
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001142bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1143 SourceRange Range) {
1144 // FIXME: This whole routine is a hack to work around the lack of proper
1145 // source information in nested-name-specifiers (PR5791). Since we do have
1146 // a beginning source location, we can visit the first component of the
1147 // nested-name-specifier, if it's a single-token component.
1148 if (!NNS)
1149 return false;
1150
1151 // Get the first component in the nested-name-specifier.
1152 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1153 NNS = Prefix;
1154
1155 switch (NNS->getKind()) {
1156 case NestedNameSpecifier::Namespace:
1157 // FIXME: The token at this source location might actually have been a
1158 // namespace alias, but we don't model that. Lame!
1159 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1160 TU));
1161
1162 case NestedNameSpecifier::TypeSpec: {
1163 // If the type has a form where we know that the beginning of the source
1164 // range matches up with a reference cursor. Visit the appropriate reference
1165 // cursor.
1166 Type *T = NNS->getAsType();
1167 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1168 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1169 if (const TagType *Tag = dyn_cast<TagType>(T))
1170 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1171 if (const TemplateSpecializationType *TST
1172 = dyn_cast<TemplateSpecializationType>(T))
1173 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1174 break;
1175 }
1176
1177 case NestedNameSpecifier::TypeSpecWithTemplate:
1178 case NestedNameSpecifier::Global:
1179 case NestedNameSpecifier::Identifier:
1180 break;
1181 }
1182
1183 return false;
1184}
1185
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001186bool CursorVisitor::VisitTemplateParameters(
1187 const TemplateParameterList *Params) {
1188 if (!Params)
1189 return false;
1190
1191 for (TemplateParameterList::const_iterator P = Params->begin(),
1192 PEnd = Params->end();
1193 P != PEnd; ++P) {
1194 if (Visit(MakeCXCursor(*P, TU)))
1195 return true;
1196 }
1197
1198 return false;
1199}
1200
Douglas Gregor0b36e612010-08-31 20:37:03 +00001201bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1202 switch (Name.getKind()) {
1203 case TemplateName::Template:
1204 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1205
1206 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001207 // Visit the overloaded template set.
1208 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1209 return true;
1210
Douglas Gregor0b36e612010-08-31 20:37:03 +00001211 return false;
1212
1213 case TemplateName::DependentTemplate:
1214 // FIXME: Visit nested-name-specifier.
1215 return false;
1216
1217 case TemplateName::QualifiedTemplate:
1218 // FIXME: Visit nested-name-specifier.
1219 return Visit(MakeCursorTemplateRef(
1220 Name.getAsQualifiedTemplateName()->getDecl(),
1221 Loc, TU));
1222 }
1223
1224 return false;
1225}
1226
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001227bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1228 switch (TAL.getArgument().getKind()) {
1229 case TemplateArgument::Null:
1230 case TemplateArgument::Integral:
1231 return false;
1232
1233 case TemplateArgument::Pack:
1234 // FIXME: Implement when variadic templates come along.
1235 return false;
1236
1237 case TemplateArgument::Type:
1238 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1239 return Visit(TSInfo->getTypeLoc());
1240 return false;
1241
1242 case TemplateArgument::Declaration:
1243 if (Expr *E = TAL.getSourceDeclExpression())
1244 return Visit(MakeCXCursor(E, StmtParent, TU));
1245 return false;
1246
1247 case TemplateArgument::Expression:
1248 if (Expr *E = TAL.getSourceExpression())
1249 return Visit(MakeCXCursor(E, StmtParent, TU));
1250 return false;
1251
1252 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001253 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1254 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001255 }
1256
1257 return false;
1258}
1259
Ted Kremeneka0536d82010-05-07 01:04:29 +00001260bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1261 return VisitDeclContext(D);
1262}
1263
Douglas Gregor01829d32010-08-31 14:41:23 +00001264bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1265 return Visit(TL.getUnqualifiedLoc());
1266}
1267
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001268bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1269 ASTContext &Context = TU->getASTContext();
1270
1271 // Some builtin types (such as Objective-C's "id", "sel", and
1272 // "Class") have associated declarations. Create cursors for those.
1273 QualType VisitType;
1274 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001275 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277 case BuiltinType::Char_U:
1278 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001279 case BuiltinType::Char16:
1280 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001281 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001282 case BuiltinType::UInt:
1283 case BuiltinType::ULong:
1284 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001285 case BuiltinType::UInt128:
1286 case BuiltinType::Char_S:
1287 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001288 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001289 case BuiltinType::Short:
1290 case BuiltinType::Int:
1291 case BuiltinType::Long:
1292 case BuiltinType::LongLong:
1293 case BuiltinType::Int128:
1294 case BuiltinType::Float:
1295 case BuiltinType::Double:
1296 case BuiltinType::LongDouble:
1297 case BuiltinType::NullPtr:
1298 case BuiltinType::Overload:
1299 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001300 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001301
1302 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001303 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001304
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001305 case BuiltinType::ObjCId:
1306 VisitType = Context.getObjCIdType();
1307 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001308
1309 case BuiltinType::ObjCClass:
1310 VisitType = Context.getObjCClassType();
1311 break;
1312
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001313 case BuiltinType::ObjCSel:
1314 VisitType = Context.getObjCSelType();
1315 break;
1316 }
1317
1318 if (!VisitType.isNull()) {
1319 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001320 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001321 TU));
1322 }
1323
1324 return false;
1325}
1326
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001327bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1328 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1329}
1330
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1332 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1333}
1334
1335bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1336 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1337}
1338
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001339bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001340 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001341 // no context information with which we can match up the depth/index in the
1342 // type to the appropriate
1343 return false;
1344}
1345
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001346bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1347 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1348 return true;
1349
John McCallc12c5bb2010-05-15 11:32:37 +00001350 return false;
1351}
1352
1353bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1354 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1355 return true;
1356
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001357 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1358 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1359 TU)))
1360 return true;
1361 }
1362
1363 return false;
1364}
1365
1366bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001367 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001368}
1369
1370bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1371 return Visit(TL.getPointeeLoc());
1372}
1373
1374bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1375 return Visit(TL.getPointeeLoc());
1376}
1377
1378bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1379 return Visit(TL.getPointeeLoc());
1380}
1381
1382bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001383 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384}
1385
1386bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001387 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388}
1389
Douglas Gregor01829d32010-08-31 14:41:23 +00001390bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1391 bool SkipResultType) {
1392 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001393 return true;
1394
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001395 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001396 if (Decl *D = TL.getArg(I))
1397 if (Visit(MakeCXCursor(D, TU)))
1398 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001399
1400 return false;
1401}
1402
1403bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1404 if (Visit(TL.getElementLoc()))
1405 return true;
1406
1407 if (Expr *Size = TL.getSizeExpr())
1408 return Visit(MakeCXCursor(Size, StmtParent, TU));
1409
1410 return false;
1411}
1412
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001413bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1414 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001415 // Visit the template name.
1416 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1417 TL.getTemplateNameLoc()))
1418 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001419
1420 // Visit the template arguments.
1421 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1422 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1423 return true;
1424
1425 return false;
1426}
1427
Douglas Gregor2332c112010-01-21 20:48:56 +00001428bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1429 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1430}
1431
1432bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1433 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1434 return Visit(TSInfo->getTypeLoc());
1435
1436 return false;
1437}
1438
Douglas Gregora59e3902010-01-21 23:27:09 +00001439bool CursorVisitor::VisitStmt(Stmt *S) {
1440 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1441 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001442 if (Stmt *C = *Child)
1443 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1444 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001445 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001446
Douglas Gregora59e3902010-01-21 23:27:09 +00001447 return false;
1448}
1449
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001450bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1451 // Specially handle CaseStmts because they can be nested, e.g.:
1452 //
1453 // case 1:
1454 // case 2:
1455 //
1456 // In this case the second CaseStmt is the child of the first. Walking
1457 // these recursively can blow out the stack.
1458 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1459 while (true) {
1460 // Set the Parent field to Cursor, then back to its old value once we're
1461 // done.
1462 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1463
1464 if (Stmt *LHS = S->getLHS())
1465 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1466 return true;
1467 if (Stmt *RHS = S->getRHS())
1468 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1469 return true;
1470 if (Stmt *SubStmt = S->getSubStmt()) {
1471 if (!isa<CaseStmt>(SubStmt))
1472 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1473
1474 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1475 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1476 Cursor = MakeCXCursor(CS, StmtParent, TU);
1477 if (RegionOfInterest.isValid()) {
1478 SourceRange Range = CS->getSourceRange();
1479 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1480 return false;
1481 }
1482
1483 switch (Visitor(Cursor, Parent, ClientData)) {
1484 case CXChildVisit_Break: return true;
1485 case CXChildVisit_Continue: return false;
1486 case CXChildVisit_Recurse:
1487 // Perform tail-recursion manually.
1488 S = CS;
1489 continue;
1490 }
1491 }
1492 return false;
1493 }
1494}
1495
Douglas Gregora59e3902010-01-21 23:27:09 +00001496bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001497 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001498 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1499 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001500 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001501 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001502 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001503 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001504
Douglas Gregora59e3902010-01-21 23:27:09 +00001505 return false;
1506}
1507
Douglas Gregor36897b02010-09-10 00:22:18 +00001508bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1509 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1510}
1511
Douglas Gregorf5bab412010-01-22 01:00:11 +00001512bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1513 if (VarDecl *Var = S->getConditionVariable()) {
1514 if (Visit(MakeCXCursor(Var, TU)))
1515 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001516 }
1517
Douglas Gregor263b47b2010-01-25 16:12:32 +00001518 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1519 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001520 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1521 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001522 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1523 return true;
1524
1525 return false;
1526}
1527
1528bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1529 if (VarDecl *Var = S->getConditionVariable()) {
1530 if (Visit(MakeCXCursor(Var, TU)))
1531 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001532 }
1533
Douglas Gregor263b47b2010-01-25 16:12:32 +00001534 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1535 return true;
1536 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1537 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001538
Douglas Gregor263b47b2010-01-25 16:12:32 +00001539 return false;
1540}
1541
1542bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1543 if (VarDecl *Var = S->getConditionVariable()) {
1544 if (Visit(MakeCXCursor(Var, TU)))
1545 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001546 }
1547
Douglas Gregor263b47b2010-01-25 16:12:32 +00001548 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1549 return true;
1550 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001551 return true;
1552
Douglas Gregor263b47b2010-01-25 16:12:32 +00001553 return false;
1554}
1555
1556bool CursorVisitor::VisitForStmt(ForStmt *S) {
1557 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1558 return true;
1559 if (VarDecl *Var = S->getConditionVariable()) {
1560 if (Visit(MakeCXCursor(Var, TU)))
1561 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001562 }
1563
Douglas Gregor263b47b2010-01-25 16:12:32 +00001564 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1565 return true;
1566 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1567 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001568 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1569 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001570
Douglas Gregorf5bab412010-01-22 01:00:11 +00001571 return false;
1572}
1573
Douglas Gregor8947a752010-09-02 20:35:02 +00001574bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1575 // Visit nested-name-specifier, if present.
1576 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1577 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1578 return true;
1579
1580 // Visit declaration name.
1581 if (VisitDeclarationNameInfo(E->getNameInfo()))
1582 return true;
1583
1584 // Visit explicitly-specified template arguments.
1585 if (E->hasExplicitTemplateArgs()) {
1586 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1587 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1588 *ArgEnd = Arg + Args.NumTemplateArgs;
1589 Arg != ArgEnd; ++Arg)
1590 if (VisitTemplateArgumentLoc(*Arg))
1591 return true;
1592 }
1593
1594 return false;
1595}
1596
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001597bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1598 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1599 return true;
1600
1601 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1602 return true;
1603
1604 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1605 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1606 return true;
1607
1608 return false;
1609}
1610
Ted Kremenek3064ef92010-08-27 21:34:58 +00001611bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1612 if (D->isDefinition()) {
1613 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1614 E = D->bases_end(); I != E; ++I) {
1615 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1616 return true;
1617 }
1618 }
1619
1620 return VisitTagDecl(D);
1621}
1622
1623
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001624bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1625 return Visit(B->getBlockDecl());
1626}
1627
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001628bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001629 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001630 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1631 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001632
1633 // Visit the components of the offsetof expression.
1634 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1635 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1636 const OffsetOfNode &Node = E->getComponent(I);
1637 switch (Node.getKind()) {
1638 case OffsetOfNode::Array:
1639 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1640 StmtParent, TU)))
1641 return true;
1642 break;
1643
1644 case OffsetOfNode::Field:
1645 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1646 TU)))
1647 return true;
1648 break;
1649
1650 case OffsetOfNode::Identifier:
1651 case OffsetOfNode::Base:
1652 continue;
1653 }
1654 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001655
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001656 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001657}
1658
Douglas Gregor336fd812010-01-23 00:40:08 +00001659bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1660 if (E->isArgumentType()) {
1661 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1662 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001663
Douglas Gregor336fd812010-01-23 00:40:08 +00001664 return false;
1665 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001666
Douglas Gregor336fd812010-01-23 00:40:08 +00001667 return VisitExpr(E);
1668}
1669
1670bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1671 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1672 if (Visit(TSInfo->getTypeLoc()))
1673 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001674
Douglas Gregor336fd812010-01-23 00:40:08 +00001675 return VisitCastExpr(E);
1676}
1677
1678bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1679 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1680 if (Visit(TSInfo->getTypeLoc()))
1681 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001682
Douglas Gregor336fd812010-01-23 00:40:08 +00001683 return VisitExpr(E);
1684}
1685
Douglas Gregor36897b02010-09-10 00:22:18 +00001686bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1687 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1688}
1689
Douglas Gregor648220e2010-08-10 15:02:34 +00001690bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1691 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1692 Visit(E->getArgTInfo2()->getTypeLoc());
1693}
1694
1695bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1696 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1697 return true;
1698
1699 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1700}
1701
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001702bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1703 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001704 if (InitListExpr *Syntactic = E->getSyntacticForm())
1705 return VisitExpr(Syntactic);
1706
1707 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001708}
1709
1710bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1711 // Visit the designators.
1712 typedef DesignatedInitExpr::Designator Designator;
1713 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1714 DEnd = E->designators_end();
1715 D != DEnd; ++D) {
1716 if (D->isFieldDesignator()) {
1717 if (FieldDecl *Field = D->getField())
1718 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1719 return true;
1720
1721 continue;
1722 }
1723
1724 if (D->isArrayDesignator()) {
1725 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1726 return true;
1727
1728 continue;
1729 }
1730
1731 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1732 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1733 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1734 return true;
1735 }
1736
1737 // Visit the initializer value itself.
1738 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1739}
1740
Douglas Gregor94802292010-09-02 21:20:16 +00001741bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1742 if (E->isTypeOperand()) {
1743 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1744 return Visit(TSInfo->getTypeLoc());
1745
1746 return false;
1747 }
1748
1749 return VisitExpr(E);
1750}
1751
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001752bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1753 if (E->isTypeOperand()) {
1754 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1755 return Visit(TSInfo->getTypeLoc());
1756
1757 return false;
1758 }
1759
1760 return VisitExpr(E);
1761}
1762
Douglas Gregorab6677e2010-09-08 00:15:04 +00001763bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1764 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001765 if (Visit(TSInfo->getTypeLoc()))
1766 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001767
1768 return VisitExpr(E);
1769}
1770
1771bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1772 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1773 return Visit(TSInfo->getTypeLoc());
1774
1775 return false;
1776}
1777
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001778bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1779 // Visit placement arguments.
1780 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1781 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1782 return true;
1783
1784 // Visit the allocated type.
1785 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1786 if (Visit(TSInfo->getTypeLoc()))
1787 return true;
1788
1789 // Visit the array size, if any.
1790 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1791 return true;
1792
1793 // Visit the initializer or constructor arguments.
1794 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1795 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1796 return true;
1797
1798 return false;
1799}
1800
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001801bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1802 // Visit base expression.
1803 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1804 return true;
1805
1806 // Visit the nested-name-specifier.
1807 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1808 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1809 return true;
1810
1811 // Visit the scope type that looks disturbingly like the nested-name-specifier
1812 // but isn't.
1813 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1814 if (Visit(TSInfo->getTypeLoc()))
1815 return true;
1816
1817 // Visit the name of the type being destroyed.
1818 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1819 if (Visit(TSInfo->getTypeLoc()))
1820 return true;
1821
1822 return false;
1823}
1824
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001825bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1826 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1827}
1828
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001829bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001830 // Visit the nested-name-specifier.
1831 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1832 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1833 return true;
1834
1835 // Visit the declaration name.
1836 if (VisitDeclarationNameInfo(E->getNameInfo()))
1837 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001838
1839 // Visit the overloaded declaration reference.
1840 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1841 return true;
1842
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001843 // Visit the explicitly-specified template arguments.
1844 if (const ExplicitTemplateArgumentList *ArgList
1845 = E->getOptionalExplicitTemplateArgs()) {
1846 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1847 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1848 Arg != ArgEnd; ++Arg) {
1849 if (VisitTemplateArgumentLoc(*Arg))
1850 return true;
1851 }
1852 }
1853
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001854 return false;
1855}
1856
Douglas Gregorbfebed22010-09-03 17:24:10 +00001857bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1858 DependentScopeDeclRefExpr *E) {
1859 // Visit the nested-name-specifier.
1860 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1861 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1862 return true;
1863
1864 // Visit the declaration name.
1865 if (VisitDeclarationNameInfo(E->getNameInfo()))
1866 return true;
1867
1868 // Visit the explicitly-specified template arguments.
1869 if (const ExplicitTemplateArgumentList *ArgList
1870 = E->getOptionalExplicitTemplateArgs()) {
1871 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1872 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1873 Arg != ArgEnd; ++Arg) {
1874 if (VisitTemplateArgumentLoc(*Arg))
1875 return true;
1876 }
1877 }
1878
1879 return false;
1880}
1881
Douglas Gregorab6677e2010-09-08 00:15:04 +00001882bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1883 CXXUnresolvedConstructExpr *E) {
1884 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1885 if (Visit(TSInfo->getTypeLoc()))
1886 return true;
1887
1888 return VisitExpr(E);
1889}
1890
Douglas Gregor25d63622010-09-03 17:35:34 +00001891bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1892 CXXDependentScopeMemberExpr *E) {
1893 // Visit the base expression, if there is one.
1894 if (!E->isImplicitAccess() &&
1895 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1896 return true;
1897
1898 // Visit the nested-name-specifier.
1899 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1900 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1901 return true;
1902
1903 // Visit the declaration name.
1904 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1905 return true;
1906
1907 // Visit the explicitly-specified template arguments.
1908 if (const ExplicitTemplateArgumentList *ArgList
1909 = E->getOptionalExplicitTemplateArgs()) {
1910 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1911 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1912 Arg != ArgEnd; ++Arg) {
1913 if (VisitTemplateArgumentLoc(*Arg))
1914 return true;
1915 }
1916 }
1917
1918 return false;
1919}
1920
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001921bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1922 // Visit the base expression, if there is one.
1923 if (!E->isImplicitAccess() &&
1924 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1925 return true;
1926
1927 return VisitOverloadExpr(E);
1928}
Douglas Gregor25d63622010-09-03 17:35:34 +00001929
Douglas Gregorc2350e52010-03-08 16:40:19 +00001930bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001931 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1932 if (Visit(TSInfo->getTypeLoc()))
1933 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001934
1935 return VisitExpr(E);
1936}
1937
Douglas Gregor81d34662010-04-20 15:39:42 +00001938bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1939 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1940}
1941
1942
Ted Kremenek09dfa372010-02-18 05:46:33 +00001943bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001944 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1945 i != e; ++i)
1946 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001947 return true;
1948
1949 return false;
1950}
1951
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001952//===----------------------------------------------------------------------===//
1953// Data-recursive visitor methods.
1954//===----------------------------------------------------------------------===//
1955
1956void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1957 CXCursor C = MakeCXCursor(S, StmtParent, TU);
1958 switch (S->getStmtClass()) {
1959 default: {
1960 unsigned size = WL.size();
1961 for (Stmt::child_iterator Child = S->child_begin(),
1962 ChildEnd = S->child_end(); Child != ChildEnd; ++Child) {
1963 if (Stmt *child = *Child) {
1964 WL.push_back(StmtVisit(child, C));
1965 }
1966 }
1967
1968 if (size == WL.size())
1969 return;
1970
1971 // Now reverse the entries we just added. This will match the DFS
1972 // ordering performed by the worklist.
1973 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1974 std::reverse(I, E);
1975 break;
1976 }
1977 case Stmt::ParenExprClass: {
1978 WL.push_back(StmtVisit(cast<ParenExpr>(S)->getSubExpr(), C));
1979 break;
1980 }
1981 case Stmt::BinaryOperatorClass: {
1982 BinaryOperator *B = cast<BinaryOperator>(S);
1983 WL.push_back(StmtVisit(B->getRHS(), C));
1984 WL.push_back(StmtVisit(B->getLHS(), C));
1985 break;
1986 }
1987 case Stmt::MemberExprClass: {
1988 MemberExpr *M = cast<MemberExpr>(S);
1989 WL.push_back(MemberExprParts(M, C));
1990 WL.push_back(StmtVisit(M->getBase(), C));
1991 break;
1992 }
1993 }
1994}
1995
1996bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1997 if (RegionOfInterest.isValid()) {
1998 SourceRange Range = getRawCursorExtent(C);
1999 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2000 return false;
2001 }
2002 return true;
2003}
2004
2005bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2006 while (!WL.empty()) {
2007 // Dequeue the worklist item.
2008 VisitorJob LI = WL.back(); WL.pop_back();
2009
2010 // Set the Parent field, then back to its old value once we're done.
2011 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2012
2013 switch (LI.getKind()) {
2014 case VisitorJob::StmtVisitKind: {
2015 // Update the current cursor.
2016 Stmt *S = cast<StmtVisit>(LI).get();
2017 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
2018
2019 switch (S->getStmtClass()) {
2020 default: {
2021 // Perform default visitation for other cases.
2022 if (Visit(Cursor))
2023 return true;
2024 continue;
2025 }
2026 case Stmt::CallExprClass:
2027 case Stmt::CXXMemberCallExprClass:
2028 case Stmt::ParenExprClass:
2029 case Stmt::MemberExprClass:
2030 case Stmt::BinaryOperatorClass: {
2031 if (!IsInRegionOfInterest(Cursor))
2032 continue;
2033 switch (Visitor(Cursor, Parent, ClientData)) {
2034 case CXChildVisit_Break:
2035 return true;
2036 case CXChildVisit_Continue:
2037 break;
2038 case CXChildVisit_Recurse:
2039 EnqueueWorkList(WL, S);
2040 break;
2041 }
2042 }
2043 }
2044 continue;
2045 }
2046 case VisitorJob::MemberExprPartsKind: {
2047 // Handle the other pieces in the MemberExpr besides the base.
2048 MemberExpr *M = cast<MemberExprParts>(LI).get();
2049
2050 // Visit the nested-name-specifier
2051 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2052 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2053 return true;
2054
2055 // Visit the declaration name.
2056 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2057 return true;
2058
2059 // Visit the explicitly-specified template arguments, if any.
2060 if (M->hasExplicitTemplateArgs()) {
2061 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2062 *ArgEnd = Arg + M->getNumTemplateArgs();
2063 Arg != ArgEnd; ++Arg) {
2064 if (VisitTemplateArgumentLoc(*Arg))
2065 return true;
2066 }
2067 }
2068 continue;
2069 }
2070 }
2071 }
2072 return false;
2073}
2074
2075bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2076 VisitorWorkList WL;
2077 EnqueueWorkList(WL, S);
2078 return RunVisitorWorkList(WL);
2079}
2080
2081//===----------------------------------------------------------------------===//
2082// Misc. API hooks.
2083//===----------------------------------------------------------------------===//
2084
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002085static llvm::sys::Mutex EnableMultithreadingMutex;
2086static bool EnabledMultithreading;
2087
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002088extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002089CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2090 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002091 // Disable pretty stack trace functionality, which will otherwise be a very
2092 // poor citizen of the world and set up all sorts of signal handlers.
2093 llvm::DisablePrettyStackTrace = true;
2094
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002095 // We use crash recovery to make some of our APIs more reliable, implicitly
2096 // enable it.
2097 llvm::CrashRecoveryContext::Enable();
2098
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002099 // Enable support for multithreading in LLVM.
2100 {
2101 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2102 if (!EnabledMultithreading) {
2103 llvm::llvm_start_multithreaded();
2104 EnabledMultithreading = true;
2105 }
2106 }
2107
Douglas Gregora030b7c2010-01-22 20:35:53 +00002108 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002109 if (excludeDeclarationsFromPCH)
2110 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002111 if (displayDiagnostics)
2112 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002113 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002114}
2115
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002116void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002117 if (CIdx)
2118 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002119}
2120
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002121CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002122 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002123 if (!CIdx)
2124 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002125
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002126 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002127 FileSystemOptions FileSystemOpts;
2128 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002129
Douglas Gregor28019772010-04-05 23:52:57 +00002130 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002131 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002132 CXXIdx->getOnlyLocalDecls(),
2133 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002134}
2135
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002136unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002137 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002138 CXTranslationUnit_CacheCompletionResults |
2139 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002140}
2141
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002142CXTranslationUnit
2143clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2144 const char *source_filename,
2145 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002146 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002147 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002148 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002149 return clang_parseTranslationUnit(CIdx, source_filename,
2150 command_line_args, num_command_line_args,
2151 unsaved_files, num_unsaved_files,
2152 CXTranslationUnit_DetailedPreprocessingRecord);
2153}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002154
2155struct ParseTranslationUnitInfo {
2156 CXIndex CIdx;
2157 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002158 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002159 int num_command_line_args;
2160 struct CXUnsavedFile *unsaved_files;
2161 unsigned num_unsaved_files;
2162 unsigned options;
2163 CXTranslationUnit result;
2164};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002165static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002166 ParseTranslationUnitInfo *PTUI =
2167 static_cast<ParseTranslationUnitInfo*>(UserData);
2168 CXIndex CIdx = PTUI->CIdx;
2169 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002170 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002171 int num_command_line_args = PTUI->num_command_line_args;
2172 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2173 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2174 unsigned options = PTUI->options;
2175 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002176
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002177 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002178 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002180 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2181
Douglas Gregor44c181a2010-07-23 00:33:23 +00002182 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002183 bool CompleteTranslationUnit
2184 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002185 bool CacheCodeCompetionResults
2186 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002187 bool CXXPrecompilePreamble
2188 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2189 bool CXXChainedPCH
2190 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002191
Douglas Gregor5352ac02010-01-28 00:27:43 +00002192 // Configure the diagnostics.
2193 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002194 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2195 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002196
Douglas Gregor4db64a42010-01-23 00:14:00 +00002197 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2198 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002199 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002200 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002201 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002202 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2203 Buffer));
2204 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002205
Douglas Gregorb10daed2010-10-11 16:52:23 +00002206 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002207
Ted Kremenek139ba862009-10-22 00:03:57 +00002208 // The 'source_filename' argument is optional. If the caller does not
2209 // specify it then it is assumed that the source file is specified
2210 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002211 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002212 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002213
2214 // Since the Clang C library is primarily used by batch tools dealing with
2215 // (often very broken) source code, where spell-checking can have a
2216 // significant negative impact on performance (particularly when
2217 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 // Only do this if we haven't found a spell-checking-related argument.
2219 bool FoundSpellCheckingArgument = false;
2220 for (int I = 0; I != num_command_line_args; ++I) {
2221 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2222 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2223 FoundSpellCheckingArgument = true;
2224 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002225 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002226 }
2227 if (!FoundSpellCheckingArgument)
2228 Args.push_back("-fno-spell-checking");
2229
2230 Args.insert(Args.end(), command_line_args,
2231 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002232
Douglas Gregor44c181a2010-07-23 00:33:23 +00002233 // Do we need the detailed preprocessing record?
2234 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002235 Args.push_back("-Xclang");
2236 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002237 }
2238
Douglas Gregorb10daed2010-10-11 16:52:23 +00002239 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002240 llvm::OwningPtr<ASTUnit> Unit(
2241 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2242 Diags,
2243 CXXIdx->getClangResourcesPath(),
2244 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002245 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002246 RemappedFiles.data(),
2247 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002248 PrecompilePreamble,
2249 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002250 CacheCodeCompetionResults,
2251 CXXPrecompilePreamble,
2252 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002253
Douglas Gregorb10daed2010-10-11 16:52:23 +00002254 if (NumErrors != Diags->getNumErrors()) {
2255 // Make sure to check that 'Unit' is non-NULL.
2256 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2257 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2258 DEnd = Unit->stored_diag_end();
2259 D != DEnd; ++D) {
2260 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2261 CXString Msg = clang_formatDiagnostic(&Diag,
2262 clang_defaultDiagnosticDisplayOptions());
2263 fprintf(stderr, "%s\n", clang_getCString(Msg));
2264 clang_disposeString(Msg);
2265 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002266#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002267 // On Windows, force a flush, since there may be multiple copies of
2268 // stderr and stdout in the file system, all with different buffers
2269 // but writing to the same device.
2270 fflush(stderr);
2271#endif
2272 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002273 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002274
Douglas Gregorb10daed2010-10-11 16:52:23 +00002275 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002276}
2277CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2278 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002279 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002280 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002281 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002282 unsigned num_unsaved_files,
2283 unsigned options) {
2284 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002285 num_command_line_args, unsaved_files,
2286 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002287 llvm::CrashRecoveryContext CRC;
2288
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002289 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002290 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2291 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2292 fprintf(stderr, " 'command_line_args' : [");
2293 for (int i = 0; i != num_command_line_args; ++i) {
2294 if (i)
2295 fprintf(stderr, ", ");
2296 fprintf(stderr, "'%s'", command_line_args[i]);
2297 }
2298 fprintf(stderr, "],\n");
2299 fprintf(stderr, " 'unsaved_files' : [");
2300 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2301 if (i)
2302 fprintf(stderr, ", ");
2303 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2304 unsaved_files[i].Length);
2305 }
2306 fprintf(stderr, "],\n");
2307 fprintf(stderr, " 'options' : %d,\n", options);
2308 fprintf(stderr, "}\n");
2309
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002310 return 0;
2311 }
2312
2313 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002314}
2315
Douglas Gregor19998442010-08-13 15:35:05 +00002316unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2317 return CXSaveTranslationUnit_None;
2318}
2319
2320int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2321 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002322 if (!TU)
2323 return 1;
2324
2325 return static_cast<ASTUnit *>(TU)->Save(FileName);
2326}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002327
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002328void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002329 if (CTUnit) {
2330 // If the translation unit has been marked as unsafe to free, just discard
2331 // it.
2332 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2333 return;
2334
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002335 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002336 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002337}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002338
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002339unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2340 return CXReparse_None;
2341}
2342
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002343struct ReparseTranslationUnitInfo {
2344 CXTranslationUnit TU;
2345 unsigned num_unsaved_files;
2346 struct CXUnsavedFile *unsaved_files;
2347 unsigned options;
2348 int result;
2349};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002350
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002351static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002352 ReparseTranslationUnitInfo *RTUI =
2353 static_cast<ReparseTranslationUnitInfo*>(UserData);
2354 CXTranslationUnit TU = RTUI->TU;
2355 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2356 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2357 unsigned options = RTUI->options;
2358 (void) options;
2359 RTUI->result = 1;
2360
Douglas Gregorabc563f2010-07-19 21:46:24 +00002361 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002362 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002363
2364 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2365 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002366
2367 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2368 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2369 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2370 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002371 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002372 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2373 Buffer));
2374 }
2375
Douglas Gregor593b0c12010-09-23 18:47:53 +00002376 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2377 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002378}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002379
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002380int clang_reparseTranslationUnit(CXTranslationUnit TU,
2381 unsigned num_unsaved_files,
2382 struct CXUnsavedFile *unsaved_files,
2383 unsigned options) {
2384 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2385 options, 0 };
2386 llvm::CrashRecoveryContext CRC;
2387
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002388 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002389 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002390 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2391 return 1;
2392 }
2393
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002394
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002395 return RTUI.result;
2396}
2397
Douglas Gregordf95a132010-08-09 20:45:32 +00002398
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002399CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002400 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002401 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002402
Steve Naroff77accc12009-09-03 18:19:54 +00002403 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002404 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002405}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002406
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002407CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002408 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002409 return Result;
2410}
2411
Ted Kremenekfb480492010-01-13 21:46:36 +00002412} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002413
Ted Kremenekfb480492010-01-13 21:46:36 +00002414//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002415// CXSourceLocation and CXSourceRange Operations.
2416//===----------------------------------------------------------------------===//
2417
Douglas Gregorb9790342010-01-22 21:44:22 +00002418extern "C" {
2419CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002420 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002421 return Result;
2422}
2423
2424unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002425 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2426 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2427 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002428}
2429
2430CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2431 CXFile file,
2432 unsigned line,
2433 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002434 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002435 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002436
Douglas Gregorb9790342010-01-22 21:44:22 +00002437 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2438 SourceLocation SLoc
2439 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002440 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002441 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002442 if (SLoc.isInvalid()) return clang_getNullLocation();
2443
2444 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2445}
2446
2447CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2448 CXFile file,
2449 unsigned offset) {
2450 if (!tu || !file)
2451 return clang_getNullLocation();
2452
2453 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2454 SourceLocation Start
2455 = CXXUnit->getSourceManager().getLocation(
2456 static_cast<const FileEntry *>(file),
2457 1, 1);
2458 if (Start.isInvalid()) return clang_getNullLocation();
2459
2460 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2461
2462 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002463
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002464 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002465}
2466
Douglas Gregor5352ac02010-01-28 00:27:43 +00002467CXSourceRange clang_getNullRange() {
2468 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2469 return Result;
2470}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002471
Douglas Gregor5352ac02010-01-28 00:27:43 +00002472CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2473 if (begin.ptr_data[0] != end.ptr_data[0] ||
2474 begin.ptr_data[1] != end.ptr_data[1])
2475 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002476
2477 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002478 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002479 return Result;
2480}
2481
Douglas Gregor46766dc2010-01-26 19:19:08 +00002482void clang_getInstantiationLocation(CXSourceLocation location,
2483 CXFile *file,
2484 unsigned *line,
2485 unsigned *column,
2486 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002487 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2488
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002489 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002490 if (file)
2491 *file = 0;
2492 if (line)
2493 *line = 0;
2494 if (column)
2495 *column = 0;
2496 if (offset)
2497 *offset = 0;
2498 return;
2499 }
2500
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002501 const SourceManager &SM =
2502 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002503 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002504
2505 if (file)
2506 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2507 if (line)
2508 *line = SM.getInstantiationLineNumber(InstLoc);
2509 if (column)
2510 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002511 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002512 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002513}
2514
Douglas Gregora9b06d42010-11-09 06:24:54 +00002515void clang_getSpellingLocation(CXSourceLocation location,
2516 CXFile *file,
2517 unsigned *line,
2518 unsigned *column,
2519 unsigned *offset) {
2520 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2521
2522 if (!location.ptr_data[0] || Loc.isInvalid()) {
2523 if (file)
2524 *file = 0;
2525 if (line)
2526 *line = 0;
2527 if (column)
2528 *column = 0;
2529 if (offset)
2530 *offset = 0;
2531 return;
2532 }
2533
2534 const SourceManager &SM =
2535 *static_cast<const SourceManager*>(location.ptr_data[0]);
2536 SourceLocation SpellLoc = Loc;
2537 if (SpellLoc.isMacroID()) {
2538 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2539 if (SimpleSpellingLoc.isFileID() &&
2540 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2541 SpellLoc = SimpleSpellingLoc;
2542 else
2543 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2544 }
2545
2546 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2547 FileID FID = LocInfo.first;
2548 unsigned FileOffset = LocInfo.second;
2549
2550 if (file)
2551 *file = (void *)SM.getFileEntryForID(FID);
2552 if (line)
2553 *line = SM.getLineNumber(FID, FileOffset);
2554 if (column)
2555 *column = SM.getColumnNumber(FID, FileOffset);
2556 if (offset)
2557 *offset = FileOffset;
2558}
2559
Douglas Gregor1db19de2010-01-19 21:36:55 +00002560CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002561 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002562 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002563 return Result;
2564}
2565
2566CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002567 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002568 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002569 return Result;
2570}
2571
Douglas Gregorb9790342010-01-22 21:44:22 +00002572} // end: extern "C"
2573
Douglas Gregor1db19de2010-01-19 21:36:55 +00002574//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002575// CXFile Operations.
2576//===----------------------------------------------------------------------===//
2577
2578extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002579CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002580 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002581 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582
Steve Naroff88145032009-10-27 14:35:18 +00002583 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002584 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002585}
2586
2587time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002588 if (!SFile)
2589 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590
Steve Naroff88145032009-10-27 14:35:18 +00002591 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2592 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002593}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002594
Douglas Gregorb9790342010-01-22 21:44:22 +00002595CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2596 if (!tu)
2597 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Douglas Gregorb9790342010-01-22 21:44:22 +00002599 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002600
Douglas Gregorb9790342010-01-22 21:44:22 +00002601 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002602 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2603 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002604 return const_cast<FileEntry *>(File);
2605}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002606
Ted Kremenekfb480492010-01-13 21:46:36 +00002607} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002608
Ted Kremenekfb480492010-01-13 21:46:36 +00002609//===----------------------------------------------------------------------===//
2610// CXCursor Operations.
2611//===----------------------------------------------------------------------===//
2612
Ted Kremenekfb480492010-01-13 21:46:36 +00002613static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002614 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2615 return getDeclFromExpr(CE->getSubExpr());
2616
Ted Kremenekfb480492010-01-13 21:46:36 +00002617 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2618 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002619 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2620 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002621 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2622 return ME->getMemberDecl();
2623 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2624 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002625 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2626 return PRE->getProperty();
2627
Ted Kremenekfb480492010-01-13 21:46:36 +00002628 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2629 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002630 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2631 if (!CE->isElidable())
2632 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002633 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2634 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002635
Douglas Gregordb1314e2010-10-01 21:11:22 +00002636 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2637 return PE->getProtocol();
2638
Ted Kremenekfb480492010-01-13 21:46:36 +00002639 return 0;
2640}
2641
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002642static SourceLocation getLocationFromExpr(Expr *E) {
2643 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2644 return /*FIXME:*/Msg->getLeftLoc();
2645 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2646 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002647 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2648 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002649 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2650 return Member->getMemberLoc();
2651 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2652 return Ivar->getLocation();
2653 return E->getLocStart();
2654}
2655
Ted Kremenekfb480492010-01-13 21:46:36 +00002656extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002657
2658unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002659 CXCursorVisitor visitor,
2660 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002661 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002662
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002663 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2664 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002665 return CursorVis.VisitChildren(parent);
2666}
2667
David Chisnall3387c652010-11-03 14:12:26 +00002668#ifndef __has_feature
2669#define __has_feature(x) 0
2670#endif
2671#if __has_feature(blocks)
2672typedef enum CXChildVisitResult
2673 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2674
2675static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2676 CXClientData client_data) {
2677 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2678 return block(cursor, parent);
2679}
2680#else
2681// If we are compiled with a compiler that doesn't have native blocks support,
2682// define and call the block manually, so the
2683typedef struct _CXChildVisitResult
2684{
2685 void *isa;
2686 int flags;
2687 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002688 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2689 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002690} *CXCursorVisitorBlock;
2691
2692static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2693 CXClientData client_data) {
2694 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2695 return block->invoke(block, cursor, parent);
2696}
2697#endif
2698
2699
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002700unsigned clang_visitChildrenWithBlock(CXCursor parent,
2701 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002702 return clang_visitChildren(parent, visitWithBlock, block);
2703}
2704
Douglas Gregor78205d42010-01-20 21:45:58 +00002705static CXString getDeclSpelling(Decl *D) {
2706 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2707 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002708 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002709
Douglas Gregor78205d42010-01-20 21:45:58 +00002710 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002711 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002712
Douglas Gregor78205d42010-01-20 21:45:58 +00002713 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2714 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2715 // and returns different names. NamedDecl returns the class name and
2716 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002717 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002718
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002719 if (isa<UsingDirectiveDecl>(D))
2720 return createCXString("");
2721
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002722 llvm::SmallString<1024> S;
2723 llvm::raw_svector_ostream os(S);
2724 ND->printName(os);
2725
2726 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002727}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002728
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002729CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002730 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002731 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002732
Steve Narofff334b4e2009-09-02 18:26:48 +00002733 if (clang_isReference(C.kind)) {
2734 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002735 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002736 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002737 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002738 }
2739 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002740 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002741 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002742 }
2743 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002744 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002745 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002746 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002747 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002748 case CXCursor_CXXBaseSpecifier: {
2749 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2750 return createCXString(B->getType().getAsString());
2751 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002752 case CXCursor_TypeRef: {
2753 TypeDecl *Type = getCursorTypeRef(C).first;
2754 assert(Type && "Missing type decl");
2755
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002756 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2757 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002758 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002759 case CXCursor_TemplateRef: {
2760 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002761 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002762
2763 return createCXString(Template->getNameAsString());
2764 }
Douglas Gregor69319002010-08-31 23:48:11 +00002765
2766 case CXCursor_NamespaceRef: {
2767 NamedDecl *NS = getCursorNamespaceRef(C).first;
2768 assert(NS && "Missing namespace decl");
2769
2770 return createCXString(NS->getNameAsString());
2771 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002772
Douglas Gregora67e03f2010-09-09 21:42:20 +00002773 case CXCursor_MemberRef: {
2774 FieldDecl *Field = getCursorMemberRef(C).first;
2775 assert(Field && "Missing member decl");
2776
2777 return createCXString(Field->getNameAsString());
2778 }
2779
Douglas Gregor36897b02010-09-10 00:22:18 +00002780 case CXCursor_LabelRef: {
2781 LabelStmt *Label = getCursorLabelRef(C).first;
2782 assert(Label && "Missing label");
2783
2784 return createCXString(Label->getID()->getName());
2785 }
2786
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002787 case CXCursor_OverloadedDeclRef: {
2788 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2789 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2790 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2791 return createCXString(ND->getNameAsString());
2792 return createCXString("");
2793 }
2794 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2795 return createCXString(E->getName().getAsString());
2796 OverloadedTemplateStorage *Ovl
2797 = Storage.get<OverloadedTemplateStorage*>();
2798 if (Ovl->size() == 0)
2799 return createCXString("");
2800 return createCXString((*Ovl->begin())->getNameAsString());
2801 }
2802
Daniel Dunbaracca7252009-11-30 20:42:49 +00002803 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002804 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002805 }
2806 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002807
2808 if (clang_isExpression(C.kind)) {
2809 Decl *D = getDeclFromExpr(getCursorExpr(C));
2810 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002811 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002812 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002813 }
2814
Douglas Gregor36897b02010-09-10 00:22:18 +00002815 if (clang_isStatement(C.kind)) {
2816 Stmt *S = getCursorStmt(C);
2817 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2818 return createCXString(Label->getID()->getName());
2819
2820 return createCXString("");
2821 }
2822
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002823 if (C.kind == CXCursor_MacroInstantiation)
2824 return createCXString(getCursorMacroInstantiation(C)->getName()
2825 ->getNameStart());
2826
Douglas Gregor572feb22010-03-18 18:04:21 +00002827 if (C.kind == CXCursor_MacroDefinition)
2828 return createCXString(getCursorMacroDefinition(C)->getName()
2829 ->getNameStart());
2830
Douglas Gregorecdcb882010-10-20 22:00:55 +00002831 if (C.kind == CXCursor_InclusionDirective)
2832 return createCXString(getCursorInclusionDirective(C)->getFileName());
2833
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002834 if (clang_isDeclaration(C.kind))
2835 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002836
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002837 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002838}
2839
Douglas Gregor358559d2010-10-02 22:49:11 +00002840CXString clang_getCursorDisplayName(CXCursor C) {
2841 if (!clang_isDeclaration(C.kind))
2842 return clang_getCursorSpelling(C);
2843
2844 Decl *D = getCursorDecl(C);
2845 if (!D)
2846 return createCXString("");
2847
2848 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2849 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2850 D = FunTmpl->getTemplatedDecl();
2851
2852 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2853 llvm::SmallString<64> Str;
2854 llvm::raw_svector_ostream OS(Str);
2855 OS << Function->getNameAsString();
2856 if (Function->getPrimaryTemplate())
2857 OS << "<>";
2858 OS << "(";
2859 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2860 if (I)
2861 OS << ", ";
2862 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2863 }
2864
2865 if (Function->isVariadic()) {
2866 if (Function->getNumParams())
2867 OS << ", ";
2868 OS << "...";
2869 }
2870 OS << ")";
2871 return createCXString(OS.str());
2872 }
2873
2874 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2875 llvm::SmallString<64> Str;
2876 llvm::raw_svector_ostream OS(Str);
2877 OS << ClassTemplate->getNameAsString();
2878 OS << "<";
2879 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2880 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2881 if (I)
2882 OS << ", ";
2883
2884 NamedDecl *Param = Params->getParam(I);
2885 if (Param->getIdentifier()) {
2886 OS << Param->getIdentifier()->getName();
2887 continue;
2888 }
2889
2890 // There is no parameter name, which makes this tricky. Try to come up
2891 // with something useful that isn't too long.
2892 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2893 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2894 else if (NonTypeTemplateParmDecl *NTTP
2895 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2896 OS << NTTP->getType().getAsString(Policy);
2897 else
2898 OS << "template<...> class";
2899 }
2900
2901 OS << ">";
2902 return createCXString(OS.str());
2903 }
2904
2905 if (ClassTemplateSpecializationDecl *ClassSpec
2906 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2907 // If the type was explicitly written, use that.
2908 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2909 return createCXString(TSInfo->getType().getAsString(Policy));
2910
2911 llvm::SmallString<64> Str;
2912 llvm::raw_svector_ostream OS(Str);
2913 OS << ClassSpec->getNameAsString();
2914 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002915 ClassSpec->getTemplateArgs().data(),
2916 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002917 Policy);
2918 return createCXString(OS.str());
2919 }
2920
2921 return clang_getCursorSpelling(C);
2922}
2923
Ted Kremeneke68fff62010-02-17 00:41:32 +00002924CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002925 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002926 case CXCursor_FunctionDecl:
2927 return createCXString("FunctionDecl");
2928 case CXCursor_TypedefDecl:
2929 return createCXString("TypedefDecl");
2930 case CXCursor_EnumDecl:
2931 return createCXString("EnumDecl");
2932 case CXCursor_EnumConstantDecl:
2933 return createCXString("EnumConstantDecl");
2934 case CXCursor_StructDecl:
2935 return createCXString("StructDecl");
2936 case CXCursor_UnionDecl:
2937 return createCXString("UnionDecl");
2938 case CXCursor_ClassDecl:
2939 return createCXString("ClassDecl");
2940 case CXCursor_FieldDecl:
2941 return createCXString("FieldDecl");
2942 case CXCursor_VarDecl:
2943 return createCXString("VarDecl");
2944 case CXCursor_ParmDecl:
2945 return createCXString("ParmDecl");
2946 case CXCursor_ObjCInterfaceDecl:
2947 return createCXString("ObjCInterfaceDecl");
2948 case CXCursor_ObjCCategoryDecl:
2949 return createCXString("ObjCCategoryDecl");
2950 case CXCursor_ObjCProtocolDecl:
2951 return createCXString("ObjCProtocolDecl");
2952 case CXCursor_ObjCPropertyDecl:
2953 return createCXString("ObjCPropertyDecl");
2954 case CXCursor_ObjCIvarDecl:
2955 return createCXString("ObjCIvarDecl");
2956 case CXCursor_ObjCInstanceMethodDecl:
2957 return createCXString("ObjCInstanceMethodDecl");
2958 case CXCursor_ObjCClassMethodDecl:
2959 return createCXString("ObjCClassMethodDecl");
2960 case CXCursor_ObjCImplementationDecl:
2961 return createCXString("ObjCImplementationDecl");
2962 case CXCursor_ObjCCategoryImplDecl:
2963 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002964 case CXCursor_CXXMethod:
2965 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002966 case CXCursor_UnexposedDecl:
2967 return createCXString("UnexposedDecl");
2968 case CXCursor_ObjCSuperClassRef:
2969 return createCXString("ObjCSuperClassRef");
2970 case CXCursor_ObjCProtocolRef:
2971 return createCXString("ObjCProtocolRef");
2972 case CXCursor_ObjCClassRef:
2973 return createCXString("ObjCClassRef");
2974 case CXCursor_TypeRef:
2975 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002976 case CXCursor_TemplateRef:
2977 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002978 case CXCursor_NamespaceRef:
2979 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002980 case CXCursor_MemberRef:
2981 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002982 case CXCursor_LabelRef:
2983 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002984 case CXCursor_OverloadedDeclRef:
2985 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002986 case CXCursor_UnexposedExpr:
2987 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002988 case CXCursor_BlockExpr:
2989 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002990 case CXCursor_DeclRefExpr:
2991 return createCXString("DeclRefExpr");
2992 case CXCursor_MemberRefExpr:
2993 return createCXString("MemberRefExpr");
2994 case CXCursor_CallExpr:
2995 return createCXString("CallExpr");
2996 case CXCursor_ObjCMessageExpr:
2997 return createCXString("ObjCMessageExpr");
2998 case CXCursor_UnexposedStmt:
2999 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003000 case CXCursor_LabelStmt:
3001 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003002 case CXCursor_InvalidFile:
3003 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003004 case CXCursor_InvalidCode:
3005 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003006 case CXCursor_NoDeclFound:
3007 return createCXString("NoDeclFound");
3008 case CXCursor_NotImplemented:
3009 return createCXString("NotImplemented");
3010 case CXCursor_TranslationUnit:
3011 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003012 case CXCursor_UnexposedAttr:
3013 return createCXString("UnexposedAttr");
3014 case CXCursor_IBActionAttr:
3015 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003016 case CXCursor_IBOutletAttr:
3017 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003018 case CXCursor_IBOutletCollectionAttr:
3019 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003020 case CXCursor_PreprocessingDirective:
3021 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003022 case CXCursor_MacroDefinition:
3023 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003024 case CXCursor_MacroInstantiation:
3025 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003026 case CXCursor_InclusionDirective:
3027 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003028 case CXCursor_Namespace:
3029 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003030 case CXCursor_LinkageSpec:
3031 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003032 case CXCursor_CXXBaseSpecifier:
3033 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003034 case CXCursor_Constructor:
3035 return createCXString("CXXConstructor");
3036 case CXCursor_Destructor:
3037 return createCXString("CXXDestructor");
3038 case CXCursor_ConversionFunction:
3039 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003040 case CXCursor_TemplateTypeParameter:
3041 return createCXString("TemplateTypeParameter");
3042 case CXCursor_NonTypeTemplateParameter:
3043 return createCXString("NonTypeTemplateParameter");
3044 case CXCursor_TemplateTemplateParameter:
3045 return createCXString("TemplateTemplateParameter");
3046 case CXCursor_FunctionTemplate:
3047 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003048 case CXCursor_ClassTemplate:
3049 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003050 case CXCursor_ClassTemplatePartialSpecialization:
3051 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003052 case CXCursor_NamespaceAlias:
3053 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003054 case CXCursor_UsingDirective:
3055 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003056 case CXCursor_UsingDeclaration:
3057 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003058 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003059
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003060 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003061 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003062}
Steve Naroff89922f82009-08-31 00:59:03 +00003063
Ted Kremeneke68fff62010-02-17 00:41:32 +00003064enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3065 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003066 CXClientData client_data) {
3067 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003068
3069 // If our current best cursor is the construction of a temporary object,
3070 // don't replace that cursor with a type reference, because we want
3071 // clang_getCursor() to point at the constructor.
3072 if (clang_isExpression(BestCursor->kind) &&
3073 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3074 cursor.kind == CXCursor_TypeRef)
3075 return CXChildVisit_Recurse;
3076
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003077 *BestCursor = cursor;
3078 return CXChildVisit_Recurse;
3079}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003080
Douglas Gregorb9790342010-01-22 21:44:22 +00003081CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3082 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003083 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003084
Douglas Gregorb9790342010-01-22 21:44:22 +00003085 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003086 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3087
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003088 // Translate the given source location to make it point at the beginning of
3089 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003090 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003091
3092 // Guard against an invalid SourceLocation, or we may assert in one
3093 // of the following calls.
3094 if (SLoc.isInvalid())
3095 return clang_getNullCursor();
3096
Douglas Gregor40749ee2010-11-03 00:35:38 +00003097 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003098 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3099 CXXUnit->getASTContext().getLangOptions());
3100
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003101 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3102 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003103 // FIXME: Would be great to have a "hint" cursor, then walk from that
3104 // hint cursor upward until we find a cursor whose source range encloses
3105 // the region of interest, rather than starting from the translation unit.
3106 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003107 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003108 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003109 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003110 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003111
3112 if (Logging) {
3113 CXFile SearchFile;
3114 unsigned SearchLine, SearchColumn;
3115 CXFile ResultFile;
3116 unsigned ResultLine, ResultColumn;
3117 CXString SearchFileName, ResultFileName, KindSpelling;
3118 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3119
3120 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3121 0);
3122 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3123 &ResultColumn, 0);
3124 SearchFileName = clang_getFileName(SearchFile);
3125 ResultFileName = clang_getFileName(ResultFile);
3126 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3127 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3128 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3129 clang_getCString(KindSpelling),
3130 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3131 clang_disposeString(SearchFileName);
3132 clang_disposeString(ResultFileName);
3133 clang_disposeString(KindSpelling);
3134 }
3135
Ted Kremeneke68fff62010-02-17 00:41:32 +00003136 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003137}
3138
Ted Kremenek73885552009-11-17 19:28:59 +00003139CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003140 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003141}
3142
3143unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003144 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003145}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003146
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003147unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003148 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3149}
3150
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003151unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003152 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3153}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003154
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003155unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003156 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3157}
3158
Douglas Gregor97b98722010-01-19 23:20:36 +00003159unsigned clang_isExpression(enum CXCursorKind K) {
3160 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3161}
3162
3163unsigned clang_isStatement(enum CXCursorKind K) {
3164 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3165}
3166
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003167unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3168 return K == CXCursor_TranslationUnit;
3169}
3170
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003171unsigned clang_isPreprocessing(enum CXCursorKind K) {
3172 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3173}
3174
Ted Kremenekad6eff62010-03-08 21:17:29 +00003175unsigned clang_isUnexposed(enum CXCursorKind K) {
3176 switch (K) {
3177 case CXCursor_UnexposedDecl:
3178 case CXCursor_UnexposedExpr:
3179 case CXCursor_UnexposedStmt:
3180 case CXCursor_UnexposedAttr:
3181 return true;
3182 default:
3183 return false;
3184 }
3185}
3186
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003187CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003188 return C.kind;
3189}
3190
Douglas Gregor98258af2010-01-18 22:46:11 +00003191CXSourceLocation clang_getCursorLocation(CXCursor C) {
3192 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003193 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003194 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003195 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3196 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003197 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003198 }
3199
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003200 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003201 std::pair<ObjCProtocolDecl *, SourceLocation> P
3202 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003203 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003204 }
3205
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003206 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003207 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3208 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003209 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003210 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003211
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003212 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003213 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003214 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003215 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003216
3217 case CXCursor_TemplateRef: {
3218 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3219 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3220 }
3221
Douglas Gregor69319002010-08-31 23:48:11 +00003222 case CXCursor_NamespaceRef: {
3223 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3224 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3225 }
3226
Douglas Gregora67e03f2010-09-09 21:42:20 +00003227 case CXCursor_MemberRef: {
3228 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3229 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3230 }
3231
Ted Kremenek3064ef92010-08-27 21:34:58 +00003232 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003233 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3234 if (!BaseSpec)
3235 return clang_getNullLocation();
3236
3237 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3238 return cxloc::translateSourceLocation(getCursorContext(C),
3239 TSInfo->getTypeLoc().getBeginLoc());
3240
3241 return cxloc::translateSourceLocation(getCursorContext(C),
3242 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003243 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003244
Douglas Gregor36897b02010-09-10 00:22:18 +00003245 case CXCursor_LabelRef: {
3246 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3247 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3248 }
3249
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003250 case CXCursor_OverloadedDeclRef:
3251 return cxloc::translateSourceLocation(getCursorContext(C),
3252 getCursorOverloadedDeclRef(C).second);
3253
Douglas Gregorf46034a2010-01-18 23:41:10 +00003254 default:
3255 // FIXME: Need a way to enumerate all non-reference cases.
3256 llvm_unreachable("Missed a reference kind");
3257 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003258 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003259
3260 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003261 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003262 getLocationFromExpr(getCursorExpr(C)));
3263
Douglas Gregor36897b02010-09-10 00:22:18 +00003264 if (clang_isStatement(C.kind))
3265 return cxloc::translateSourceLocation(getCursorContext(C),
3266 getCursorStmt(C)->getLocStart());
3267
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003268 if (C.kind == CXCursor_PreprocessingDirective) {
3269 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3270 return cxloc::translateSourceLocation(getCursorContext(C), L);
3271 }
Douglas Gregor48072312010-03-18 15:23:44 +00003272
3273 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003274 SourceLocation L
3275 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003276 return cxloc::translateSourceLocation(getCursorContext(C), L);
3277 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003278
3279 if (C.kind == CXCursor_MacroDefinition) {
3280 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3281 return cxloc::translateSourceLocation(getCursorContext(C), L);
3282 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003283
3284 if (C.kind == CXCursor_InclusionDirective) {
3285 SourceLocation L
3286 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3287 return cxloc::translateSourceLocation(getCursorContext(C), L);
3288 }
3289
Ted Kremenek9a700d22010-05-12 06:16:13 +00003290 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003291 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003292
Douglas Gregorf46034a2010-01-18 23:41:10 +00003293 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003294 SourceLocation Loc = D->getLocation();
3295 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3296 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003297 // FIXME: Multiple variables declared in a single declaration
3298 // currently lack the information needed to correctly determine their
3299 // ranges when accounting for the type-specifier. We use context
3300 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3301 // and if so, whether it is the first decl.
3302 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3303 if (!cxcursor::isFirstInDeclGroup(C))
3304 Loc = VD->getLocation();
3305 }
3306
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003307 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003308}
Douglas Gregora7bde202010-01-19 00:34:46 +00003309
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003310} // end extern "C"
3311
3312static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003313 if (clang_isReference(C.kind)) {
3314 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003315 case CXCursor_ObjCSuperClassRef:
3316 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003317
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003318 case CXCursor_ObjCProtocolRef:
3319 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003320
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003321 case CXCursor_ObjCClassRef:
3322 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003323
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003324 case CXCursor_TypeRef:
3325 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003326
3327 case CXCursor_TemplateRef:
3328 return getCursorTemplateRef(C).second;
3329
Douglas Gregor69319002010-08-31 23:48:11 +00003330 case CXCursor_NamespaceRef:
3331 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003332
3333 case CXCursor_MemberRef:
3334 return getCursorMemberRef(C).second;
3335
Ted Kremenek3064ef92010-08-27 21:34:58 +00003336 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003337 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003338
Douglas Gregor36897b02010-09-10 00:22:18 +00003339 case CXCursor_LabelRef:
3340 return getCursorLabelRef(C).second;
3341
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003342 case CXCursor_OverloadedDeclRef:
3343 return getCursorOverloadedDeclRef(C).second;
3344
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003345 default:
3346 // FIXME: Need a way to enumerate all non-reference cases.
3347 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003348 }
3349 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003350
3351 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003352 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003353
3354 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003355 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003357 if (C.kind == CXCursor_PreprocessingDirective)
3358 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003359
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003360 if (C.kind == CXCursor_MacroInstantiation)
3361 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003362
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003363 if (C.kind == CXCursor_MacroDefinition)
3364 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003365
3366 if (C.kind == CXCursor_InclusionDirective)
3367 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3368
Ted Kremenek007a7c92010-11-01 23:26:51 +00003369 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3370 Decl *D = cxcursor::getCursorDecl(C);
3371 SourceRange R = D->getSourceRange();
3372 // FIXME: Multiple variables declared in a single declaration
3373 // currently lack the information needed to correctly determine their
3374 // ranges when accounting for the type-specifier. We use context
3375 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3376 // and if so, whether it is the first decl.
3377 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3378 if (!cxcursor::isFirstInDeclGroup(C))
3379 R.setBegin(VD->getLocation());
3380 }
3381 return R;
3382 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003383 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003384
3385extern "C" {
3386
3387CXSourceRange clang_getCursorExtent(CXCursor C) {
3388 SourceRange R = getRawCursorExtent(C);
3389 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003390 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003391
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003392 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003393}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003394
3395CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003396 if (clang_isInvalid(C.kind))
3397 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003398
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003399 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003400 if (clang_isDeclaration(C.kind)) {
3401 Decl *D = getCursorDecl(C);
3402 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3403 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3404 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3405 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3406 if (ObjCForwardProtocolDecl *Protocols
3407 = dyn_cast<ObjCForwardProtocolDecl>(D))
3408 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3409
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003410 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003411 }
3412
Douglas Gregor97b98722010-01-19 23:20:36 +00003413 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003414 Expr *E = getCursorExpr(C);
3415 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003416 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003417 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003418
3419 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3420 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3421
Douglas Gregor97b98722010-01-19 23:20:36 +00003422 return clang_getNullCursor();
3423 }
3424
Douglas Gregor36897b02010-09-10 00:22:18 +00003425 if (clang_isStatement(C.kind)) {
3426 Stmt *S = getCursorStmt(C);
3427 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3428 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3429 getCursorASTUnit(C));
3430
3431 return clang_getNullCursor();
3432 }
3433
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003434 if (C.kind == CXCursor_MacroInstantiation) {
3435 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3436 return MakeMacroDefinitionCursor(Def, CXXUnit);
3437 }
3438
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003439 if (!clang_isReference(C.kind))
3440 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003441
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003442 switch (C.kind) {
3443 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003444 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003445
3446 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003447 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003448
3449 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003450 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003451
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003452 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003453 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003454
3455 case CXCursor_TemplateRef:
3456 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3457
Douglas Gregor69319002010-08-31 23:48:11 +00003458 case CXCursor_NamespaceRef:
3459 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3460
Douglas Gregora67e03f2010-09-09 21:42:20 +00003461 case CXCursor_MemberRef:
3462 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3463
Ted Kremenek3064ef92010-08-27 21:34:58 +00003464 case CXCursor_CXXBaseSpecifier: {
3465 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3466 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3467 CXXUnit));
3468 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003469
Douglas Gregor36897b02010-09-10 00:22:18 +00003470 case CXCursor_LabelRef:
3471 // FIXME: We end up faking the "parent" declaration here because we
3472 // don't want to make CXCursor larger.
3473 return MakeCXCursor(getCursorLabelRef(C).first,
3474 CXXUnit->getASTContext().getTranslationUnitDecl(),
3475 CXXUnit);
3476
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003477 case CXCursor_OverloadedDeclRef:
3478 return C;
3479
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003480 default:
3481 // We would prefer to enumerate all non-reference cursor kinds here.
3482 llvm_unreachable("Unhandled reference cursor kind");
3483 break;
3484 }
3485 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003486
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003487 return clang_getNullCursor();
3488}
3489
Douglas Gregorb6998662010-01-19 19:34:47 +00003490CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003491 if (clang_isInvalid(C.kind))
3492 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003493
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003494 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003495
Douglas Gregorb6998662010-01-19 19:34:47 +00003496 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003497 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003498 C = clang_getCursorReferenced(C);
3499 WasReference = true;
3500 }
3501
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003502 if (C.kind == CXCursor_MacroInstantiation)
3503 return clang_getCursorReferenced(C);
3504
Douglas Gregorb6998662010-01-19 19:34:47 +00003505 if (!clang_isDeclaration(C.kind))
3506 return clang_getNullCursor();
3507
3508 Decl *D = getCursorDecl(C);
3509 if (!D)
3510 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003511
Douglas Gregorb6998662010-01-19 19:34:47 +00003512 switch (D->getKind()) {
3513 // Declaration kinds that don't really separate the notions of
3514 // declaration and definition.
3515 case Decl::Namespace:
3516 case Decl::Typedef:
3517 case Decl::TemplateTypeParm:
3518 case Decl::EnumConstant:
3519 case Decl::Field:
3520 case Decl::ObjCIvar:
3521 case Decl::ObjCAtDefsField:
3522 case Decl::ImplicitParam:
3523 case Decl::ParmVar:
3524 case Decl::NonTypeTemplateParm:
3525 case Decl::TemplateTemplateParm:
3526 case Decl::ObjCCategoryImpl:
3527 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003528 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003529 case Decl::LinkageSpec:
3530 case Decl::ObjCPropertyImpl:
3531 case Decl::FileScopeAsm:
3532 case Decl::StaticAssert:
3533 case Decl::Block:
3534 return C;
3535
3536 // Declaration kinds that don't make any sense here, but are
3537 // nonetheless harmless.
3538 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003539 break;
3540
3541 // Declaration kinds for which the definition is not resolvable.
3542 case Decl::UnresolvedUsingTypename:
3543 case Decl::UnresolvedUsingValue:
3544 break;
3545
3546 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003547 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3548 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003549
3550 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003551 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003552
3553 case Decl::Enum:
3554 case Decl::Record:
3555 case Decl::CXXRecord:
3556 case Decl::ClassTemplateSpecialization:
3557 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003558 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003559 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003560 return clang_getNullCursor();
3561
3562 case Decl::Function:
3563 case Decl::CXXMethod:
3564 case Decl::CXXConstructor:
3565 case Decl::CXXDestructor:
3566 case Decl::CXXConversion: {
3567 const FunctionDecl *Def = 0;
3568 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003569 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003570 return clang_getNullCursor();
3571 }
3572
3573 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003574 // Ask the variable if it has a definition.
3575 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3576 return MakeCXCursor(Def, CXXUnit);
3577 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003579
Douglas Gregorb6998662010-01-19 19:34:47 +00003580 case Decl::FunctionTemplate: {
3581 const FunctionDecl *Def = 0;
3582 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003583 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003584 return clang_getNullCursor();
3585 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003586
Douglas Gregorb6998662010-01-19 19:34:47 +00003587 case Decl::ClassTemplate: {
3588 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003589 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003590 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003591 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003592 return clang_getNullCursor();
3593 }
3594
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003595 case Decl::Using:
3596 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3597 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003598
3599 case Decl::UsingShadow:
3600 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003601 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003602 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003603
3604 case Decl::ObjCMethod: {
3605 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3606 if (Method->isThisDeclarationADefinition())
3607 return C;
3608
3609 // Dig out the method definition in the associated
3610 // @implementation, if we have it.
3611 // FIXME: The ASTs should make finding the definition easier.
3612 if (ObjCInterfaceDecl *Class
3613 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3614 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3615 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3616 Method->isInstanceMethod()))
3617 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003618 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003619
3620 return clang_getNullCursor();
3621 }
3622
3623 case Decl::ObjCCategory:
3624 if (ObjCCategoryImplDecl *Impl
3625 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003626 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003627 return clang_getNullCursor();
3628
3629 case Decl::ObjCProtocol:
3630 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3631 return C;
3632 return clang_getNullCursor();
3633
3634 case Decl::ObjCInterface:
3635 // There are two notions of a "definition" for an Objective-C
3636 // class: the interface and its implementation. When we resolved a
3637 // reference to an Objective-C class, produce the @interface as
3638 // the definition; when we were provided with the interface,
3639 // produce the @implementation as the definition.
3640 if (WasReference) {
3641 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3642 return C;
3643 } else if (ObjCImplementationDecl *Impl
3644 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003645 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003646 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003647
Douglas Gregorb6998662010-01-19 19:34:47 +00003648 case Decl::ObjCProperty:
3649 // FIXME: We don't really know where to find the
3650 // ObjCPropertyImplDecls that implement this property.
3651 return clang_getNullCursor();
3652
3653 case Decl::ObjCCompatibleAlias:
3654 if (ObjCInterfaceDecl *Class
3655 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3656 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003657 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003658
Douglas Gregorb6998662010-01-19 19:34:47 +00003659 return clang_getNullCursor();
3660
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003661 case Decl::ObjCForwardProtocol:
3662 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3663 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003664
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003665 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003666 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003667 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003668
3669 case Decl::Friend:
3670 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003671 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003672 return clang_getNullCursor();
3673
3674 case Decl::FriendTemplate:
3675 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003676 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003677 return clang_getNullCursor();
3678 }
3679
3680 return clang_getNullCursor();
3681}
3682
3683unsigned clang_isCursorDefinition(CXCursor C) {
3684 if (!clang_isDeclaration(C.kind))
3685 return 0;
3686
3687 return clang_getCursorDefinition(C) == C;
3688}
3689
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003690unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003691 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003692 return 0;
3693
3694 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3695 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3696 return E->getNumDecls();
3697
3698 if (OverloadedTemplateStorage *S
3699 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3700 return S->size();
3701
3702 Decl *D = Storage.get<Decl*>();
3703 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003704 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003705 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3706 return Classes->size();
3707 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3708 return Protocols->protocol_size();
3709
3710 return 0;
3711}
3712
3713CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003714 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003715 return clang_getNullCursor();
3716
3717 if (index >= clang_getNumOverloadedDecls(cursor))
3718 return clang_getNullCursor();
3719
3720 ASTUnit *Unit = getCursorASTUnit(cursor);
3721 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3722 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3723 return MakeCXCursor(E->decls_begin()[index], Unit);
3724
3725 if (OverloadedTemplateStorage *S
3726 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3727 return MakeCXCursor(S->begin()[index], Unit);
3728
3729 Decl *D = Storage.get<Decl*>();
3730 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3731 // FIXME: This is, unfortunately, linear time.
3732 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3733 std::advance(Pos, index);
3734 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3735 }
3736
3737 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3738 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3739
3740 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3741 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3742
3743 return clang_getNullCursor();
3744}
3745
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003746void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003747 const char **startBuf,
3748 const char **endBuf,
3749 unsigned *startLine,
3750 unsigned *startColumn,
3751 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003752 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003753 assert(getCursorDecl(C) && "CXCursor has null decl");
3754 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003755 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3756 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003757
Steve Naroff4ade6d62009-09-23 17:52:52 +00003758 SourceManager &SM = FD->getASTContext().getSourceManager();
3759 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3760 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3761 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3762 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3763 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3764 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3765}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003766
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003767void clang_enableStackTraces(void) {
3768 llvm::sys::PrintStackTraceOnErrorSignal();
3769}
3770
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003771void clang_executeOnThread(void (*fn)(void*), void *user_data,
3772 unsigned stack_size) {
3773 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3774}
3775
Ted Kremenekfb480492010-01-13 21:46:36 +00003776} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003777
Ted Kremenekfb480492010-01-13 21:46:36 +00003778//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003779// Token-based Operations.
3780//===----------------------------------------------------------------------===//
3781
3782/* CXToken layout:
3783 * int_data[0]: a CXTokenKind
3784 * int_data[1]: starting token location
3785 * int_data[2]: token length
3786 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003787 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003788 * otherwise unused.
3789 */
3790extern "C" {
3791
3792CXTokenKind clang_getTokenKind(CXToken CXTok) {
3793 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3794}
3795
3796CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3797 switch (clang_getTokenKind(CXTok)) {
3798 case CXToken_Identifier:
3799 case CXToken_Keyword:
3800 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003801 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3802 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003803
3804 case CXToken_Literal: {
3805 // We have stashed the starting pointer in the ptr_data field. Use it.
3806 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003807 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003808 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003809
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003810 case CXToken_Punctuation:
3811 case CXToken_Comment:
3812 break;
3813 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003814
3815 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003816 // deconstructing the source location.
3817 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3818 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003819 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003820
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003821 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3822 std::pair<FileID, unsigned> LocInfo
3823 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003824 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003825 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003826 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3827 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003828 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003829
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003830 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003831}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003833CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3834 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3835 if (!CXXUnit)
3836 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003837
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003838 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3839 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3840}
3841
3842CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3843 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003844 if (!CXXUnit)
3845 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
3847 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003848 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3849}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003850
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003851void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3852 CXToken **Tokens, unsigned *NumTokens) {
3853 if (Tokens)
3854 *Tokens = 0;
3855 if (NumTokens)
3856 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003857
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003858 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3859 if (!CXXUnit || !Tokens || !NumTokens)
3860 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003861
Douglas Gregorbdf60622010-03-05 21:16:25 +00003862 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3863
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003864 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003865 if (R.isInvalid())
3866 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003867
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003868 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3869 std::pair<FileID, unsigned> BeginLocInfo
3870 = SourceMgr.getDecomposedLoc(R.getBegin());
3871 std::pair<FileID, unsigned> EndLocInfo
3872 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003873
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 // Cannot tokenize across files.
3875 if (BeginLocInfo.first != EndLocInfo.first)
3876 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003877
3878 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003879 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003880 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003881 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003882 if (Invalid)
3883 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003884
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003885 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3886 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003887 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003888 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003889
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003891 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003892 llvm::SmallVector<CXToken, 32> CXTokens;
3893 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003894 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895 do {
3896 // Lex the next token
3897 Lex.LexFromRawLexer(Tok);
3898 if (Tok.is(tok::eof))
3899 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003900
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003901 // Initialize the CXToken.
3902 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003903
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003904 // - Common fields
3905 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3906 CXTok.int_data[2] = Tok.getLength();
3907 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003908
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003909 // - Kind-specific fields
3910 if (Tok.isLiteral()) {
3911 CXTok.int_data[0] = CXToken_Literal;
3912 CXTok.ptr_data = (void *)Tok.getLiteralData();
3913 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003914 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003915 std::pair<FileID, unsigned> LocInfo
3916 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003917 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003918 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003919 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3920 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003921 return;
3922
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003923 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003924 IdentifierInfo *II
3925 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003926
David Chisnall096428b2010-10-13 21:44:48 +00003927 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003928 CXTok.int_data[0] = CXToken_Keyword;
3929 }
3930 else {
3931 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3932 CXToken_Identifier
3933 : CXToken_Keyword;
3934 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003935 CXTok.ptr_data = II;
3936 } else if (Tok.is(tok::comment)) {
3937 CXTok.int_data[0] = CXToken_Comment;
3938 CXTok.ptr_data = 0;
3939 } else {
3940 CXTok.int_data[0] = CXToken_Punctuation;
3941 CXTok.ptr_data = 0;
3942 }
3943 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003944 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003945 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003946
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003947 if (CXTokens.empty())
3948 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003949
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003950 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3951 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3952 *NumTokens = CXTokens.size();
3953}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003954
Ted Kremenek6db61092010-05-05 00:55:15 +00003955void clang_disposeTokens(CXTranslationUnit TU,
3956 CXToken *Tokens, unsigned NumTokens) {
3957 free(Tokens);
3958}
3959
3960} // end: extern "C"
3961
3962//===----------------------------------------------------------------------===//
3963// Token annotation APIs.
3964//===----------------------------------------------------------------------===//
3965
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003966typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003967static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3968 CXCursor parent,
3969 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003970namespace {
3971class AnnotateTokensWorker {
3972 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003973 CXToken *Tokens;
3974 CXCursor *Cursors;
3975 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003976 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003977 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003978 CursorVisitor AnnotateVis;
3979 SourceManager &SrcMgr;
3980
3981 bool MoreTokens() const { return TokIdx < NumTokens; }
3982 unsigned NextToken() const { return TokIdx; }
3983 void AdvanceToken() { ++TokIdx; }
3984 SourceLocation GetTokenLoc(unsigned tokI) {
3985 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3986 }
3987
Ted Kremenek6db61092010-05-05 00:55:15 +00003988public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003989 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003990 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3991 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003992 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003993 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003994 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3995 Decl::MaxPCHLevel, RegionOfInterest),
3996 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003997
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003998 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003999 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004000 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00004001};
4002}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004003
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4005 // Walk the AST within the region of interest, annotating tokens
4006 // along the way.
4007 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004008
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004009 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4010 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004011 if (Pos != Annotated.end() &&
4012 (clang_isInvalid(Cursors[I].kind) ||
4013 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004014 Cursors[I] = Pos->second;
4015 }
4016
4017 // Finish up annotating any tokens left.
4018 if (!MoreTokens())
4019 return;
4020
4021 const CXCursor &C = clang_getNullCursor();
4022 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4023 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4024 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004025 }
4026}
4027
Ted Kremenek6db61092010-05-05 00:55:15 +00004028enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004029AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004030 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004031 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004032 if (cursorRange.isInvalid())
4033 return CXChildVisit_Recurse;
4034
Douglas Gregor4419b672010-10-21 06:10:04 +00004035 if (clang_isPreprocessing(cursor.kind)) {
4036 // For macro instantiations, just note where the beginning of the macro
4037 // instantiation occurs.
4038 if (cursor.kind == CXCursor_MacroInstantiation) {
4039 Annotated[Loc.int_data] = cursor;
4040 return CXChildVisit_Recurse;
4041 }
4042
Douglas Gregor4419b672010-10-21 06:10:04 +00004043 // Items in the preprocessing record are kept separate from items in
4044 // declarations, so we keep a separate token index.
4045 unsigned SavedTokIdx = TokIdx;
4046 TokIdx = PreprocessingTokIdx;
4047
4048 // Skip tokens up until we catch up to the beginning of the preprocessing
4049 // entry.
4050 while (MoreTokens()) {
4051 const unsigned I = NextToken();
4052 SourceLocation TokLoc = GetTokenLoc(I);
4053 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4054 case RangeBefore:
4055 AdvanceToken();
4056 continue;
4057 case RangeAfter:
4058 case RangeOverlap:
4059 break;
4060 }
4061 break;
4062 }
4063
4064 // Look at all of the tokens within this range.
4065 while (MoreTokens()) {
4066 const unsigned I = NextToken();
4067 SourceLocation TokLoc = GetTokenLoc(I);
4068 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4069 case RangeBefore:
4070 assert(0 && "Infeasible");
4071 case RangeAfter:
4072 break;
4073 case RangeOverlap:
4074 Cursors[I] = cursor;
4075 AdvanceToken();
4076 continue;
4077 }
4078 break;
4079 }
4080
4081 // Save the preprocessing token index; restore the non-preprocessing
4082 // token index.
4083 PreprocessingTokIdx = TokIdx;
4084 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004085 return CXChildVisit_Recurse;
4086 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004087
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004088 if (cursorRange.isInvalid())
4089 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004090
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004091 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4092
Ted Kremeneka333c662010-05-12 05:29:33 +00004093 // Adjust the annotated range based specific declarations.
4094 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4095 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004096 Decl *D = cxcursor::getCursorDecl(cursor);
4097 // Don't visit synthesized ObjC methods, since they have no syntatic
4098 // representation in the source.
4099 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4100 if (MD->isSynthesized())
4101 return CXChildVisit_Continue;
4102 }
4103 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004104 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4105 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004106 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004107 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004108 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004109 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004110 }
4111 }
4112 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004113
Ted Kremenek3f404602010-08-14 01:14:06 +00004114 // If the location of the cursor occurs within a macro instantiation, record
4115 // the spelling location of the cursor in our annotation map. We can then
4116 // paper over the token labelings during a post-processing step to try and
4117 // get cursor mappings for tokens that are the *arguments* of a macro
4118 // instantiation.
4119 if (L.isMacroID()) {
4120 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4121 // Only invalidate the old annotation if it isn't part of a preprocessing
4122 // directive. Here we assume that the default construction of CXCursor
4123 // results in CXCursor.kind being an initialized value (i.e., 0). If
4124 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004125
Ted Kremenek3f404602010-08-14 01:14:06 +00004126 CXCursor &oldC = Annotated[rawEncoding];
4127 if (!clang_isPreprocessing(oldC.kind))
4128 oldC = cursor;
4129 }
4130
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004131 const enum CXCursorKind K = clang_getCursorKind(parent);
4132 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004133 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4134 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004135
4136 while (MoreTokens()) {
4137 const unsigned I = NextToken();
4138 SourceLocation TokLoc = GetTokenLoc(I);
4139 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4140 case RangeBefore:
4141 Cursors[I] = updateC;
4142 AdvanceToken();
4143 continue;
4144 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004145 case RangeOverlap:
4146 break;
4147 }
4148 break;
4149 }
4150
4151 // Visit children to get their cursor information.
4152 const unsigned BeforeChildren = NextToken();
4153 VisitChildren(cursor);
4154 const unsigned AfterChildren = NextToken();
4155
4156 // Adjust 'Last' to the last token within the extent of the cursor.
4157 while (MoreTokens()) {
4158 const unsigned I = NextToken();
4159 SourceLocation TokLoc = GetTokenLoc(I);
4160 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4161 case RangeBefore:
4162 assert(0 && "Infeasible");
4163 case RangeAfter:
4164 break;
4165 case RangeOverlap:
4166 Cursors[I] = updateC;
4167 AdvanceToken();
4168 continue;
4169 }
4170 break;
4171 }
4172 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004173
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004174 // Scan the tokens that are at the beginning of the cursor, but are not
4175 // capture by the child cursors.
4176
4177 // For AST elements within macros, rely on a post-annotate pass to
4178 // to correctly annotate the tokens with cursors. Otherwise we can
4179 // get confusing results of having tokens that map to cursors that really
4180 // are expanded by an instantiation.
4181 if (L.isMacroID())
4182 cursor = clang_getNullCursor();
4183
4184 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4185 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4186 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004187
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004188 Cursors[I] = cursor;
4189 }
4190 // Scan the tokens that are at the end of the cursor, but are not captured
4191 // but the child cursors.
4192 for (unsigned I = AfterChildren; I != Last; ++I)
4193 Cursors[I] = cursor;
4194
4195 TokIdx = Last;
4196 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004197}
4198
Ted Kremenek6db61092010-05-05 00:55:15 +00004199static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4200 CXCursor parent,
4201 CXClientData client_data) {
4202 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4203}
4204
4205extern "C" {
4206
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004207void clang_annotateTokens(CXTranslationUnit TU,
4208 CXToken *Tokens, unsigned NumTokens,
4209 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004210
4211 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004212 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004213
Douglas Gregor4419b672010-10-21 06:10:04 +00004214 // Any token we don't specifically annotate will have a NULL cursor.
4215 CXCursor C = clang_getNullCursor();
4216 for (unsigned I = 0; I != NumTokens; ++I)
4217 Cursors[I] = C;
4218
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004219 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004220 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004221 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004222
Douglas Gregorbdf60622010-03-05 21:16:25 +00004223 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004224
Douglas Gregor0396f462010-03-19 05:22:59 +00004225 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004226 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4228 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004229 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4230 clang_getTokenLocation(TU,
4231 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232
Douglas Gregor0396f462010-03-19 05:22:59 +00004233 // A mapping from the source locations found when re-lexing or traversing the
4234 // region of interest to the corresponding cursors.
4235 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004236
4237 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004238 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004239 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4240 std::pair<FileID, unsigned> BeginLocInfo
4241 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4242 std::pair<FileID, unsigned> EndLocInfo
4243 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004244
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004246 bool Invalid = false;
4247 if (BeginLocInfo.first == EndLocInfo.first &&
4248 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4249 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004250 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4251 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004253 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004254 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004255
4256 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004257 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004258 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004259 Token Tok;
4260 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004261
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004262 reprocess:
4263 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4264 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004265 // don't see it while preprocessing these tokens later, but keep track
4266 // of all of the token locations inside this preprocessing directive so
4267 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004268 //
4269 // FIXME: Some simple tests here could identify macro definitions and
4270 // #undefs, to provide specific cursor kinds for those.
4271 std::vector<SourceLocation> Locations;
4272 do {
4273 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004274 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004275 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004276
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004277 using namespace cxcursor;
4278 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4280 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004281 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004282 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4283 Annotated[Locations[I].getRawEncoding()] = Cursor;
4284 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004286 if (Tok.isAtStartOfLine())
4287 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004288
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004289 continue;
4290 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004291
Douglas Gregor48072312010-03-18 15:23:44 +00004292 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004293 break;
4294 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004295 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004296
Douglas Gregor0396f462010-03-19 05:22:59 +00004297 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004298 // a specific cursor.
4299 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4300 CXXUnit, RegionOfInterest);
4301 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004302}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004303} // end: extern "C"
4304
4305//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004306// Operations for querying linkage of a cursor.
4307//===----------------------------------------------------------------------===//
4308
4309extern "C" {
4310CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004311 if (!clang_isDeclaration(cursor.kind))
4312 return CXLinkage_Invalid;
4313
Ted Kremenek16b42592010-03-03 06:36:57 +00004314 Decl *D = cxcursor::getCursorDecl(cursor);
4315 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4316 switch (ND->getLinkage()) {
4317 case NoLinkage: return CXLinkage_NoLinkage;
4318 case InternalLinkage: return CXLinkage_Internal;
4319 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4320 case ExternalLinkage: return CXLinkage_External;
4321 };
4322
4323 return CXLinkage_Invalid;
4324}
4325} // end: extern "C"
4326
4327//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004328// Operations for querying language of a cursor.
4329//===----------------------------------------------------------------------===//
4330
4331static CXLanguageKind getDeclLanguage(const Decl *D) {
4332 switch (D->getKind()) {
4333 default:
4334 break;
4335 case Decl::ImplicitParam:
4336 case Decl::ObjCAtDefsField:
4337 case Decl::ObjCCategory:
4338 case Decl::ObjCCategoryImpl:
4339 case Decl::ObjCClass:
4340 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004341 case Decl::ObjCForwardProtocol:
4342 case Decl::ObjCImplementation:
4343 case Decl::ObjCInterface:
4344 case Decl::ObjCIvar:
4345 case Decl::ObjCMethod:
4346 case Decl::ObjCProperty:
4347 case Decl::ObjCPropertyImpl:
4348 case Decl::ObjCProtocol:
4349 return CXLanguage_ObjC;
4350 case Decl::CXXConstructor:
4351 case Decl::CXXConversion:
4352 case Decl::CXXDestructor:
4353 case Decl::CXXMethod:
4354 case Decl::CXXRecord:
4355 case Decl::ClassTemplate:
4356 case Decl::ClassTemplatePartialSpecialization:
4357 case Decl::ClassTemplateSpecialization:
4358 case Decl::Friend:
4359 case Decl::FriendTemplate:
4360 case Decl::FunctionTemplate:
4361 case Decl::LinkageSpec:
4362 case Decl::Namespace:
4363 case Decl::NamespaceAlias:
4364 case Decl::NonTypeTemplateParm:
4365 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004366 case Decl::TemplateTemplateParm:
4367 case Decl::TemplateTypeParm:
4368 case Decl::UnresolvedUsingTypename:
4369 case Decl::UnresolvedUsingValue:
4370 case Decl::Using:
4371 case Decl::UsingDirective:
4372 case Decl::UsingShadow:
4373 return CXLanguage_CPlusPlus;
4374 }
4375
4376 return CXLanguage_C;
4377}
4378
4379extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004380
4381enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4382 if (clang_isDeclaration(cursor.kind))
4383 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4384 if (D->hasAttr<UnavailableAttr>() ||
4385 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4386 return CXAvailability_Available;
4387
4388 if (D->hasAttr<DeprecatedAttr>())
4389 return CXAvailability_Deprecated;
4390 }
4391
4392 return CXAvailability_Available;
4393}
4394
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004395CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4396 if (clang_isDeclaration(cursor.kind))
4397 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4398
4399 return CXLanguage_Invalid;
4400}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004401
4402CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4403 if (clang_isDeclaration(cursor.kind)) {
4404 if (Decl *D = getCursorDecl(cursor)) {
4405 DeclContext *DC = D->getDeclContext();
4406 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4407 }
4408 }
4409
4410 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4411 if (Decl *D = getCursorDecl(cursor))
4412 return MakeCXCursor(D, getCursorASTUnit(cursor));
4413 }
4414
4415 return clang_getNullCursor();
4416}
4417
4418CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4419 if (clang_isDeclaration(cursor.kind)) {
4420 if (Decl *D = getCursorDecl(cursor)) {
4421 DeclContext *DC = D->getLexicalDeclContext();
4422 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4423 }
4424 }
4425
4426 // FIXME: Note that we can't easily compute the lexical context of a
4427 // statement or expression, so we return nothing.
4428 return clang_getNullCursor();
4429}
4430
Douglas Gregor9f592342010-10-01 20:25:15 +00004431static void CollectOverriddenMethods(DeclContext *Ctx,
4432 ObjCMethodDecl *Method,
4433 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4434 if (!Ctx)
4435 return;
4436
4437 // If we have a class or category implementation, jump straight to the
4438 // interface.
4439 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4440 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4441
4442 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4443 if (!Container)
4444 return;
4445
4446 // Check whether we have a matching method at this level.
4447 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4448 Method->isInstanceMethod()))
4449 if (Method != Overridden) {
4450 // We found an override at this level; there is no need to look
4451 // into other protocols or categories.
4452 Methods.push_back(Overridden);
4453 return;
4454 }
4455
4456 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4457 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4458 PEnd = Protocol->protocol_end();
4459 P != PEnd; ++P)
4460 CollectOverriddenMethods(*P, Method, Methods);
4461 }
4462
4463 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4464 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4465 PEnd = Category->protocol_end();
4466 P != PEnd; ++P)
4467 CollectOverriddenMethods(*P, Method, Methods);
4468 }
4469
4470 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4471 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4472 PEnd = Interface->protocol_end();
4473 P != PEnd; ++P)
4474 CollectOverriddenMethods(*P, Method, Methods);
4475
4476 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4477 Category; Category = Category->getNextClassCategory())
4478 CollectOverriddenMethods(Category, Method, Methods);
4479
4480 // We only look into the superclass if we haven't found anything yet.
4481 if (Methods.empty())
4482 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4483 return CollectOverriddenMethods(Super, Method, Methods);
4484 }
4485}
4486
4487void clang_getOverriddenCursors(CXCursor cursor,
4488 CXCursor **overridden,
4489 unsigned *num_overridden) {
4490 if (overridden)
4491 *overridden = 0;
4492 if (num_overridden)
4493 *num_overridden = 0;
4494 if (!overridden || !num_overridden)
4495 return;
4496
4497 if (!clang_isDeclaration(cursor.kind))
4498 return;
4499
4500 Decl *D = getCursorDecl(cursor);
4501 if (!D)
4502 return;
4503
4504 // Handle C++ member functions.
4505 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4506 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4507 *num_overridden = CXXMethod->size_overridden_methods();
4508 if (!*num_overridden)
4509 return;
4510
4511 *overridden = new CXCursor [*num_overridden];
4512 unsigned I = 0;
4513 for (CXXMethodDecl::method_iterator
4514 M = CXXMethod->begin_overridden_methods(),
4515 MEnd = CXXMethod->end_overridden_methods();
4516 M != MEnd; (void)++M, ++I)
4517 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4518 return;
4519 }
4520
4521 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4522 if (!Method)
4523 return;
4524
4525 // Handle Objective-C methods.
4526 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4527 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4528
4529 if (Methods.empty())
4530 return;
4531
4532 *num_overridden = Methods.size();
4533 *overridden = new CXCursor [Methods.size()];
4534 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4535 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4536}
4537
4538void clang_disposeOverriddenCursors(CXCursor *overridden) {
4539 delete [] overridden;
4540}
4541
Douglas Gregorecdcb882010-10-20 22:00:55 +00004542CXFile clang_getIncludedFile(CXCursor cursor) {
4543 if (cursor.kind != CXCursor_InclusionDirective)
4544 return 0;
4545
4546 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4547 return (void *)ID->getFile();
4548}
4549
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004550} // end: extern "C"
4551
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004552
4553//===----------------------------------------------------------------------===//
4554// C++ AST instrospection.
4555//===----------------------------------------------------------------------===//
4556
4557extern "C" {
4558unsigned clang_CXXMethod_isStatic(CXCursor C) {
4559 if (!clang_isDeclaration(C.kind))
4560 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004561
4562 CXXMethodDecl *Method = 0;
4563 Decl *D = cxcursor::getCursorDecl(C);
4564 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4565 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4566 else
4567 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4568 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004569}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004570
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004571} // end: extern "C"
4572
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004573//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004574// Attribute introspection.
4575//===----------------------------------------------------------------------===//
4576
4577extern "C" {
4578CXType clang_getIBOutletCollectionType(CXCursor C) {
4579 if (C.kind != CXCursor_IBOutletCollectionAttr)
4580 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4581
4582 IBOutletCollectionAttr *A =
4583 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4584
4585 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4586}
4587} // end: extern "C"
4588
4589//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004590// CXString Operations.
4591//===----------------------------------------------------------------------===//
4592
4593extern "C" {
4594const char *clang_getCString(CXString string) {
4595 return string.Spelling;
4596}
4597
4598void clang_disposeString(CXString string) {
4599 if (string.MustFreeString && string.Spelling)
4600 free((void*)string.Spelling);
4601}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004602
Ted Kremenekfb480492010-01-13 21:46:36 +00004603} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004604
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004605namespace clang { namespace cxstring {
4606CXString createCXString(const char *String, bool DupString){
4607 CXString Str;
4608 if (DupString) {
4609 Str.Spelling = strdup(String);
4610 Str.MustFreeString = 1;
4611 } else {
4612 Str.Spelling = String;
4613 Str.MustFreeString = 0;
4614 }
4615 return Str;
4616}
4617
4618CXString createCXString(llvm::StringRef String, bool DupString) {
4619 CXString Result;
4620 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4621 char *Spelling = (char *)malloc(String.size() + 1);
4622 memmove(Spelling, String.data(), String.size());
4623 Spelling[String.size()] = 0;
4624 Result.Spelling = Spelling;
4625 Result.MustFreeString = 1;
4626 } else {
4627 Result.Spelling = String.data();
4628 Result.MustFreeString = 0;
4629 }
4630 return Result;
4631}
4632}}
4633
Ted Kremenek04bb7162010-01-22 22:44:15 +00004634//===----------------------------------------------------------------------===//
4635// Misc. utility functions.
4636//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004637
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004638/// Default to using an 8 MB stack size on "safety" threads.
4639static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004640
4641namespace clang {
4642
4643bool RunSafely(llvm::CrashRecoveryContext &CRC,
4644 void (*Fn)(void*), void *UserData) {
4645 if (unsigned Size = GetSafetyThreadStackSize())
4646 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4647 return CRC.RunSafely(Fn, UserData);
4648}
4649
4650unsigned GetSafetyThreadStackSize() {
4651 return SafetyStackThreadSize;
4652}
4653
4654void SetSafetyThreadStackSize(unsigned Value) {
4655 SafetyStackThreadSize = Value;
4656}
4657
4658}
4659
Ted Kremenek04bb7162010-01-22 22:44:15 +00004660extern "C" {
4661
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004662CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004663 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004664}
4665
4666} // end: extern "C"