blob: c1b2fb64deecedec5583af61ed2db248bf3b34f1 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000126
127class VisitorJob {
128public:
Ted Kremenekf1107452010-11-12 18:26:56 +0000129 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000130protected:
131 void *data;
132 CXCursor parent;
133 Kind K;
134 VisitorJob(void *d, CXCursor C, Kind k) : data(d), parent(C), K(k) {}
135public:
136 Kind getKind() const { return K; }
137 const CXCursor &getParent() const { return parent; }
138 static bool classof(VisitorJob *VJ) { return true; }
139};
140
141typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
142
143#define DEF_JOB(NAME, DATA, KIND)\
144class NAME : public VisitorJob {\
145public:\
146 NAME(DATA *d, CXCursor parent) : VisitorJob(d, parent, VisitorJob::KIND) {}\
147 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
148 DATA *get() const { return static_cast<DATA*>(data); }\
149};
150
Ted Kremenekf1107452010-11-12 18:26:56 +0000151DEF_JOB(DeclVisit, Decl, DeclVisitKind)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000152DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
153DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000154#undef DEF_JOB
155
Ted 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
Ted Kremenekab979612010-11-11 08:05:23 +0000238 ASTUnit *getASTUnit() const { return TU; }
239
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000240 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000241
242 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
243 getPreprocessedEntities();
244
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000246
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000247 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000248 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000249 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000250 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000251 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000252 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000253 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
254 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000255 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000256 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000257 bool VisitClassTemplatePartialSpecializationDecl(
258 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000259 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000260 bool VisitEnumConstantDecl(EnumConstantDecl *D);
261 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
262 bool VisitFunctionDecl(FunctionDecl *ND);
263 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000264 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000265 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000266 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000267 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000268 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
270 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
271 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
272 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000273 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000274 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
275 bool VisitObjCImplDecl(ObjCImplDecl *D);
276 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
277 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000278 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
279 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
280 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000281 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000282 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000283 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000284 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000285 bool VisitUsingDecl(UsingDecl *D);
286 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
287 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000288
Douglas Gregor01829d32010-08-31 14:41:23 +0000289 // Name visitor
290 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000291 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000292
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000293 // Template visitors
294 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000295 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000296 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
297
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000298 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000299 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000300 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000301 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000302 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
303 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000304 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000305 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000306 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000307 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
308 bool VisitPointerTypeLoc(PointerTypeLoc TL);
309 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
310 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
311 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
312 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000313 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000315 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000316 // FIXME: Implement visitors here when the unimplemented TypeLocs get
317 // implemented
318 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
319 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000320
Douglas Gregora59e3902010-01-21 23:27:09 +0000321 // Statement visitors
322 bool VisitStmt(Stmt *S);
323 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000324 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000325 bool VisitIfStmt(IfStmt *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);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000331 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000332 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000333 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000334 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000335 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000336 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000337 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000338 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000339 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
340 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000341 bool VisitInitListExpr(InitListExpr *E);
342 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000343 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000344 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000345 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000346 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
347 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000348 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000349 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000350 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000351 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000352 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000353 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000354 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000355 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000356
357#define DATA_RECURSIVE_VISIT(NAME)\
358bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
359 DATA_RECURSIVE_VISIT(BinaryOperator)
360 DATA_RECURSIVE_VISIT(MemberExpr)
361 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000362 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000363 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000364
365 // Data-recursive visitor functions.
366 bool IsInRegionOfInterest(CXCursor C);
367 bool RunVisitorWorkList(VisitorWorkList &WL);
368 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
369 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000370};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000371
Ted Kremenekab188932010-01-05 19:32:54 +0000372} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000373
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000374static SourceRange getRawCursorExtent(CXCursor C);
375
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000376RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000377 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
378}
379
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380/// \brief Visit the given cursor and, if requested by the visitor,
381/// its children.
382///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000383/// \param Cursor the cursor to visit.
384///
385/// \param CheckRegionOfInterest if true, then the caller already checked that
386/// this cursor is within the region of interest.
387///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388/// \returns true if the visitation should be aborted, false if it
389/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391 if (clang_isInvalid(Cursor.kind))
392 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000393
Douglas Gregorb1373d02010-01-20 20:59:29 +0000394 if (clang_isDeclaration(Cursor.kind)) {
395 Decl *D = getCursorDecl(Cursor);
396 assert(D && "Invalid declaration cursor");
397 if (D->getPCHLevel() > MaxPCHLevel)
398 return false;
399
400 if (D->isImplicit())
401 return false;
402 }
403
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000404 // If we have a range of interest, and this cursor doesn't intersect with it,
405 // we're done.
406 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000407 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000408 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000409 return false;
410 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000411
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 switch (Visitor(Cursor, Parent, ClientData)) {
413 case CXChildVisit_Break:
414 return true;
415
416 case CXChildVisit_Continue:
417 return false;
418
419 case CXChildVisit_Recurse:
420 return VisitChildren(Cursor);
421 }
422
Douglas Gregorfd643772010-01-25 16:45:46 +0000423 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000424}
425
Douglas Gregor788f5a12010-03-20 00:41:21 +0000426std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
427CursorVisitor::getPreprocessedEntities() {
428 PreprocessingRecord &PPRec
429 = *TU->getPreprocessor().getPreprocessingRecord();
430
431 bool OnlyLocalDecls
432 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
433
434 // There is no region of interest; we have to walk everything.
435 if (RegionOfInterest.isInvalid())
436 return std::make_pair(PPRec.begin(OnlyLocalDecls),
437 PPRec.end(OnlyLocalDecls));
438
439 // Find the file in which the region of interest lands.
440 SourceManager &SM = TU->getSourceManager();
441 std::pair<FileID, unsigned> Begin
442 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
443 std::pair<FileID, unsigned> End
444 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
445
446 // The region of interest spans files; we have to walk everything.
447 if (Begin.first != End.first)
448 return std::make_pair(PPRec.begin(OnlyLocalDecls),
449 PPRec.end(OnlyLocalDecls));
450
451 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
452 = TU->getPreprocessedEntitiesByFile();
453 if (ByFileMap.empty()) {
454 // Build the mapping from files to sets of preprocessed entities.
455 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
456 EEnd = PPRec.end(OnlyLocalDecls);
457 E != EEnd; ++E) {
458 std::pair<FileID, unsigned> P
459 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
460 ByFileMap[P.first].push_back(*E);
461 }
462 }
463
464 return std::make_pair(ByFileMap[Begin.first].begin(),
465 ByFileMap[Begin.first].end());
466}
467
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468/// \brief Visit the children of the given cursor.
469///
470/// \returns true if the visitation should be aborted, false if it
471/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000473 if (clang_isReference(Cursor.kind)) {
474 // By definition, references have no children.
475 return false;
476 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000477
478 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000479 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000480 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482 if (clang_isDeclaration(Cursor.kind)) {
483 Decl *D = getCursorDecl(Cursor);
484 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000485 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000487
Douglas Gregora59e3902010-01-21 23:27:09 +0000488 if (clang_isStatement(Cursor.kind))
489 return Visit(getCursorStmt(Cursor));
490 if (clang_isExpression(Cursor.kind))
491 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000492
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000494 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000495 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
496 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000497 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
498 TLEnd = CXXUnit->top_level_end();
499 TL != TLEnd; ++TL) {
500 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000501 return true;
502 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 } else if (VisitDeclContext(
504 CXXUnit->getASTContext().getTranslationUnitDecl()))
505 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000506
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000508 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000509 // FIXME: Once we have the ability to deserialize a preprocessing record,
510 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000511 PreprocessingRecord::iterator E, EEnd;
512 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000513 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
514 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
515 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000516
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 continue;
518 }
519
520 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
521 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
522 return true;
523
524 continue;
525 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000526
527 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
528 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
529 return true;
530
531 continue;
532 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000533 }
534 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000535 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000536 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000537
Douglas Gregorb1373d02010-01-20 20:59:29 +0000538 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 return false;
540}
541
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000542bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000543 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
544 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000545
Ted Kremenek664cffd2010-07-22 11:30:19 +0000546 if (Stmt *Body = B->getBody())
547 return Visit(MakeCXCursor(Body, StmtParent, TU));
548
549 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000550}
551
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000552llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
553 if (RegionOfInterest.isValid()) {
554 SourceRange Range = getRawCursorExtent(Cursor);
555 if (Range.isInvalid())
556 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000557
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000558 switch (CompareRegionOfInterest(Range)) {
559 case RangeBefore:
560 // This declaration comes before the region of interest; skip it.
561 return llvm::Optional<bool>();
562
563 case RangeAfter:
564 // This declaration comes after the region of interest; we're done.
565 return false;
566
567 case RangeOverlap:
568 // This declaration overlaps the region of interest; visit it.
569 break;
570 }
571 }
572 return true;
573}
574
575bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
576 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
577
578 // FIXME: Eventually remove. This part of a hack to support proper
579 // iteration over all Decls contained lexically within an ObjC container.
580 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
581 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
582
583 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000584 Decl *D = *I;
585 if (D->getLexicalDeclContext() != DC)
586 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000587 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000588 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
589 if (!V.hasValue())
590 continue;
591 if (!V.getValue())
592 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000593 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594 return true;
595 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000596 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000597}
598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
600 llvm_unreachable("Translation units are visited directly by Visit()");
601 return false;
602}
603
604bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
605 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
606 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608 return false;
609}
610
611bool CursorVisitor::VisitTagDecl(TagDecl *D) {
612 return VisitDeclContext(D);
613}
614
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000615bool CursorVisitor::VisitClassTemplateSpecializationDecl(
616 ClassTemplateSpecializationDecl *D) {
617 bool ShouldVisitBody = false;
618 switch (D->getSpecializationKind()) {
619 case TSK_Undeclared:
620 case TSK_ImplicitInstantiation:
621 // Nothing to visit
622 return false;
623
624 case TSK_ExplicitInstantiationDeclaration:
625 case TSK_ExplicitInstantiationDefinition:
626 break;
627
628 case TSK_ExplicitSpecialization:
629 ShouldVisitBody = true;
630 break;
631 }
632
633 // Visit the template arguments used in the specialization.
634 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
635 TypeLoc TL = SpecType->getTypeLoc();
636 if (TemplateSpecializationTypeLoc *TSTLoc
637 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
638 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
639 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
640 return true;
641 }
642 }
643
644 if (ShouldVisitBody && VisitCXXRecordDecl(D))
645 return true;
646
647 return false;
648}
649
Douglas Gregor74dbe642010-08-31 19:31:58 +0000650bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
651 ClassTemplatePartialSpecializationDecl *D) {
652 // FIXME: Visit the "outer" template parameter lists on the TagDecl
653 // before visiting these template parameters.
654 if (VisitTemplateParameters(D->getTemplateParameters()))
655 return true;
656
657 // Visit the partial specialization arguments.
658 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
659 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
660 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
661 return true;
662
663 return VisitCXXRecordDecl(D);
664}
665
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000666bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000667 // Visit the default argument.
668 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
669 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
670 if (Visit(DefArg->getTypeLoc()))
671 return true;
672
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000673 return false;
674}
675
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000676bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
677 if (Expr *Init = D->getInitExpr())
678 return Visit(MakeCXCursor(Init, StmtParent, TU));
679 return false;
680}
681
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000682bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
683 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
684 if (Visit(TSInfo->getTypeLoc()))
685 return true;
686
687 return false;
688}
689
Douglas Gregora67e03f2010-09-09 21:42:20 +0000690/// \brief Compare two base or member initializers based on their source order.
691static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
692 CXXBaseOrMemberInitializer const * const *X
693 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
694 CXXBaseOrMemberInitializer const * const *Y
695 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
696
697 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
698 return -1;
699 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
700 return 1;
701 else
702 return 0;
703}
704
Douglas Gregorb1373d02010-01-20 20:59:29 +0000705bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000706 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
707 // Visit the function declaration's syntactic components in the order
708 // written. This requires a bit of work.
709 TypeLoc TL = TSInfo->getTypeLoc();
710 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
711
712 // If we have a function declared directly (without the use of a typedef),
713 // visit just the return type. Otherwise, just visit the function's type
714 // now.
715 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
716 (!FTL && Visit(TL)))
717 return true;
718
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000719 // Visit the nested-name-specifier, if present.
720 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
721 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
722 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000723
724 // Visit the declaration name.
725 if (VisitDeclarationNameInfo(ND->getNameInfo()))
726 return true;
727
728 // FIXME: Visit explicitly-specified template arguments!
729
730 // Visit the function parameters, if we have a function type.
731 if (FTL && VisitFunctionTypeLoc(*FTL, true))
732 return true;
733
734 // FIXME: Attributes?
735 }
736
Douglas Gregora67e03f2010-09-09 21:42:20 +0000737 if (ND->isThisDeclarationADefinition()) {
738 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
739 // Find the initializers that were written in the source.
740 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
741 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
742 IEnd = Constructor->init_end();
743 I != IEnd; ++I) {
744 if (!(*I)->isWritten())
745 continue;
746
747 WrittenInits.push_back(*I);
748 }
749
750 // Sort the initializers in source order
751 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
752 &CompareCXXBaseOrMemberInitializers);
753
754 // Visit the initializers in source order
755 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
756 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
757 if (Init->isMemberInitializer()) {
758 if (Visit(MakeCursorMemberRef(Init->getMember(),
759 Init->getMemberLocation(), TU)))
760 return true;
761 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
762 if (Visit(BaseInfo->getTypeLoc()))
763 return true;
764 }
765
766 // Visit the initializer value.
767 if (Expr *Initializer = Init->getInit())
768 if (Visit(MakeCXCursor(Initializer, ND, TU)))
769 return true;
770 }
771 }
772
773 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
774 return true;
775 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregorb1373d02010-01-20 20:59:29 +0000777 return false;
778}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
781 if (VisitDeclaratorDecl(D))
782 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 if (Expr *BitWidth = D->getBitWidth())
785 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 return false;
788}
789
790bool CursorVisitor::VisitVarDecl(VarDecl *D) {
791 if (VisitDeclaratorDecl(D))
792 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000793
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000794 if (Expr *Init = D->getInit())
795 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 return false;
798}
799
Douglas Gregor84b51d72010-09-01 20:16:53 +0000800bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
801 if (VisitDeclaratorDecl(D))
802 return true;
803
804 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
805 if (Expr *DefArg = D->getDefaultArgument())
806 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
807
808 return false;
809}
810
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000811bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
812 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
813 // before visiting these template parameters.
814 if (VisitTemplateParameters(D->getTemplateParameters()))
815 return true;
816
817 return VisitFunctionDecl(D->getTemplatedDecl());
818}
819
Douglas Gregor39d6f072010-08-31 19:02:00 +0000820bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
821 // FIXME: Visit the "outer" template parameter lists on the TagDecl
822 // before visiting these template parameters.
823 if (VisitTemplateParameters(D->getTemplateParameters()))
824 return true;
825
826 return VisitCXXRecordDecl(D->getTemplatedDecl());
827}
828
Douglas Gregor84b51d72010-09-01 20:16:53 +0000829bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
830 if (VisitTemplateParameters(D->getTemplateParameters()))
831 return true;
832
833 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
834 VisitTemplateArgumentLoc(D->getDefaultArgument()))
835 return true;
836
837 return false;
838}
839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000841 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
842 if (Visit(TSInfo->getTypeLoc()))
843 return true;
844
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000846 PEnd = ND->param_end();
847 P != PEnd; ++P) {
848 if (Visit(MakeCXCursor(*P, TU)))
849 return true;
850 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000851
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000852 if (ND->isThisDeclarationADefinition() &&
853 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
854 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000855
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856 return false;
857}
858
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000859namespace {
860 struct ContainerDeclsSort {
861 SourceManager &SM;
862 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
863 bool operator()(Decl *A, Decl *B) {
864 SourceLocation L_A = A->getLocStart();
865 SourceLocation L_B = B->getLocStart();
866 assert(L_A.isValid() && L_B.isValid());
867 return SM.isBeforeInTranslationUnit(L_A, L_B);
868 }
869 };
870}
871
Douglas Gregora59e3902010-01-21 23:27:09 +0000872bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000873 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
874 // an @implementation can lexically contain Decls that are not properly
875 // nested in the AST. When we identify such cases, we need to retrofit
876 // this nesting here.
877 if (!DI_current)
878 return VisitDeclContext(D);
879
880 // Scan the Decls that immediately come after the container
881 // in the current DeclContext. If any fall within the
882 // container's lexical region, stash them into a vector
883 // for later processing.
884 llvm::SmallVector<Decl *, 24> DeclsInContainer;
885 SourceLocation EndLoc = D->getSourceRange().getEnd();
886 SourceManager &SM = TU->getSourceManager();
887 if (EndLoc.isValid()) {
888 DeclContext::decl_iterator next = *DI_current;
889 while (++next != DE_current) {
890 Decl *D_next = *next;
891 if (!D_next)
892 break;
893 SourceLocation L = D_next->getLocStart();
894 if (!L.isValid())
895 break;
896 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
897 *DI_current = next;
898 DeclsInContainer.push_back(D_next);
899 continue;
900 }
901 break;
902 }
903 }
904
905 // The common case.
906 if (DeclsInContainer.empty())
907 return VisitDeclContext(D);
908
909 // Get all the Decls in the DeclContext, and sort them with the
910 // additional ones we've collected. Then visit them.
911 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
912 I!=E; ++I) {
913 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000914 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
915 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000916 continue;
917 DeclsInContainer.push_back(subDecl);
918 }
919
920 // Now sort the Decls so that they appear in lexical order.
921 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
922 ContainerDeclsSort(SM));
923
924 // Now visit the decls.
925 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
926 E = DeclsInContainer.end(); I != E; ++I) {
927 CXCursor Cursor = MakeCXCursor(*I, TU);
928 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
929 if (!V.hasValue())
930 continue;
931 if (!V.getValue())
932 return false;
933 if (Visit(Cursor, true))
934 return true;
935 }
936 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000937}
938
Douglas Gregorb1373d02010-01-20 20:59:29 +0000939bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000940 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
941 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000942 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000943
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000944 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
945 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
946 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000947 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000948 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregora59e3902010-01-21 23:27:09 +0000950 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000951}
952
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000953bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
954 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
955 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
956 E = PID->protocol_end(); I != E; ++I, ++PL)
957 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
958 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000959
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000960 return VisitObjCContainerDecl(PID);
961}
962
Ted Kremenek23173d72010-05-18 21:09:07 +0000963bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000964 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000965 return true;
966
Ted Kremenek23173d72010-05-18 21:09:07 +0000967 // FIXME: This implements a workaround with @property declarations also being
968 // installed in the DeclContext for the @interface. Eventually this code
969 // should be removed.
970 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
971 if (!CDecl || !CDecl->IsClassExtension())
972 return false;
973
974 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
975 if (!ID)
976 return false;
977
978 IdentifierInfo *PropertyId = PD->getIdentifier();
979 ObjCPropertyDecl *prevDecl =
980 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
981
982 if (!prevDecl)
983 return false;
984
985 // Visit synthesized methods since they will be skipped when visiting
986 // the @interface.
987 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000988 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000989 if (Visit(MakeCXCursor(MD, TU)))
990 return true;
991
992 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000993 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000994 if (Visit(MakeCXCursor(MD, TU)))
995 return true;
996
997 return false;
998}
999
Douglas Gregorb1373d02010-01-20 20:59:29 +00001000bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001001 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001002 if (D->getSuperClass() &&
1003 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001004 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001005 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001006 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001007
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001008 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1009 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1010 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001011 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001012 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013
Douglas Gregora59e3902010-01-21 23:27:09 +00001014 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001015}
1016
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001017bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1018 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001019}
1020
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001021bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001022 // 'ID' could be null when dealing with invalid code.
1023 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1024 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1025 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001027 return VisitObjCImplDecl(D);
1028}
1029
1030bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1031#if 0
1032 // Issue callbacks for super class.
1033 // FIXME: No source location information!
1034 if (D->getSuperClass() &&
1035 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001036 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001037 TU)))
1038 return true;
1039#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001040
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001041 return VisitObjCImplDecl(D);
1042}
1043
1044bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1045 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1046 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1047 E = D->protocol_end();
1048 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001049 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001050 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001051
1052 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001053}
1054
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001055bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1056 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1057 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1058 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001059
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001060 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001061}
1062
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001063bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1064 return VisitDeclContext(D);
1065}
1066
Douglas Gregor69319002010-08-31 23:48:11 +00001067bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001068 // Visit nested-name-specifier.
1069 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1070 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1071 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001072
1073 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1074 D->getTargetNameLoc(), TU));
1075}
1076
Douglas Gregor7e242562010-09-01 19:52:22 +00001077bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001078 // Visit nested-name-specifier.
1079 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1080 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1081 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001082
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001083 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1084 return true;
1085
Douglas Gregor7e242562010-09-01 19:52:22 +00001086 return VisitDeclarationNameInfo(D->getNameInfo());
1087}
1088
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001089bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 // Visit nested-name-specifier.
1091 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1092 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1093 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001094
1095 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1096 D->getIdentLocation(), TU));
1097}
1098
Douglas Gregor7e242562010-09-01 19:52:22 +00001099bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 // Visit nested-name-specifier.
1101 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1102 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1103 return true;
1104
Douglas Gregor7e242562010-09-01 19:52:22 +00001105 return VisitDeclarationNameInfo(D->getNameInfo());
1106}
1107
1108bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1109 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 // Visit nested-name-specifier.
1111 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1112 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1113 return true;
1114
Douglas Gregor7e242562010-09-01 19:52:22 +00001115 return false;
1116}
1117
Douglas Gregor01829d32010-08-31 14:41:23 +00001118bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1119 switch (Name.getName().getNameKind()) {
1120 case clang::DeclarationName::Identifier:
1121 case clang::DeclarationName::CXXLiteralOperatorName:
1122 case clang::DeclarationName::CXXOperatorName:
1123 case clang::DeclarationName::CXXUsingDirective:
1124 return false;
1125
1126 case clang::DeclarationName::CXXConstructorName:
1127 case clang::DeclarationName::CXXDestructorName:
1128 case clang::DeclarationName::CXXConversionFunctionName:
1129 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1130 return Visit(TSInfo->getTypeLoc());
1131 return false;
1132
1133 case clang::DeclarationName::ObjCZeroArgSelector:
1134 case clang::DeclarationName::ObjCOneArgSelector:
1135 case clang::DeclarationName::ObjCMultiArgSelector:
1136 // FIXME: Per-identifier location info?
1137 return false;
1138 }
1139
1140 return false;
1141}
1142
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001143bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1144 SourceRange Range) {
1145 // FIXME: This whole routine is a hack to work around the lack of proper
1146 // source information in nested-name-specifiers (PR5791). Since we do have
1147 // a beginning source location, we can visit the first component of the
1148 // nested-name-specifier, if it's a single-token component.
1149 if (!NNS)
1150 return false;
1151
1152 // Get the first component in the nested-name-specifier.
1153 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1154 NNS = Prefix;
1155
1156 switch (NNS->getKind()) {
1157 case NestedNameSpecifier::Namespace:
1158 // FIXME: The token at this source location might actually have been a
1159 // namespace alias, but we don't model that. Lame!
1160 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1161 TU));
1162
1163 case NestedNameSpecifier::TypeSpec: {
1164 // If the type has a form where we know that the beginning of the source
1165 // range matches up with a reference cursor. Visit the appropriate reference
1166 // cursor.
1167 Type *T = NNS->getAsType();
1168 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1169 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1170 if (const TagType *Tag = dyn_cast<TagType>(T))
1171 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1172 if (const TemplateSpecializationType *TST
1173 = dyn_cast<TemplateSpecializationType>(T))
1174 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1175 break;
1176 }
1177
1178 case NestedNameSpecifier::TypeSpecWithTemplate:
1179 case NestedNameSpecifier::Global:
1180 case NestedNameSpecifier::Identifier:
1181 break;
1182 }
1183
1184 return false;
1185}
1186
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001187bool CursorVisitor::VisitTemplateParameters(
1188 const TemplateParameterList *Params) {
1189 if (!Params)
1190 return false;
1191
1192 for (TemplateParameterList::const_iterator P = Params->begin(),
1193 PEnd = Params->end();
1194 P != PEnd; ++P) {
1195 if (Visit(MakeCXCursor(*P, TU)))
1196 return true;
1197 }
1198
1199 return false;
1200}
1201
Douglas Gregor0b36e612010-08-31 20:37:03 +00001202bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1203 switch (Name.getKind()) {
1204 case TemplateName::Template:
1205 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1206
1207 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001208 // Visit the overloaded template set.
1209 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1210 return true;
1211
Douglas Gregor0b36e612010-08-31 20:37:03 +00001212 return false;
1213
1214 case TemplateName::DependentTemplate:
1215 // FIXME: Visit nested-name-specifier.
1216 return false;
1217
1218 case TemplateName::QualifiedTemplate:
1219 // FIXME: Visit nested-name-specifier.
1220 return Visit(MakeCursorTemplateRef(
1221 Name.getAsQualifiedTemplateName()->getDecl(),
1222 Loc, TU));
1223 }
1224
1225 return false;
1226}
1227
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001228bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1229 switch (TAL.getArgument().getKind()) {
1230 case TemplateArgument::Null:
1231 case TemplateArgument::Integral:
1232 return false;
1233
1234 case TemplateArgument::Pack:
1235 // FIXME: Implement when variadic templates come along.
1236 return false;
1237
1238 case TemplateArgument::Type:
1239 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1240 return Visit(TSInfo->getTypeLoc());
1241 return false;
1242
1243 case TemplateArgument::Declaration:
1244 if (Expr *E = TAL.getSourceDeclExpression())
1245 return Visit(MakeCXCursor(E, StmtParent, TU));
1246 return false;
1247
1248 case TemplateArgument::Expression:
1249 if (Expr *E = TAL.getSourceExpression())
1250 return Visit(MakeCXCursor(E, StmtParent, TU));
1251 return false;
1252
1253 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001254 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1255 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001256 }
1257
1258 return false;
1259}
1260
Ted Kremeneka0536d82010-05-07 01:04:29 +00001261bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1262 return VisitDeclContext(D);
1263}
1264
Douglas Gregor01829d32010-08-31 14:41:23 +00001265bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1266 return Visit(TL.getUnqualifiedLoc());
1267}
1268
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001269bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1270 ASTContext &Context = TU->getASTContext();
1271
1272 // Some builtin types (such as Objective-C's "id", "sel", and
1273 // "Class") have associated declarations. Create cursors for those.
1274 QualType VisitType;
1275 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001276 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001277 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001278 case BuiltinType::Char_U:
1279 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001280 case BuiltinType::Char16:
1281 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001282 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001283 case BuiltinType::UInt:
1284 case BuiltinType::ULong:
1285 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001286 case BuiltinType::UInt128:
1287 case BuiltinType::Char_S:
1288 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001289 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001290 case BuiltinType::Short:
1291 case BuiltinType::Int:
1292 case BuiltinType::Long:
1293 case BuiltinType::LongLong:
1294 case BuiltinType::Int128:
1295 case BuiltinType::Float:
1296 case BuiltinType::Double:
1297 case BuiltinType::LongDouble:
1298 case BuiltinType::NullPtr:
1299 case BuiltinType::Overload:
1300 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001301 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001302
1303 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001304 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001305
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001306 case BuiltinType::ObjCId:
1307 VisitType = Context.getObjCIdType();
1308 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001309
1310 case BuiltinType::ObjCClass:
1311 VisitType = Context.getObjCClassType();
1312 break;
1313
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001314 case BuiltinType::ObjCSel:
1315 VisitType = Context.getObjCSelType();
1316 break;
1317 }
1318
1319 if (!VisitType.isNull()) {
1320 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001321 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001322 TU));
1323 }
1324
1325 return false;
1326}
1327
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001328bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1329 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1330}
1331
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001332bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1333 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1334}
1335
1336bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1337 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1338}
1339
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001340bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001341 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001342 // no context information with which we can match up the depth/index in the
1343 // type to the appropriate
1344 return false;
1345}
1346
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001347bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1348 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1349 return true;
1350
John McCallc12c5bb2010-05-15 11:32:37 +00001351 return false;
1352}
1353
1354bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1355 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1356 return true;
1357
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001358 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1359 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1360 TU)))
1361 return true;
1362 }
1363
1364 return false;
1365}
1366
1367bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001368 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001369}
1370
1371bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1372 return Visit(TL.getPointeeLoc());
1373}
1374
1375bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1376 return Visit(TL.getPointeeLoc());
1377}
1378
1379bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1380 return Visit(TL.getPointeeLoc());
1381}
1382
1383bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385}
1386
1387bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001388 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001389}
1390
Douglas Gregor01829d32010-08-31 14:41:23 +00001391bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1392 bool SkipResultType) {
1393 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394 return true;
1395
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001396 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001397 if (Decl *D = TL.getArg(I))
1398 if (Visit(MakeCXCursor(D, TU)))
1399 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001400
1401 return false;
1402}
1403
1404bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1405 if (Visit(TL.getElementLoc()))
1406 return true;
1407
1408 if (Expr *Size = TL.getSizeExpr())
1409 return Visit(MakeCXCursor(Size, StmtParent, TU));
1410
1411 return false;
1412}
1413
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001414bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1415 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001416 // Visit the template name.
1417 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1418 TL.getTemplateNameLoc()))
1419 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001420
1421 // Visit the template arguments.
1422 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1423 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1424 return true;
1425
1426 return false;
1427}
1428
Douglas Gregor2332c112010-01-21 20:48:56 +00001429bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1430 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1431}
1432
1433bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1434 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1435 return Visit(TSInfo->getTypeLoc());
1436
1437 return false;
1438}
1439
Douglas Gregora59e3902010-01-21 23:27:09 +00001440bool CursorVisitor::VisitStmt(Stmt *S) {
1441 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1442 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001443 if (Stmt *C = *Child)
1444 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1445 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001446 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001447
Douglas Gregora59e3902010-01-21 23:27:09 +00001448 return false;
1449}
1450
1451bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001452 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001453 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1454 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001455 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001456 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001457 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001458 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001459
Douglas Gregora59e3902010-01-21 23:27:09 +00001460 return false;
1461}
1462
Douglas Gregor36897b02010-09-10 00:22:18 +00001463bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1464 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1465}
1466
Douglas Gregorf5bab412010-01-22 01:00:11 +00001467bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1468 if (VarDecl *Var = S->getConditionVariable()) {
1469 if (Visit(MakeCXCursor(Var, TU)))
1470 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001471 }
1472
Douglas Gregor263b47b2010-01-25 16:12:32 +00001473 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1474 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001475 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1476 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001477 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1478 return true;
1479
1480 return false;
1481}
1482
Douglas Gregor263b47b2010-01-25 16:12:32 +00001483bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1484 if (VarDecl *Var = S->getConditionVariable()) {
1485 if (Visit(MakeCXCursor(Var, TU)))
1486 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001487 }
1488
Douglas Gregor263b47b2010-01-25 16:12:32 +00001489 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1490 return true;
1491 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001492 return true;
1493
Douglas Gregor263b47b2010-01-25 16:12:32 +00001494 return false;
1495}
1496
1497bool CursorVisitor::VisitForStmt(ForStmt *S) {
1498 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1499 return true;
1500 if (VarDecl *Var = S->getConditionVariable()) {
1501 if (Visit(MakeCXCursor(Var, TU)))
1502 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001503 }
1504
Douglas Gregor263b47b2010-01-25 16:12:32 +00001505 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1506 return true;
1507 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1508 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001509 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1510 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001511
Douglas Gregorf5bab412010-01-22 01:00:11 +00001512 return false;
1513}
1514
Douglas Gregor8947a752010-09-02 20:35:02 +00001515bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1516 // Visit nested-name-specifier, if present.
1517 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1518 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1519 return true;
1520
1521 // Visit declaration name.
1522 if (VisitDeclarationNameInfo(E->getNameInfo()))
1523 return true;
1524
1525 // Visit explicitly-specified template arguments.
1526 if (E->hasExplicitTemplateArgs()) {
1527 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1528 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1529 *ArgEnd = Arg + Args.NumTemplateArgs;
1530 Arg != ArgEnd; ++Arg)
1531 if (VisitTemplateArgumentLoc(*Arg))
1532 return true;
1533 }
1534
1535 return false;
1536}
1537
Ted Kremenek3064ef92010-08-27 21:34:58 +00001538bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1539 if (D->isDefinition()) {
1540 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1541 E = D->bases_end(); I != E; ++I) {
1542 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1543 return true;
1544 }
1545 }
1546
1547 return VisitTagDecl(D);
1548}
1549
1550
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001551bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1552 return Visit(B->getBlockDecl());
1553}
1554
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001555bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001556 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001557 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1558 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001559
1560 // Visit the components of the offsetof expression.
1561 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1562 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1563 const OffsetOfNode &Node = E->getComponent(I);
1564 switch (Node.getKind()) {
1565 case OffsetOfNode::Array:
1566 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1567 StmtParent, TU)))
1568 return true;
1569 break;
1570
1571 case OffsetOfNode::Field:
1572 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1573 TU)))
1574 return true;
1575 break;
1576
1577 case OffsetOfNode::Identifier:
1578 case OffsetOfNode::Base:
1579 continue;
1580 }
1581 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001582
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001583 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001584}
1585
Douglas Gregor336fd812010-01-23 00:40:08 +00001586bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1587 if (E->isArgumentType()) {
1588 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1589 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001590
Douglas Gregor336fd812010-01-23 00:40:08 +00001591 return false;
1592 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001593
Douglas Gregor336fd812010-01-23 00:40:08 +00001594 return VisitExpr(E);
1595}
1596
1597bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1598 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1599 if (Visit(TSInfo->getTypeLoc()))
1600 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001601
Douglas Gregor336fd812010-01-23 00:40:08 +00001602 return VisitCastExpr(E);
1603}
1604
1605bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1606 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1607 if (Visit(TSInfo->getTypeLoc()))
1608 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001609
Douglas Gregor336fd812010-01-23 00:40:08 +00001610 return VisitExpr(E);
1611}
1612
Douglas Gregor36897b02010-09-10 00:22:18 +00001613bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1614 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1615}
1616
Douglas Gregor648220e2010-08-10 15:02:34 +00001617bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1618 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1619 Visit(E->getArgTInfo2()->getTypeLoc());
1620}
1621
1622bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1623 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1624 return true;
1625
1626 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1627}
1628
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001629bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1630 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001631 if (InitListExpr *Syntactic = E->getSyntacticForm())
1632 return VisitExpr(Syntactic);
1633
1634 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001635}
1636
1637bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1638 // Visit the designators.
1639 typedef DesignatedInitExpr::Designator Designator;
1640 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1641 DEnd = E->designators_end();
1642 D != DEnd; ++D) {
1643 if (D->isFieldDesignator()) {
1644 if (FieldDecl *Field = D->getField())
1645 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1646 return true;
1647
1648 continue;
1649 }
1650
1651 if (D->isArrayDesignator()) {
1652 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1653 return true;
1654
1655 continue;
1656 }
1657
1658 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1659 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1660 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1661 return true;
1662 }
1663
1664 // Visit the initializer value itself.
1665 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1666}
1667
Douglas Gregor94802292010-09-02 21:20:16 +00001668bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1669 if (E->isTypeOperand()) {
1670 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1671 return Visit(TSInfo->getTypeLoc());
1672
1673 return false;
1674 }
1675
1676 return VisitExpr(E);
1677}
1678
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001679bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1680 if (E->isTypeOperand()) {
1681 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1682 return Visit(TSInfo->getTypeLoc());
1683
1684 return false;
1685 }
1686
1687 return VisitExpr(E);
1688}
1689
Douglas Gregorab6677e2010-09-08 00:15:04 +00001690bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1691 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001692 if (Visit(TSInfo->getTypeLoc()))
1693 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001694
1695 return VisitExpr(E);
1696}
1697
1698bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1699 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1700 return Visit(TSInfo->getTypeLoc());
1701
1702 return false;
1703}
1704
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001705bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1706 // Visit placement arguments.
1707 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1708 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1709 return true;
1710
1711 // Visit the allocated type.
1712 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1713 if (Visit(TSInfo->getTypeLoc()))
1714 return true;
1715
1716 // Visit the array size, if any.
1717 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1718 return true;
1719
1720 // Visit the initializer or constructor arguments.
1721 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1722 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1723 return true;
1724
1725 return false;
1726}
1727
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001728bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1729 // Visit base expression.
1730 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1731 return true;
1732
1733 // Visit the nested-name-specifier.
1734 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1735 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1736 return true;
1737
1738 // Visit the scope type that looks disturbingly like the nested-name-specifier
1739 // but isn't.
1740 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1741 if (Visit(TSInfo->getTypeLoc()))
1742 return true;
1743
1744 // Visit the name of the type being destroyed.
1745 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1746 if (Visit(TSInfo->getTypeLoc()))
1747 return true;
1748
1749 return false;
1750}
1751
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001752bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1753 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1754}
1755
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001756bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001757 // Visit the nested-name-specifier.
1758 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1759 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1760 return true;
1761
1762 // Visit the declaration name.
1763 if (VisitDeclarationNameInfo(E->getNameInfo()))
1764 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001765
1766 // Visit the overloaded declaration reference.
1767 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1768 return true;
1769
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001770 // Visit the explicitly-specified template arguments.
1771 if (const ExplicitTemplateArgumentList *ArgList
1772 = E->getOptionalExplicitTemplateArgs()) {
1773 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1774 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1775 Arg != ArgEnd; ++Arg) {
1776 if (VisitTemplateArgumentLoc(*Arg))
1777 return true;
1778 }
1779 }
1780
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001781 return false;
1782}
1783
Douglas Gregorbfebed22010-09-03 17:24:10 +00001784bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1785 DependentScopeDeclRefExpr *E) {
1786 // Visit the nested-name-specifier.
1787 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1788 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1789 return true;
1790
1791 // Visit the declaration name.
1792 if (VisitDeclarationNameInfo(E->getNameInfo()))
1793 return true;
1794
1795 // Visit the explicitly-specified template arguments.
1796 if (const ExplicitTemplateArgumentList *ArgList
1797 = E->getOptionalExplicitTemplateArgs()) {
1798 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1799 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1800 Arg != ArgEnd; ++Arg) {
1801 if (VisitTemplateArgumentLoc(*Arg))
1802 return true;
1803 }
1804 }
1805
1806 return false;
1807}
1808
Douglas Gregorab6677e2010-09-08 00:15:04 +00001809bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1810 CXXUnresolvedConstructExpr *E) {
1811 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1812 if (Visit(TSInfo->getTypeLoc()))
1813 return true;
1814
1815 return VisitExpr(E);
1816}
1817
Douglas Gregor25d63622010-09-03 17:35:34 +00001818bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1819 CXXDependentScopeMemberExpr *E) {
1820 // Visit the base expression, if there is one.
1821 if (!E->isImplicitAccess() &&
1822 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1823 return true;
1824
1825 // Visit the nested-name-specifier.
1826 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1827 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1828 return true;
1829
1830 // Visit the declaration name.
1831 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1832 return true;
1833
1834 // Visit the explicitly-specified template arguments.
1835 if (const ExplicitTemplateArgumentList *ArgList
1836 = E->getOptionalExplicitTemplateArgs()) {
1837 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1838 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1839 Arg != ArgEnd; ++Arg) {
1840 if (VisitTemplateArgumentLoc(*Arg))
1841 return true;
1842 }
1843 }
1844
1845 return false;
1846}
1847
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001848bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1849 // Visit the base expression, if there is one.
1850 if (!E->isImplicitAccess() &&
1851 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1852 return true;
1853
1854 return VisitOverloadExpr(E);
1855}
Douglas Gregor25d63622010-09-03 17:35:34 +00001856
Douglas Gregorc2350e52010-03-08 16:40:19 +00001857bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001858 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1859 if (Visit(TSInfo->getTypeLoc()))
1860 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001861
1862 return VisitExpr(E);
1863}
1864
Douglas Gregor81d34662010-04-20 15:39:42 +00001865bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1866 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1867}
1868
1869
Ted Kremenek09dfa372010-02-18 05:46:33 +00001870bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001871 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1872 i != e; ++i)
1873 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001874 return true;
1875
1876 return false;
1877}
1878
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001879//===----------------------------------------------------------------------===//
1880// Data-recursive visitor methods.
1881//===----------------------------------------------------------------------===//
1882
1883void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1884 CXCursor C = MakeCXCursor(S, StmtParent, TU);
1885 switch (S->getStmtClass()) {
1886 default: {
1887 unsigned size = WL.size();
1888 for (Stmt::child_iterator Child = S->child_begin(),
1889 ChildEnd = S->child_end(); Child != ChildEnd; ++Child) {
1890 if (Stmt *child = *Child) {
1891 WL.push_back(StmtVisit(child, C));
1892 }
1893 }
1894
1895 if (size == WL.size())
1896 return;
1897
1898 // Now reverse the entries we just added. This will match the DFS
1899 // ordering performed by the worklist.
1900 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1901 std::reverse(I, E);
1902 break;
Ted Kremenekf1107452010-11-12 18:26:56 +00001903 }
1904 case Stmt::CXXOperatorCallExprClass: {
1905 CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(S);
1906 // Note that we enqueue things in reverse order so that
1907 // they are visited correctly by the DFS.
1908
1909 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
1910 WL.push_back(StmtVisit(CE->getArg(N-I), C));
1911
1912 WL.push_back(StmtVisit(CE->getCallee(), C));
1913 WL.push_back(StmtVisit(CE->getArg(0), C));
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001914 break;
1915 }
1916 case Stmt::BinaryOperatorClass: {
1917 BinaryOperator *B = cast<BinaryOperator>(S);
1918 WL.push_back(StmtVisit(B->getRHS(), C));
1919 WL.push_back(StmtVisit(B->getLHS(), C));
1920 break;
1921 }
1922 case Stmt::MemberExprClass: {
1923 MemberExpr *M = cast<MemberExpr>(S);
1924 WL.push_back(MemberExprParts(M, C));
1925 WL.push_back(StmtVisit(M->getBase(), C));
1926 break;
1927 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001928 case Stmt::ParenExprClass: {
1929 WL.push_back(StmtVisit(cast<ParenExpr>(S)->getSubExpr(), C));
1930 break;
1931 }
1932 case Stmt::SwitchStmtClass: {
1933 SwitchStmt *SS = cast<SwitchStmt>(S);
1934 if (Stmt *Body = SS->getBody())
1935 WL.push_back(StmtVisit(Body, C));
1936 if (Stmt *Cond = SS->getCond())
1937 WL.push_back(StmtVisit(Cond, C));
1938 if (VarDecl *Var = SS->getConditionVariable())
1939 WL.push_back(DeclVisit(Var, C));
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001940 break;
1941 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001942 }
1943}
1944
1945bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1946 if (RegionOfInterest.isValid()) {
1947 SourceRange Range = getRawCursorExtent(C);
1948 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1949 return false;
1950 }
1951 return true;
1952}
1953
1954bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1955 while (!WL.empty()) {
1956 // Dequeue the worklist item.
1957 VisitorJob LI = WL.back(); WL.pop_back();
1958
1959 // Set the Parent field, then back to its old value once we're done.
1960 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1961
1962 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001963 case VisitorJob::DeclVisitKind: {
1964 Decl *D = cast<DeclVisit>(LI).get();
1965 if (!D)
1966 continue;
1967
1968 // For now, perform default visitation for Decls.
1969 if (Visit(MakeCXCursor(D, TU)))
1970 return true;
1971
1972 continue;
1973 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001974 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001975 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001976 if (!S)
1977 continue;
1978
Ted Kremenekf1107452010-11-12 18:26:56 +00001979 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001980 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1981
1982 switch (S->getStmtClass()) {
1983 default: {
1984 // Perform default visitation for other cases.
1985 if (Visit(Cursor))
1986 return true;
1987 continue;
1988 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001989 case Stmt::BinaryOperatorClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001990 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001991 case Stmt::CaseStmtClass:
1992 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001993 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001994 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001995 case Stmt::DefaultStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001996 case Stmt::MemberExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001997 case Stmt::ParenExprClass:
1998 case Stmt::SwitchStmtClass:
1999 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002000 if (!IsInRegionOfInterest(Cursor))
2001 continue;
2002 switch (Visitor(Cursor, Parent, ClientData)) {
2003 case CXChildVisit_Break:
2004 return true;
2005 case CXChildVisit_Continue:
2006 break;
2007 case CXChildVisit_Recurse:
2008 EnqueueWorkList(WL, S);
2009 break;
2010 }
2011 }
2012 }
2013 continue;
2014 }
2015 case VisitorJob::MemberExprPartsKind: {
2016 // Handle the other pieces in the MemberExpr besides the base.
2017 MemberExpr *M = cast<MemberExprParts>(LI).get();
2018
2019 // Visit the nested-name-specifier
2020 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2021 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2022 return true;
2023
2024 // Visit the declaration name.
2025 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2026 return true;
2027
2028 // Visit the explicitly-specified template arguments, if any.
2029 if (M->hasExplicitTemplateArgs()) {
2030 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2031 *ArgEnd = Arg + M->getNumTemplateArgs();
2032 Arg != ArgEnd; ++Arg) {
2033 if (VisitTemplateArgumentLoc(*Arg))
2034 return true;
2035 }
2036 }
2037 continue;
2038 }
2039 }
2040 }
2041 return false;
2042}
2043
2044bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2045 VisitorWorkList WL;
2046 EnqueueWorkList(WL, S);
2047 return RunVisitorWorkList(WL);
2048}
2049
2050//===----------------------------------------------------------------------===//
2051// Misc. API hooks.
2052//===----------------------------------------------------------------------===//
2053
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002054static llvm::sys::Mutex EnableMultithreadingMutex;
2055static bool EnabledMultithreading;
2056
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002057extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002058CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2059 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002060 // Disable pretty stack trace functionality, which will otherwise be a very
2061 // poor citizen of the world and set up all sorts of signal handlers.
2062 llvm::DisablePrettyStackTrace = true;
2063
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002064 // We use crash recovery to make some of our APIs more reliable, implicitly
2065 // enable it.
2066 llvm::CrashRecoveryContext::Enable();
2067
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002068 // Enable support for multithreading in LLVM.
2069 {
2070 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2071 if (!EnabledMultithreading) {
2072 llvm::llvm_start_multithreaded();
2073 EnabledMultithreading = true;
2074 }
2075 }
2076
Douglas Gregora030b7c2010-01-22 20:35:53 +00002077 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002078 if (excludeDeclarationsFromPCH)
2079 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002080 if (displayDiagnostics)
2081 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002082 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002083}
2084
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002085void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002086 if (CIdx)
2087 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002088}
2089
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002090CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002091 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002092 if (!CIdx)
2093 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002094
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002095 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002096 FileSystemOptions FileSystemOpts;
2097 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002098
Douglas Gregor28019772010-04-05 23:52:57 +00002099 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002100 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002101 CXXIdx->getOnlyLocalDecls(),
2102 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002103}
2104
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002105unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002106 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002107 CXTranslationUnit_CacheCompletionResults |
2108 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002109}
2110
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002111CXTranslationUnit
2112clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2113 const char *source_filename,
2114 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002115 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002116 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002117 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002118 return clang_parseTranslationUnit(CIdx, source_filename,
2119 command_line_args, num_command_line_args,
2120 unsaved_files, num_unsaved_files,
2121 CXTranslationUnit_DetailedPreprocessingRecord);
2122}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002123
2124struct ParseTranslationUnitInfo {
2125 CXIndex CIdx;
2126 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002127 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002128 int num_command_line_args;
2129 struct CXUnsavedFile *unsaved_files;
2130 unsigned num_unsaved_files;
2131 unsigned options;
2132 CXTranslationUnit result;
2133};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002134static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002135 ParseTranslationUnitInfo *PTUI =
2136 static_cast<ParseTranslationUnitInfo*>(UserData);
2137 CXIndex CIdx = PTUI->CIdx;
2138 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002139 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002140 int num_command_line_args = PTUI->num_command_line_args;
2141 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2142 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2143 unsigned options = PTUI->options;
2144 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002145
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002146 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002147 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002149 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2150
Douglas Gregor44c181a2010-07-23 00:33:23 +00002151 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002152 bool CompleteTranslationUnit
2153 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002154 bool CacheCodeCompetionResults
2155 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002156 bool CXXPrecompilePreamble
2157 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2158 bool CXXChainedPCH
2159 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002160
Douglas Gregor5352ac02010-01-28 00:27:43 +00002161 // Configure the diagnostics.
2162 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002163 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2164 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002165
Douglas Gregor4db64a42010-01-23 00:14:00 +00002166 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2167 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002168 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002169 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002170 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002171 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2172 Buffer));
2173 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002174
Douglas Gregorb10daed2010-10-11 16:52:23 +00002175 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002176
Ted Kremenek139ba862009-10-22 00:03:57 +00002177 // The 'source_filename' argument is optional. If the caller does not
2178 // specify it then it is assumed that the source file is specified
2179 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002180 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002181 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002182
2183 // Since the Clang C library is primarily used by batch tools dealing with
2184 // (often very broken) source code, where spell-checking can have a
2185 // significant negative impact on performance (particularly when
2186 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002187 // Only do this if we haven't found a spell-checking-related argument.
2188 bool FoundSpellCheckingArgument = false;
2189 for (int I = 0; I != num_command_line_args; ++I) {
2190 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2191 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2192 FoundSpellCheckingArgument = true;
2193 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002194 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002195 }
2196 if (!FoundSpellCheckingArgument)
2197 Args.push_back("-fno-spell-checking");
2198
2199 Args.insert(Args.end(), command_line_args,
2200 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002201
Douglas Gregor44c181a2010-07-23 00:33:23 +00002202 // Do we need the detailed preprocessing record?
2203 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002204 Args.push_back("-Xclang");
2205 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002206 }
2207
Douglas Gregorb10daed2010-10-11 16:52:23 +00002208 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002209 llvm::OwningPtr<ASTUnit> Unit(
2210 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2211 Diags,
2212 CXXIdx->getClangResourcesPath(),
2213 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002214 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002215 RemappedFiles.data(),
2216 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002217 PrecompilePreamble,
2218 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002219 CacheCodeCompetionResults,
2220 CXXPrecompilePreamble,
2221 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002222
Douglas Gregorb10daed2010-10-11 16:52:23 +00002223 if (NumErrors != Diags->getNumErrors()) {
2224 // Make sure to check that 'Unit' is non-NULL.
2225 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2226 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2227 DEnd = Unit->stored_diag_end();
2228 D != DEnd; ++D) {
2229 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2230 CXString Msg = clang_formatDiagnostic(&Diag,
2231 clang_defaultDiagnosticDisplayOptions());
2232 fprintf(stderr, "%s\n", clang_getCString(Msg));
2233 clang_disposeString(Msg);
2234 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002235#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002236 // On Windows, force a flush, since there may be multiple copies of
2237 // stderr and stdout in the file system, all with different buffers
2238 // but writing to the same device.
2239 fflush(stderr);
2240#endif
2241 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002242 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002243
Douglas Gregorb10daed2010-10-11 16:52:23 +00002244 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002245}
2246CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2247 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002248 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002249 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002250 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002251 unsigned num_unsaved_files,
2252 unsigned options) {
2253 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002254 num_command_line_args, unsaved_files,
2255 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002256 llvm::CrashRecoveryContext CRC;
2257
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002258 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002259 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2260 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2261 fprintf(stderr, " 'command_line_args' : [");
2262 for (int i = 0; i != num_command_line_args; ++i) {
2263 if (i)
2264 fprintf(stderr, ", ");
2265 fprintf(stderr, "'%s'", command_line_args[i]);
2266 }
2267 fprintf(stderr, "],\n");
2268 fprintf(stderr, " 'unsaved_files' : [");
2269 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2270 if (i)
2271 fprintf(stderr, ", ");
2272 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2273 unsaved_files[i].Length);
2274 }
2275 fprintf(stderr, "],\n");
2276 fprintf(stderr, " 'options' : %d,\n", options);
2277 fprintf(stderr, "}\n");
2278
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002279 return 0;
2280 }
2281
2282 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002283}
2284
Douglas Gregor19998442010-08-13 15:35:05 +00002285unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2286 return CXSaveTranslationUnit_None;
2287}
2288
2289int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2290 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002291 if (!TU)
2292 return 1;
2293
2294 return static_cast<ASTUnit *>(TU)->Save(FileName);
2295}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002296
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002297void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002298 if (CTUnit) {
2299 // If the translation unit has been marked as unsafe to free, just discard
2300 // it.
2301 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2302 return;
2303
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002304 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002305 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002306}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002307
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002308unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2309 return CXReparse_None;
2310}
2311
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002312struct ReparseTranslationUnitInfo {
2313 CXTranslationUnit TU;
2314 unsigned num_unsaved_files;
2315 struct CXUnsavedFile *unsaved_files;
2316 unsigned options;
2317 int result;
2318};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002319
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002320static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002321 ReparseTranslationUnitInfo *RTUI =
2322 static_cast<ReparseTranslationUnitInfo*>(UserData);
2323 CXTranslationUnit TU = RTUI->TU;
2324 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2325 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2326 unsigned options = RTUI->options;
2327 (void) options;
2328 RTUI->result = 1;
2329
Douglas Gregorabc563f2010-07-19 21:46:24 +00002330 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002331 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002332
2333 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2334 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002335
2336 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2337 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2338 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2339 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002340 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002341 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2342 Buffer));
2343 }
2344
Douglas Gregor593b0c12010-09-23 18:47:53 +00002345 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2346 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002347}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002348
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002349int clang_reparseTranslationUnit(CXTranslationUnit TU,
2350 unsigned num_unsaved_files,
2351 struct CXUnsavedFile *unsaved_files,
2352 unsigned options) {
2353 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2354 options, 0 };
2355 llvm::CrashRecoveryContext CRC;
2356
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002357 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002358 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002359 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2360 return 1;
2361 }
2362
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002363
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002364 return RTUI.result;
2365}
2366
Douglas Gregordf95a132010-08-09 20:45:32 +00002367
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002368CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002369 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002370 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002371
Steve Naroff77accc12009-09-03 18:19:54 +00002372 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002373 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002374}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002375
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002376CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002377 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002378 return Result;
2379}
2380
Ted Kremenekfb480492010-01-13 21:46:36 +00002381} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002382
Ted Kremenekfb480492010-01-13 21:46:36 +00002383//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002384// CXSourceLocation and CXSourceRange Operations.
2385//===----------------------------------------------------------------------===//
2386
Douglas Gregorb9790342010-01-22 21:44:22 +00002387extern "C" {
2388CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002389 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002390 return Result;
2391}
2392
2393unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002394 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2395 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2396 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002397}
2398
2399CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2400 CXFile file,
2401 unsigned line,
2402 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002403 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002404 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002405
Douglas Gregorb9790342010-01-22 21:44:22 +00002406 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2407 SourceLocation SLoc
2408 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002409 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002410 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002411 if (SLoc.isInvalid()) return clang_getNullLocation();
2412
2413 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2414}
2415
2416CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2417 CXFile file,
2418 unsigned offset) {
2419 if (!tu || !file)
2420 return clang_getNullLocation();
2421
2422 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2423 SourceLocation Start
2424 = CXXUnit->getSourceManager().getLocation(
2425 static_cast<const FileEntry *>(file),
2426 1, 1);
2427 if (Start.isInvalid()) return clang_getNullLocation();
2428
2429 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2430
2431 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002432
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002433 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002434}
2435
Douglas Gregor5352ac02010-01-28 00:27:43 +00002436CXSourceRange clang_getNullRange() {
2437 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2438 return Result;
2439}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002440
Douglas Gregor5352ac02010-01-28 00:27:43 +00002441CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2442 if (begin.ptr_data[0] != end.ptr_data[0] ||
2443 begin.ptr_data[1] != end.ptr_data[1])
2444 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002445
2446 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002447 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002448 return Result;
2449}
2450
Douglas Gregor46766dc2010-01-26 19:19:08 +00002451void clang_getInstantiationLocation(CXSourceLocation location,
2452 CXFile *file,
2453 unsigned *line,
2454 unsigned *column,
2455 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002456 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2457
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002458 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002459 if (file)
2460 *file = 0;
2461 if (line)
2462 *line = 0;
2463 if (column)
2464 *column = 0;
2465 if (offset)
2466 *offset = 0;
2467 return;
2468 }
2469
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002470 const SourceManager &SM =
2471 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002472 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002473
2474 if (file)
2475 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2476 if (line)
2477 *line = SM.getInstantiationLineNumber(InstLoc);
2478 if (column)
2479 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002480 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002481 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002482}
2483
Douglas Gregora9b06d42010-11-09 06:24:54 +00002484void clang_getSpellingLocation(CXSourceLocation location,
2485 CXFile *file,
2486 unsigned *line,
2487 unsigned *column,
2488 unsigned *offset) {
2489 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2490
2491 if (!location.ptr_data[0] || Loc.isInvalid()) {
2492 if (file)
2493 *file = 0;
2494 if (line)
2495 *line = 0;
2496 if (column)
2497 *column = 0;
2498 if (offset)
2499 *offset = 0;
2500 return;
2501 }
2502
2503 const SourceManager &SM =
2504 *static_cast<const SourceManager*>(location.ptr_data[0]);
2505 SourceLocation SpellLoc = Loc;
2506 if (SpellLoc.isMacroID()) {
2507 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2508 if (SimpleSpellingLoc.isFileID() &&
2509 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2510 SpellLoc = SimpleSpellingLoc;
2511 else
2512 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2513 }
2514
2515 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2516 FileID FID = LocInfo.first;
2517 unsigned FileOffset = LocInfo.second;
2518
2519 if (file)
2520 *file = (void *)SM.getFileEntryForID(FID);
2521 if (line)
2522 *line = SM.getLineNumber(FID, FileOffset);
2523 if (column)
2524 *column = SM.getColumnNumber(FID, FileOffset);
2525 if (offset)
2526 *offset = FileOffset;
2527}
2528
Douglas Gregor1db19de2010-01-19 21:36:55 +00002529CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002530 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002531 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002532 return Result;
2533}
2534
2535CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002536 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002537 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002538 return Result;
2539}
2540
Douglas Gregorb9790342010-01-22 21:44:22 +00002541} // end: extern "C"
2542
Douglas Gregor1db19de2010-01-19 21:36:55 +00002543//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002544// CXFile Operations.
2545//===----------------------------------------------------------------------===//
2546
2547extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002548CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002549 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002550 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002551
Steve Naroff88145032009-10-27 14:35:18 +00002552 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002553 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002554}
2555
2556time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002557 if (!SFile)
2558 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002559
Steve Naroff88145032009-10-27 14:35:18 +00002560 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2561 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002562}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563
Douglas Gregorb9790342010-01-22 21:44:22 +00002564CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2565 if (!tu)
2566 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002567
Douglas Gregorb9790342010-01-22 21:44:22 +00002568 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Douglas Gregorb9790342010-01-22 21:44:22 +00002570 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002571 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2572 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002573 return const_cast<FileEntry *>(File);
2574}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002575
Ted Kremenekfb480492010-01-13 21:46:36 +00002576} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002577
Ted Kremenekfb480492010-01-13 21:46:36 +00002578//===----------------------------------------------------------------------===//
2579// CXCursor Operations.
2580//===----------------------------------------------------------------------===//
2581
Ted Kremenekfb480492010-01-13 21:46:36 +00002582static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002583 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2584 return getDeclFromExpr(CE->getSubExpr());
2585
Ted Kremenekfb480492010-01-13 21:46:36 +00002586 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2587 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002588 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2589 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002590 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2591 return ME->getMemberDecl();
2592 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2593 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002594 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2595 return PRE->getProperty();
2596
Ted Kremenekfb480492010-01-13 21:46:36 +00002597 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2598 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002599 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2600 if (!CE->isElidable())
2601 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002602 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2603 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002604
Douglas Gregordb1314e2010-10-01 21:11:22 +00002605 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2606 return PE->getProtocol();
2607
Ted Kremenekfb480492010-01-13 21:46:36 +00002608 return 0;
2609}
2610
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002611static SourceLocation getLocationFromExpr(Expr *E) {
2612 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2613 return /*FIXME:*/Msg->getLeftLoc();
2614 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2615 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002616 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2617 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002618 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2619 return Member->getMemberLoc();
2620 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2621 return Ivar->getLocation();
2622 return E->getLocStart();
2623}
2624
Ted Kremenekfb480492010-01-13 21:46:36 +00002625extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002626
2627unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002628 CXCursorVisitor visitor,
2629 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002630 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002631
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002632 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2633 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002634 return CursorVis.VisitChildren(parent);
2635}
2636
David Chisnall3387c652010-11-03 14:12:26 +00002637#ifndef __has_feature
2638#define __has_feature(x) 0
2639#endif
2640#if __has_feature(blocks)
2641typedef enum CXChildVisitResult
2642 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2643
2644static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2645 CXClientData client_data) {
2646 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2647 return block(cursor, parent);
2648}
2649#else
2650// If we are compiled with a compiler that doesn't have native blocks support,
2651// define and call the block manually, so the
2652typedef struct _CXChildVisitResult
2653{
2654 void *isa;
2655 int flags;
2656 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002657 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2658 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002659} *CXCursorVisitorBlock;
2660
2661static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2662 CXClientData client_data) {
2663 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2664 return block->invoke(block, cursor, parent);
2665}
2666#endif
2667
2668
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002669unsigned clang_visitChildrenWithBlock(CXCursor parent,
2670 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002671 return clang_visitChildren(parent, visitWithBlock, block);
2672}
2673
Douglas Gregor78205d42010-01-20 21:45:58 +00002674static CXString getDeclSpelling(Decl *D) {
2675 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2676 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002677 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002678
Douglas Gregor78205d42010-01-20 21:45:58 +00002679 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002680 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002681
Douglas Gregor78205d42010-01-20 21:45:58 +00002682 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2683 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2684 // and returns different names. NamedDecl returns the class name and
2685 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002686 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002687
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002688 if (isa<UsingDirectiveDecl>(D))
2689 return createCXString("");
2690
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002691 llvm::SmallString<1024> S;
2692 llvm::raw_svector_ostream os(S);
2693 ND->printName(os);
2694
2695 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002696}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002697
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002698CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002699 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002700 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002701
Steve Narofff334b4e2009-09-02 18:26:48 +00002702 if (clang_isReference(C.kind)) {
2703 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002704 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002705 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002706 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002707 }
2708 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002709 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002710 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002711 }
2712 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002713 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002714 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002715 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002716 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002717 case CXCursor_CXXBaseSpecifier: {
2718 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2719 return createCXString(B->getType().getAsString());
2720 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002721 case CXCursor_TypeRef: {
2722 TypeDecl *Type = getCursorTypeRef(C).first;
2723 assert(Type && "Missing type decl");
2724
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002725 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2726 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002727 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002728 case CXCursor_TemplateRef: {
2729 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002730 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002731
2732 return createCXString(Template->getNameAsString());
2733 }
Douglas Gregor69319002010-08-31 23:48:11 +00002734
2735 case CXCursor_NamespaceRef: {
2736 NamedDecl *NS = getCursorNamespaceRef(C).first;
2737 assert(NS && "Missing namespace decl");
2738
2739 return createCXString(NS->getNameAsString());
2740 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002741
Douglas Gregora67e03f2010-09-09 21:42:20 +00002742 case CXCursor_MemberRef: {
2743 FieldDecl *Field = getCursorMemberRef(C).first;
2744 assert(Field && "Missing member decl");
2745
2746 return createCXString(Field->getNameAsString());
2747 }
2748
Douglas Gregor36897b02010-09-10 00:22:18 +00002749 case CXCursor_LabelRef: {
2750 LabelStmt *Label = getCursorLabelRef(C).first;
2751 assert(Label && "Missing label");
2752
2753 return createCXString(Label->getID()->getName());
2754 }
2755
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002756 case CXCursor_OverloadedDeclRef: {
2757 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2758 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2759 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2760 return createCXString(ND->getNameAsString());
2761 return createCXString("");
2762 }
2763 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2764 return createCXString(E->getName().getAsString());
2765 OverloadedTemplateStorage *Ovl
2766 = Storage.get<OverloadedTemplateStorage*>();
2767 if (Ovl->size() == 0)
2768 return createCXString("");
2769 return createCXString((*Ovl->begin())->getNameAsString());
2770 }
2771
Daniel Dunbaracca7252009-11-30 20:42:49 +00002772 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002773 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002774 }
2775 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002776
2777 if (clang_isExpression(C.kind)) {
2778 Decl *D = getDeclFromExpr(getCursorExpr(C));
2779 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002780 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002781 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002782 }
2783
Douglas Gregor36897b02010-09-10 00:22:18 +00002784 if (clang_isStatement(C.kind)) {
2785 Stmt *S = getCursorStmt(C);
2786 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2787 return createCXString(Label->getID()->getName());
2788
2789 return createCXString("");
2790 }
2791
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002792 if (C.kind == CXCursor_MacroInstantiation)
2793 return createCXString(getCursorMacroInstantiation(C)->getName()
2794 ->getNameStart());
2795
Douglas Gregor572feb22010-03-18 18:04:21 +00002796 if (C.kind == CXCursor_MacroDefinition)
2797 return createCXString(getCursorMacroDefinition(C)->getName()
2798 ->getNameStart());
2799
Douglas Gregorecdcb882010-10-20 22:00:55 +00002800 if (C.kind == CXCursor_InclusionDirective)
2801 return createCXString(getCursorInclusionDirective(C)->getFileName());
2802
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002803 if (clang_isDeclaration(C.kind))
2804 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002805
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002806 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002807}
2808
Douglas Gregor358559d2010-10-02 22:49:11 +00002809CXString clang_getCursorDisplayName(CXCursor C) {
2810 if (!clang_isDeclaration(C.kind))
2811 return clang_getCursorSpelling(C);
2812
2813 Decl *D = getCursorDecl(C);
2814 if (!D)
2815 return createCXString("");
2816
2817 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2818 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2819 D = FunTmpl->getTemplatedDecl();
2820
2821 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2822 llvm::SmallString<64> Str;
2823 llvm::raw_svector_ostream OS(Str);
2824 OS << Function->getNameAsString();
2825 if (Function->getPrimaryTemplate())
2826 OS << "<>";
2827 OS << "(";
2828 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2829 if (I)
2830 OS << ", ";
2831 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2832 }
2833
2834 if (Function->isVariadic()) {
2835 if (Function->getNumParams())
2836 OS << ", ";
2837 OS << "...";
2838 }
2839 OS << ")";
2840 return createCXString(OS.str());
2841 }
2842
2843 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2844 llvm::SmallString<64> Str;
2845 llvm::raw_svector_ostream OS(Str);
2846 OS << ClassTemplate->getNameAsString();
2847 OS << "<";
2848 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2849 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2850 if (I)
2851 OS << ", ";
2852
2853 NamedDecl *Param = Params->getParam(I);
2854 if (Param->getIdentifier()) {
2855 OS << Param->getIdentifier()->getName();
2856 continue;
2857 }
2858
2859 // There is no parameter name, which makes this tricky. Try to come up
2860 // with something useful that isn't too long.
2861 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2862 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2863 else if (NonTypeTemplateParmDecl *NTTP
2864 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2865 OS << NTTP->getType().getAsString(Policy);
2866 else
2867 OS << "template<...> class";
2868 }
2869
2870 OS << ">";
2871 return createCXString(OS.str());
2872 }
2873
2874 if (ClassTemplateSpecializationDecl *ClassSpec
2875 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2876 // If the type was explicitly written, use that.
2877 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2878 return createCXString(TSInfo->getType().getAsString(Policy));
2879
2880 llvm::SmallString<64> Str;
2881 llvm::raw_svector_ostream OS(Str);
2882 OS << ClassSpec->getNameAsString();
2883 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002884 ClassSpec->getTemplateArgs().data(),
2885 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002886 Policy);
2887 return createCXString(OS.str());
2888 }
2889
2890 return clang_getCursorSpelling(C);
2891}
2892
Ted Kremeneke68fff62010-02-17 00:41:32 +00002893CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002894 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002895 case CXCursor_FunctionDecl:
2896 return createCXString("FunctionDecl");
2897 case CXCursor_TypedefDecl:
2898 return createCXString("TypedefDecl");
2899 case CXCursor_EnumDecl:
2900 return createCXString("EnumDecl");
2901 case CXCursor_EnumConstantDecl:
2902 return createCXString("EnumConstantDecl");
2903 case CXCursor_StructDecl:
2904 return createCXString("StructDecl");
2905 case CXCursor_UnionDecl:
2906 return createCXString("UnionDecl");
2907 case CXCursor_ClassDecl:
2908 return createCXString("ClassDecl");
2909 case CXCursor_FieldDecl:
2910 return createCXString("FieldDecl");
2911 case CXCursor_VarDecl:
2912 return createCXString("VarDecl");
2913 case CXCursor_ParmDecl:
2914 return createCXString("ParmDecl");
2915 case CXCursor_ObjCInterfaceDecl:
2916 return createCXString("ObjCInterfaceDecl");
2917 case CXCursor_ObjCCategoryDecl:
2918 return createCXString("ObjCCategoryDecl");
2919 case CXCursor_ObjCProtocolDecl:
2920 return createCXString("ObjCProtocolDecl");
2921 case CXCursor_ObjCPropertyDecl:
2922 return createCXString("ObjCPropertyDecl");
2923 case CXCursor_ObjCIvarDecl:
2924 return createCXString("ObjCIvarDecl");
2925 case CXCursor_ObjCInstanceMethodDecl:
2926 return createCXString("ObjCInstanceMethodDecl");
2927 case CXCursor_ObjCClassMethodDecl:
2928 return createCXString("ObjCClassMethodDecl");
2929 case CXCursor_ObjCImplementationDecl:
2930 return createCXString("ObjCImplementationDecl");
2931 case CXCursor_ObjCCategoryImplDecl:
2932 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002933 case CXCursor_CXXMethod:
2934 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002935 case CXCursor_UnexposedDecl:
2936 return createCXString("UnexposedDecl");
2937 case CXCursor_ObjCSuperClassRef:
2938 return createCXString("ObjCSuperClassRef");
2939 case CXCursor_ObjCProtocolRef:
2940 return createCXString("ObjCProtocolRef");
2941 case CXCursor_ObjCClassRef:
2942 return createCXString("ObjCClassRef");
2943 case CXCursor_TypeRef:
2944 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002945 case CXCursor_TemplateRef:
2946 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002947 case CXCursor_NamespaceRef:
2948 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002949 case CXCursor_MemberRef:
2950 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002951 case CXCursor_LabelRef:
2952 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002953 case CXCursor_OverloadedDeclRef:
2954 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002955 case CXCursor_UnexposedExpr:
2956 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002957 case CXCursor_BlockExpr:
2958 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002959 case CXCursor_DeclRefExpr:
2960 return createCXString("DeclRefExpr");
2961 case CXCursor_MemberRefExpr:
2962 return createCXString("MemberRefExpr");
2963 case CXCursor_CallExpr:
2964 return createCXString("CallExpr");
2965 case CXCursor_ObjCMessageExpr:
2966 return createCXString("ObjCMessageExpr");
2967 case CXCursor_UnexposedStmt:
2968 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002969 case CXCursor_LabelStmt:
2970 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002971 case CXCursor_InvalidFile:
2972 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002973 case CXCursor_InvalidCode:
2974 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002975 case CXCursor_NoDeclFound:
2976 return createCXString("NoDeclFound");
2977 case CXCursor_NotImplemented:
2978 return createCXString("NotImplemented");
2979 case CXCursor_TranslationUnit:
2980 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002981 case CXCursor_UnexposedAttr:
2982 return createCXString("UnexposedAttr");
2983 case CXCursor_IBActionAttr:
2984 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002985 case CXCursor_IBOutletAttr:
2986 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002987 case CXCursor_IBOutletCollectionAttr:
2988 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002989 case CXCursor_PreprocessingDirective:
2990 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002991 case CXCursor_MacroDefinition:
2992 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002993 case CXCursor_MacroInstantiation:
2994 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002995 case CXCursor_InclusionDirective:
2996 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002997 case CXCursor_Namespace:
2998 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002999 case CXCursor_LinkageSpec:
3000 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003001 case CXCursor_CXXBaseSpecifier:
3002 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003003 case CXCursor_Constructor:
3004 return createCXString("CXXConstructor");
3005 case CXCursor_Destructor:
3006 return createCXString("CXXDestructor");
3007 case CXCursor_ConversionFunction:
3008 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003009 case CXCursor_TemplateTypeParameter:
3010 return createCXString("TemplateTypeParameter");
3011 case CXCursor_NonTypeTemplateParameter:
3012 return createCXString("NonTypeTemplateParameter");
3013 case CXCursor_TemplateTemplateParameter:
3014 return createCXString("TemplateTemplateParameter");
3015 case CXCursor_FunctionTemplate:
3016 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003017 case CXCursor_ClassTemplate:
3018 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003019 case CXCursor_ClassTemplatePartialSpecialization:
3020 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003021 case CXCursor_NamespaceAlias:
3022 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003023 case CXCursor_UsingDirective:
3024 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003025 case CXCursor_UsingDeclaration:
3026 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003027 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003028
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003029 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003030 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003031}
Steve Naroff89922f82009-08-31 00:59:03 +00003032
Ted Kremeneke68fff62010-02-17 00:41:32 +00003033enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3034 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003035 CXClientData client_data) {
3036 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003037
3038 // If our current best cursor is the construction of a temporary object,
3039 // don't replace that cursor with a type reference, because we want
3040 // clang_getCursor() to point at the constructor.
3041 if (clang_isExpression(BestCursor->kind) &&
3042 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3043 cursor.kind == CXCursor_TypeRef)
3044 return CXChildVisit_Recurse;
3045
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003046 *BestCursor = cursor;
3047 return CXChildVisit_Recurse;
3048}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003049
Douglas Gregorb9790342010-01-22 21:44:22 +00003050CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3051 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003052 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003053
Douglas Gregorb9790342010-01-22 21:44:22 +00003054 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003055 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3056
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003057 // Translate the given source location to make it point at the beginning of
3058 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003059 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003060
3061 // Guard against an invalid SourceLocation, or we may assert in one
3062 // of the following calls.
3063 if (SLoc.isInvalid())
3064 return clang_getNullCursor();
3065
Douglas Gregor40749ee2010-11-03 00:35:38 +00003066 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003067 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3068 CXXUnit->getASTContext().getLangOptions());
3069
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003070 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3071 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003072 // FIXME: Would be great to have a "hint" cursor, then walk from that
3073 // hint cursor upward until we find a cursor whose source range encloses
3074 // the region of interest, rather than starting from the translation unit.
3075 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003076 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003077 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003078 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003079 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003080
3081 if (Logging) {
3082 CXFile SearchFile;
3083 unsigned SearchLine, SearchColumn;
3084 CXFile ResultFile;
3085 unsigned ResultLine, ResultColumn;
3086 CXString SearchFileName, ResultFileName, KindSpelling;
3087 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3088
3089 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3090 0);
3091 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3092 &ResultColumn, 0);
3093 SearchFileName = clang_getFileName(SearchFile);
3094 ResultFileName = clang_getFileName(ResultFile);
3095 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3096 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3097 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3098 clang_getCString(KindSpelling),
3099 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3100 clang_disposeString(SearchFileName);
3101 clang_disposeString(ResultFileName);
3102 clang_disposeString(KindSpelling);
3103 }
3104
Ted Kremeneke68fff62010-02-17 00:41:32 +00003105 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003106}
3107
Ted Kremenek73885552009-11-17 19:28:59 +00003108CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003109 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003110}
3111
3112unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003113 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003114}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003115
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003116unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003117 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3118}
3119
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003120unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003121 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3122}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003123
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003124unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003125 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3126}
3127
Douglas Gregor97b98722010-01-19 23:20:36 +00003128unsigned clang_isExpression(enum CXCursorKind K) {
3129 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3130}
3131
3132unsigned clang_isStatement(enum CXCursorKind K) {
3133 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3134}
3135
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003136unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3137 return K == CXCursor_TranslationUnit;
3138}
3139
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003140unsigned clang_isPreprocessing(enum CXCursorKind K) {
3141 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3142}
3143
Ted Kremenekad6eff62010-03-08 21:17:29 +00003144unsigned clang_isUnexposed(enum CXCursorKind K) {
3145 switch (K) {
3146 case CXCursor_UnexposedDecl:
3147 case CXCursor_UnexposedExpr:
3148 case CXCursor_UnexposedStmt:
3149 case CXCursor_UnexposedAttr:
3150 return true;
3151 default:
3152 return false;
3153 }
3154}
3155
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003156CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003157 return C.kind;
3158}
3159
Douglas Gregor98258af2010-01-18 22:46:11 +00003160CXSourceLocation clang_getCursorLocation(CXCursor C) {
3161 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003162 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003163 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003164 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3165 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003166 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003167 }
3168
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003169 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003170 std::pair<ObjCProtocolDecl *, SourceLocation> P
3171 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003172 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003173 }
3174
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003175 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003176 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3177 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003178 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003179 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003180
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003181 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003182 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003183 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003184 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003185
3186 case CXCursor_TemplateRef: {
3187 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3188 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3189 }
3190
Douglas Gregor69319002010-08-31 23:48:11 +00003191 case CXCursor_NamespaceRef: {
3192 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3193 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3194 }
3195
Douglas Gregora67e03f2010-09-09 21:42:20 +00003196 case CXCursor_MemberRef: {
3197 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3198 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3199 }
3200
Ted Kremenek3064ef92010-08-27 21:34:58 +00003201 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003202 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3203 if (!BaseSpec)
3204 return clang_getNullLocation();
3205
3206 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3207 return cxloc::translateSourceLocation(getCursorContext(C),
3208 TSInfo->getTypeLoc().getBeginLoc());
3209
3210 return cxloc::translateSourceLocation(getCursorContext(C),
3211 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003212 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003213
Douglas Gregor36897b02010-09-10 00:22:18 +00003214 case CXCursor_LabelRef: {
3215 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3216 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3217 }
3218
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003219 case CXCursor_OverloadedDeclRef:
3220 return cxloc::translateSourceLocation(getCursorContext(C),
3221 getCursorOverloadedDeclRef(C).second);
3222
Douglas Gregorf46034a2010-01-18 23:41:10 +00003223 default:
3224 // FIXME: Need a way to enumerate all non-reference cases.
3225 llvm_unreachable("Missed a reference kind");
3226 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003227 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003228
3229 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003230 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003231 getLocationFromExpr(getCursorExpr(C)));
3232
Douglas Gregor36897b02010-09-10 00:22:18 +00003233 if (clang_isStatement(C.kind))
3234 return cxloc::translateSourceLocation(getCursorContext(C),
3235 getCursorStmt(C)->getLocStart());
3236
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003237 if (C.kind == CXCursor_PreprocessingDirective) {
3238 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3239 return cxloc::translateSourceLocation(getCursorContext(C), L);
3240 }
Douglas Gregor48072312010-03-18 15:23:44 +00003241
3242 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003243 SourceLocation L
3244 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003245 return cxloc::translateSourceLocation(getCursorContext(C), L);
3246 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003247
3248 if (C.kind == CXCursor_MacroDefinition) {
3249 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3250 return cxloc::translateSourceLocation(getCursorContext(C), L);
3251 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003252
3253 if (C.kind == CXCursor_InclusionDirective) {
3254 SourceLocation L
3255 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3256 return cxloc::translateSourceLocation(getCursorContext(C), L);
3257 }
3258
Ted Kremenek9a700d22010-05-12 06:16:13 +00003259 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003260 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003261
Douglas Gregorf46034a2010-01-18 23:41:10 +00003262 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003263 SourceLocation Loc = D->getLocation();
3264 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3265 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003266 // FIXME: Multiple variables declared in a single declaration
3267 // currently lack the information needed to correctly determine their
3268 // ranges when accounting for the type-specifier. We use context
3269 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3270 // and if so, whether it is the first decl.
3271 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3272 if (!cxcursor::isFirstInDeclGroup(C))
3273 Loc = VD->getLocation();
3274 }
3275
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003276 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003277}
Douglas Gregora7bde202010-01-19 00:34:46 +00003278
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003279} // end extern "C"
3280
3281static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003282 if (clang_isReference(C.kind)) {
3283 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003284 case CXCursor_ObjCSuperClassRef:
3285 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003286
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003287 case CXCursor_ObjCProtocolRef:
3288 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003289
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003290 case CXCursor_ObjCClassRef:
3291 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003292
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003293 case CXCursor_TypeRef:
3294 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003295
3296 case CXCursor_TemplateRef:
3297 return getCursorTemplateRef(C).second;
3298
Douglas Gregor69319002010-08-31 23:48:11 +00003299 case CXCursor_NamespaceRef:
3300 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003301
3302 case CXCursor_MemberRef:
3303 return getCursorMemberRef(C).second;
3304
Ted Kremenek3064ef92010-08-27 21:34:58 +00003305 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003306 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003307
Douglas Gregor36897b02010-09-10 00:22:18 +00003308 case CXCursor_LabelRef:
3309 return getCursorLabelRef(C).second;
3310
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003311 case CXCursor_OverloadedDeclRef:
3312 return getCursorOverloadedDeclRef(C).second;
3313
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003314 default:
3315 // FIXME: Need a way to enumerate all non-reference cases.
3316 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003317 }
3318 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003319
3320 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003321 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003322
3323 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003324 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003325
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003326 if (C.kind == CXCursor_PreprocessingDirective)
3327 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003328
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003329 if (C.kind == CXCursor_MacroInstantiation)
3330 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003331
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003332 if (C.kind == CXCursor_MacroDefinition)
3333 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003334
3335 if (C.kind == CXCursor_InclusionDirective)
3336 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3337
Ted Kremenek007a7c92010-11-01 23:26:51 +00003338 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3339 Decl *D = cxcursor::getCursorDecl(C);
3340 SourceRange R = D->getSourceRange();
3341 // FIXME: Multiple variables declared in a single declaration
3342 // currently lack the information needed to correctly determine their
3343 // ranges when accounting for the type-specifier. We use context
3344 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3345 // and if so, whether it is the first decl.
3346 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3347 if (!cxcursor::isFirstInDeclGroup(C))
3348 R.setBegin(VD->getLocation());
3349 }
3350 return R;
3351 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003352 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003353
3354extern "C" {
3355
3356CXSourceRange clang_getCursorExtent(CXCursor C) {
3357 SourceRange R = getRawCursorExtent(C);
3358 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003359 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003360
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003361 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003362}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003363
3364CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003365 if (clang_isInvalid(C.kind))
3366 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003367
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003368 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003369 if (clang_isDeclaration(C.kind)) {
3370 Decl *D = getCursorDecl(C);
3371 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3372 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3373 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3374 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3375 if (ObjCForwardProtocolDecl *Protocols
3376 = dyn_cast<ObjCForwardProtocolDecl>(D))
3377 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3378
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003379 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003380 }
3381
Douglas Gregor97b98722010-01-19 23:20:36 +00003382 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003383 Expr *E = getCursorExpr(C);
3384 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003385 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003386 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003387
3388 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3389 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3390
Douglas Gregor97b98722010-01-19 23:20:36 +00003391 return clang_getNullCursor();
3392 }
3393
Douglas Gregor36897b02010-09-10 00:22:18 +00003394 if (clang_isStatement(C.kind)) {
3395 Stmt *S = getCursorStmt(C);
3396 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3397 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3398 getCursorASTUnit(C));
3399
3400 return clang_getNullCursor();
3401 }
3402
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003403 if (C.kind == CXCursor_MacroInstantiation) {
3404 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3405 return MakeMacroDefinitionCursor(Def, CXXUnit);
3406 }
3407
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003408 if (!clang_isReference(C.kind))
3409 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003410
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003411 switch (C.kind) {
3412 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003413 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003414
3415 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003416 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003417
3418 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003419 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003420
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003421 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003422 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003423
3424 case CXCursor_TemplateRef:
3425 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3426
Douglas Gregor69319002010-08-31 23:48:11 +00003427 case CXCursor_NamespaceRef:
3428 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3429
Douglas Gregora67e03f2010-09-09 21:42:20 +00003430 case CXCursor_MemberRef:
3431 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3432
Ted Kremenek3064ef92010-08-27 21:34:58 +00003433 case CXCursor_CXXBaseSpecifier: {
3434 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3435 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3436 CXXUnit));
3437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438
Douglas Gregor36897b02010-09-10 00:22:18 +00003439 case CXCursor_LabelRef:
3440 // FIXME: We end up faking the "parent" declaration here because we
3441 // don't want to make CXCursor larger.
3442 return MakeCXCursor(getCursorLabelRef(C).first,
3443 CXXUnit->getASTContext().getTranslationUnitDecl(),
3444 CXXUnit);
3445
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003446 case CXCursor_OverloadedDeclRef:
3447 return C;
3448
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003449 default:
3450 // We would prefer to enumerate all non-reference cursor kinds here.
3451 llvm_unreachable("Unhandled reference cursor kind");
3452 break;
3453 }
3454 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003455
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003456 return clang_getNullCursor();
3457}
3458
Douglas Gregorb6998662010-01-19 19:34:47 +00003459CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003460 if (clang_isInvalid(C.kind))
3461 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003462
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003463 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003464
Douglas Gregorb6998662010-01-19 19:34:47 +00003465 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003466 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003467 C = clang_getCursorReferenced(C);
3468 WasReference = true;
3469 }
3470
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003471 if (C.kind == CXCursor_MacroInstantiation)
3472 return clang_getCursorReferenced(C);
3473
Douglas Gregorb6998662010-01-19 19:34:47 +00003474 if (!clang_isDeclaration(C.kind))
3475 return clang_getNullCursor();
3476
3477 Decl *D = getCursorDecl(C);
3478 if (!D)
3479 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003480
Douglas Gregorb6998662010-01-19 19:34:47 +00003481 switch (D->getKind()) {
3482 // Declaration kinds that don't really separate the notions of
3483 // declaration and definition.
3484 case Decl::Namespace:
3485 case Decl::Typedef:
3486 case Decl::TemplateTypeParm:
3487 case Decl::EnumConstant:
3488 case Decl::Field:
3489 case Decl::ObjCIvar:
3490 case Decl::ObjCAtDefsField:
3491 case Decl::ImplicitParam:
3492 case Decl::ParmVar:
3493 case Decl::NonTypeTemplateParm:
3494 case Decl::TemplateTemplateParm:
3495 case Decl::ObjCCategoryImpl:
3496 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003497 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003498 case Decl::LinkageSpec:
3499 case Decl::ObjCPropertyImpl:
3500 case Decl::FileScopeAsm:
3501 case Decl::StaticAssert:
3502 case Decl::Block:
3503 return C;
3504
3505 // Declaration kinds that don't make any sense here, but are
3506 // nonetheless harmless.
3507 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003508 break;
3509
3510 // Declaration kinds for which the definition is not resolvable.
3511 case Decl::UnresolvedUsingTypename:
3512 case Decl::UnresolvedUsingValue:
3513 break;
3514
3515 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003516 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3517 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003518
3519 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003520 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003521
3522 case Decl::Enum:
3523 case Decl::Record:
3524 case Decl::CXXRecord:
3525 case Decl::ClassTemplateSpecialization:
3526 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003527 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003528 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003529 return clang_getNullCursor();
3530
3531 case Decl::Function:
3532 case Decl::CXXMethod:
3533 case Decl::CXXConstructor:
3534 case Decl::CXXDestructor:
3535 case Decl::CXXConversion: {
3536 const FunctionDecl *Def = 0;
3537 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003538 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003539 return clang_getNullCursor();
3540 }
3541
3542 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003543 // Ask the variable if it has a definition.
3544 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3545 return MakeCXCursor(Def, CXXUnit);
3546 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003547 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003548
Douglas Gregorb6998662010-01-19 19:34:47 +00003549 case Decl::FunctionTemplate: {
3550 const FunctionDecl *Def = 0;
3551 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003552 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003553 return clang_getNullCursor();
3554 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003555
Douglas Gregorb6998662010-01-19 19:34:47 +00003556 case Decl::ClassTemplate: {
3557 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003558 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003559 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003560 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003561 return clang_getNullCursor();
3562 }
3563
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003564 case Decl::Using:
3565 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3566 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003567
3568 case Decl::UsingShadow:
3569 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003570 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003571 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003572
3573 case Decl::ObjCMethod: {
3574 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3575 if (Method->isThisDeclarationADefinition())
3576 return C;
3577
3578 // Dig out the method definition in the associated
3579 // @implementation, if we have it.
3580 // FIXME: The ASTs should make finding the definition easier.
3581 if (ObjCInterfaceDecl *Class
3582 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3583 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3584 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3585 Method->isInstanceMethod()))
3586 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003587 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003588
3589 return clang_getNullCursor();
3590 }
3591
3592 case Decl::ObjCCategory:
3593 if (ObjCCategoryImplDecl *Impl
3594 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003595 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003596 return clang_getNullCursor();
3597
3598 case Decl::ObjCProtocol:
3599 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3600 return C;
3601 return clang_getNullCursor();
3602
3603 case Decl::ObjCInterface:
3604 // There are two notions of a "definition" for an Objective-C
3605 // class: the interface and its implementation. When we resolved a
3606 // reference to an Objective-C class, produce the @interface as
3607 // the definition; when we were provided with the interface,
3608 // produce the @implementation as the definition.
3609 if (WasReference) {
3610 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3611 return C;
3612 } else if (ObjCImplementationDecl *Impl
3613 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003614 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003615 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003616
Douglas Gregorb6998662010-01-19 19:34:47 +00003617 case Decl::ObjCProperty:
3618 // FIXME: We don't really know where to find the
3619 // ObjCPropertyImplDecls that implement this property.
3620 return clang_getNullCursor();
3621
3622 case Decl::ObjCCompatibleAlias:
3623 if (ObjCInterfaceDecl *Class
3624 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3625 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003626 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003627
Douglas Gregorb6998662010-01-19 19:34:47 +00003628 return clang_getNullCursor();
3629
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003630 case Decl::ObjCForwardProtocol:
3631 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3632 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003633
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003634 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003635 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003636 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003637
3638 case Decl::Friend:
3639 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003640 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003641 return clang_getNullCursor();
3642
3643 case Decl::FriendTemplate:
3644 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003645 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003646 return clang_getNullCursor();
3647 }
3648
3649 return clang_getNullCursor();
3650}
3651
3652unsigned clang_isCursorDefinition(CXCursor C) {
3653 if (!clang_isDeclaration(C.kind))
3654 return 0;
3655
3656 return clang_getCursorDefinition(C) == C;
3657}
3658
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003659unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003660 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003661 return 0;
3662
3663 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3664 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3665 return E->getNumDecls();
3666
3667 if (OverloadedTemplateStorage *S
3668 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3669 return S->size();
3670
3671 Decl *D = Storage.get<Decl*>();
3672 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003673 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003674 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3675 return Classes->size();
3676 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3677 return Protocols->protocol_size();
3678
3679 return 0;
3680}
3681
3682CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003683 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003684 return clang_getNullCursor();
3685
3686 if (index >= clang_getNumOverloadedDecls(cursor))
3687 return clang_getNullCursor();
3688
3689 ASTUnit *Unit = getCursorASTUnit(cursor);
3690 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3691 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3692 return MakeCXCursor(E->decls_begin()[index], Unit);
3693
3694 if (OverloadedTemplateStorage *S
3695 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3696 return MakeCXCursor(S->begin()[index], Unit);
3697
3698 Decl *D = Storage.get<Decl*>();
3699 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3700 // FIXME: This is, unfortunately, linear time.
3701 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3702 std::advance(Pos, index);
3703 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3704 }
3705
3706 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3707 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3708
3709 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3710 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3711
3712 return clang_getNullCursor();
3713}
3714
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003715void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003716 const char **startBuf,
3717 const char **endBuf,
3718 unsigned *startLine,
3719 unsigned *startColumn,
3720 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003721 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003722 assert(getCursorDecl(C) && "CXCursor has null decl");
3723 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003724 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3725 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003726
Steve Naroff4ade6d62009-09-23 17:52:52 +00003727 SourceManager &SM = FD->getASTContext().getSourceManager();
3728 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3729 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3730 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3731 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3732 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3733 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3734}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003735
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003736void clang_enableStackTraces(void) {
3737 llvm::sys::PrintStackTraceOnErrorSignal();
3738}
3739
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003740void clang_executeOnThread(void (*fn)(void*), void *user_data,
3741 unsigned stack_size) {
3742 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3743}
3744
Ted Kremenekfb480492010-01-13 21:46:36 +00003745} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003746
Ted Kremenekfb480492010-01-13 21:46:36 +00003747//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003748// Token-based Operations.
3749//===----------------------------------------------------------------------===//
3750
3751/* CXToken layout:
3752 * int_data[0]: a CXTokenKind
3753 * int_data[1]: starting token location
3754 * int_data[2]: token length
3755 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003756 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003757 * otherwise unused.
3758 */
3759extern "C" {
3760
3761CXTokenKind clang_getTokenKind(CXToken CXTok) {
3762 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3763}
3764
3765CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3766 switch (clang_getTokenKind(CXTok)) {
3767 case CXToken_Identifier:
3768 case CXToken_Keyword:
3769 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003770 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3771 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003772
3773 case CXToken_Literal: {
3774 // We have stashed the starting pointer in the ptr_data field. Use it.
3775 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003776 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003777 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003778
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003779 case CXToken_Punctuation:
3780 case CXToken_Comment:
3781 break;
3782 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003783
3784 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003785 // deconstructing the source location.
3786 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3787 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003788 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003789
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003790 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3791 std::pair<FileID, unsigned> LocInfo
3792 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003793 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003794 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003795 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3796 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003797 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003798
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003799 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003800}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003801
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3803 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3804 if (!CXXUnit)
3805 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3808 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3809}
3810
3811CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3812 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003813 if (!CXXUnit)
3814 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003815
3816 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003817 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3818}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003819
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3821 CXToken **Tokens, unsigned *NumTokens) {
3822 if (Tokens)
3823 *Tokens = 0;
3824 if (NumTokens)
3825 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003826
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003827 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3828 if (!CXXUnit || !Tokens || !NumTokens)
3829 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003830
Douglas Gregorbdf60622010-03-05 21:16:25 +00003831 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3832
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003833 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834 if (R.isInvalid())
3835 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3838 std::pair<FileID, unsigned> BeginLocInfo
3839 = SourceMgr.getDecomposedLoc(R.getBegin());
3840 std::pair<FileID, unsigned> EndLocInfo
3841 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003842
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003843 // Cannot tokenize across files.
3844 if (BeginLocInfo.first != EndLocInfo.first)
3845 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
3847 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003848 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003849 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003850 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003851 if (Invalid)
3852 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003853
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003854 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3855 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003856 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003857 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003860 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003861 llvm::SmallVector<CXToken, 32> CXTokens;
3862 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003863 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 do {
3865 // Lex the next token
3866 Lex.LexFromRawLexer(Tok);
3867 if (Tok.is(tok::eof))
3868 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870 // Initialize the CXToken.
3871 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003872
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003873 // - Common fields
3874 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3875 CXTok.int_data[2] = Tok.getLength();
3876 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003877
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 // - Kind-specific fields
3879 if (Tok.isLiteral()) {
3880 CXTok.int_data[0] = CXToken_Literal;
3881 CXTok.ptr_data = (void *)Tok.getLiteralData();
3882 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003883 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003884 std::pair<FileID, unsigned> LocInfo
3885 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003886 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003887 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003888 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3889 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003890 return;
3891
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003892 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893 IdentifierInfo *II
3894 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003895
David Chisnall096428b2010-10-13 21:44:48 +00003896 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003897 CXTok.int_data[0] = CXToken_Keyword;
3898 }
3899 else {
3900 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3901 CXToken_Identifier
3902 : CXToken_Keyword;
3903 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003904 CXTok.ptr_data = II;
3905 } else if (Tok.is(tok::comment)) {
3906 CXTok.int_data[0] = CXToken_Comment;
3907 CXTok.ptr_data = 0;
3908 } else {
3909 CXTok.int_data[0] = CXToken_Punctuation;
3910 CXTok.ptr_data = 0;
3911 }
3912 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003913 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003914 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003915
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003916 if (CXTokens.empty())
3917 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003918
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003919 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3920 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3921 *NumTokens = CXTokens.size();
3922}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003923
Ted Kremenek6db61092010-05-05 00:55:15 +00003924void clang_disposeTokens(CXTranslationUnit TU,
3925 CXToken *Tokens, unsigned NumTokens) {
3926 free(Tokens);
3927}
3928
3929} // end: extern "C"
3930
3931//===----------------------------------------------------------------------===//
3932// Token annotation APIs.
3933//===----------------------------------------------------------------------===//
3934
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003935typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003936static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3937 CXCursor parent,
3938 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003939namespace {
3940class AnnotateTokensWorker {
3941 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003942 CXToken *Tokens;
3943 CXCursor *Cursors;
3944 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003945 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003946 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003947 CursorVisitor AnnotateVis;
3948 SourceManager &SrcMgr;
3949
3950 bool MoreTokens() const { return TokIdx < NumTokens; }
3951 unsigned NextToken() const { return TokIdx; }
3952 void AdvanceToken() { ++TokIdx; }
3953 SourceLocation GetTokenLoc(unsigned tokI) {
3954 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3955 }
3956
Ted Kremenek6db61092010-05-05 00:55:15 +00003957public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003958 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003959 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3960 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003961 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003962 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003963 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3964 Decl::MaxPCHLevel, RegionOfInterest),
3965 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003966
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003967 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003968 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003969 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003970 void AnnotateTokens() {
3971 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3972 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003973};
3974}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003975
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003976void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3977 // Walk the AST within the region of interest, annotating tokens
3978 // along the way.
3979 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003980
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003981 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3982 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003983 if (Pos != Annotated.end() &&
3984 (clang_isInvalid(Cursors[I].kind) ||
3985 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003986 Cursors[I] = Pos->second;
3987 }
3988
3989 // Finish up annotating any tokens left.
3990 if (!MoreTokens())
3991 return;
3992
3993 const CXCursor &C = clang_getNullCursor();
3994 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3995 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3996 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003997 }
3998}
3999
Ted Kremenek6db61092010-05-05 00:55:15 +00004000enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004001AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004002 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004003 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004004 if (cursorRange.isInvalid())
4005 return CXChildVisit_Recurse;
4006
Douglas Gregor4419b672010-10-21 06:10:04 +00004007 if (clang_isPreprocessing(cursor.kind)) {
4008 // For macro instantiations, just note where the beginning of the macro
4009 // instantiation occurs.
4010 if (cursor.kind == CXCursor_MacroInstantiation) {
4011 Annotated[Loc.int_data] = cursor;
4012 return CXChildVisit_Recurse;
4013 }
4014
Douglas Gregor4419b672010-10-21 06:10:04 +00004015 // Items in the preprocessing record are kept separate from items in
4016 // declarations, so we keep a separate token index.
4017 unsigned SavedTokIdx = TokIdx;
4018 TokIdx = PreprocessingTokIdx;
4019
4020 // Skip tokens up until we catch up to the beginning of the preprocessing
4021 // entry.
4022 while (MoreTokens()) {
4023 const unsigned I = NextToken();
4024 SourceLocation TokLoc = GetTokenLoc(I);
4025 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4026 case RangeBefore:
4027 AdvanceToken();
4028 continue;
4029 case RangeAfter:
4030 case RangeOverlap:
4031 break;
4032 }
4033 break;
4034 }
4035
4036 // Look at all of the tokens within this range.
4037 while (MoreTokens()) {
4038 const unsigned I = NextToken();
4039 SourceLocation TokLoc = GetTokenLoc(I);
4040 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4041 case RangeBefore:
4042 assert(0 && "Infeasible");
4043 case RangeAfter:
4044 break;
4045 case RangeOverlap:
4046 Cursors[I] = cursor;
4047 AdvanceToken();
4048 continue;
4049 }
4050 break;
4051 }
4052
4053 // Save the preprocessing token index; restore the non-preprocessing
4054 // token index.
4055 PreprocessingTokIdx = TokIdx;
4056 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004057 return CXChildVisit_Recurse;
4058 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004059
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004060 if (cursorRange.isInvalid())
4061 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004062
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004063 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4064
Ted Kremeneka333c662010-05-12 05:29:33 +00004065 // Adjust the annotated range based specific declarations.
4066 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4067 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004068 Decl *D = cxcursor::getCursorDecl(cursor);
4069 // Don't visit synthesized ObjC methods, since they have no syntatic
4070 // representation in the source.
4071 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4072 if (MD->isSynthesized())
4073 return CXChildVisit_Continue;
4074 }
4075 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004076 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4077 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004078 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004079 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004080 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004081 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004082 }
4083 }
4084 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004085
Ted Kremenek3f404602010-08-14 01:14:06 +00004086 // If the location of the cursor occurs within a macro instantiation, record
4087 // the spelling location of the cursor in our annotation map. We can then
4088 // paper over the token labelings during a post-processing step to try and
4089 // get cursor mappings for tokens that are the *arguments* of a macro
4090 // instantiation.
4091 if (L.isMacroID()) {
4092 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4093 // Only invalidate the old annotation if it isn't part of a preprocessing
4094 // directive. Here we assume that the default construction of CXCursor
4095 // results in CXCursor.kind being an initialized value (i.e., 0). If
4096 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004097
Ted Kremenek3f404602010-08-14 01:14:06 +00004098 CXCursor &oldC = Annotated[rawEncoding];
4099 if (!clang_isPreprocessing(oldC.kind))
4100 oldC = cursor;
4101 }
4102
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004103 const enum CXCursorKind K = clang_getCursorKind(parent);
4104 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004105 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4106 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004107
4108 while (MoreTokens()) {
4109 const unsigned I = NextToken();
4110 SourceLocation TokLoc = GetTokenLoc(I);
4111 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4112 case RangeBefore:
4113 Cursors[I] = updateC;
4114 AdvanceToken();
4115 continue;
4116 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004117 case RangeOverlap:
4118 break;
4119 }
4120 break;
4121 }
4122
4123 // Visit children to get their cursor information.
4124 const unsigned BeforeChildren = NextToken();
4125 VisitChildren(cursor);
4126 const unsigned AfterChildren = NextToken();
4127
4128 // Adjust 'Last' to the last token within the extent of the cursor.
4129 while (MoreTokens()) {
4130 const unsigned I = NextToken();
4131 SourceLocation TokLoc = GetTokenLoc(I);
4132 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4133 case RangeBefore:
4134 assert(0 && "Infeasible");
4135 case RangeAfter:
4136 break;
4137 case RangeOverlap:
4138 Cursors[I] = updateC;
4139 AdvanceToken();
4140 continue;
4141 }
4142 break;
4143 }
4144 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004145
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004146 // Scan the tokens that are at the beginning of the cursor, but are not
4147 // capture by the child cursors.
4148
4149 // For AST elements within macros, rely on a post-annotate pass to
4150 // to correctly annotate the tokens with cursors. Otherwise we can
4151 // get confusing results of having tokens that map to cursors that really
4152 // are expanded by an instantiation.
4153 if (L.isMacroID())
4154 cursor = clang_getNullCursor();
4155
4156 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4157 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4158 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004159
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004160 Cursors[I] = cursor;
4161 }
4162 // Scan the tokens that are at the end of the cursor, but are not captured
4163 // but the child cursors.
4164 for (unsigned I = AfterChildren; I != Last; ++I)
4165 Cursors[I] = cursor;
4166
4167 TokIdx = Last;
4168 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004169}
4170
Ted Kremenek6db61092010-05-05 00:55:15 +00004171static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4172 CXCursor parent,
4173 CXClientData client_data) {
4174 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4175}
4176
Ted Kremenekab979612010-11-11 08:05:23 +00004177// This gets run a separate thread to avoid stack blowout.
4178static void runAnnotateTokensWorker(void *UserData) {
4179 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4180}
4181
Ted Kremenek6db61092010-05-05 00:55:15 +00004182extern "C" {
4183
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004184void clang_annotateTokens(CXTranslationUnit TU,
4185 CXToken *Tokens, unsigned NumTokens,
4186 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004187
4188 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004189 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004190
Douglas Gregor4419b672010-10-21 06:10:04 +00004191 // Any token we don't specifically annotate will have a NULL cursor.
4192 CXCursor C = clang_getNullCursor();
4193 for (unsigned I = 0; I != NumTokens; ++I)
4194 Cursors[I] = C;
4195
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004196 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004197 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004198 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004199
Douglas Gregorbdf60622010-03-05 21:16:25 +00004200 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004201
Douglas Gregor0396f462010-03-19 05:22:59 +00004202 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004203 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004204 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4205 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004206 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4207 clang_getTokenLocation(TU,
4208 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004209
Douglas Gregor0396f462010-03-19 05:22:59 +00004210 // A mapping from the source locations found when re-lexing or traversing the
4211 // region of interest to the corresponding cursors.
4212 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004213
4214 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004215 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004216 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4217 std::pair<FileID, unsigned> BeginLocInfo
4218 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4219 std::pair<FileID, unsigned> EndLocInfo
4220 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004221
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004222 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004223 bool Invalid = false;
4224 if (BeginLocInfo.first == EndLocInfo.first &&
4225 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4226 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004227 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4228 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004230 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004231 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232
4233 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004234 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004235 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004236 Token Tok;
4237 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004239 reprocess:
4240 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4241 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004242 // don't see it while preprocessing these tokens later, but keep track
4243 // of all of the token locations inside this preprocessing directive so
4244 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 //
4246 // FIXME: Some simple tests here could identify macro definitions and
4247 // #undefs, to provide specific cursor kinds for those.
4248 std::vector<SourceLocation> Locations;
4249 do {
4250 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004251 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004252 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004253
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004254 using namespace cxcursor;
4255 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004256 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4257 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004258 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004259 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4260 Annotated[Locations[I].getRawEncoding()] = Cursor;
4261 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004262
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004263 if (Tok.isAtStartOfLine())
4264 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004265
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004266 continue;
4267 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004268
Douglas Gregor48072312010-03-18 15:23:44 +00004269 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004270 break;
4271 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004272 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004273
Douglas Gregor0396f462010-03-19 05:22:59 +00004274 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004275 // a specific cursor.
4276 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4277 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004278
4279 // Run the worker within a CrashRecoveryContext.
4280 llvm::CrashRecoveryContext CRC;
4281 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4282 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4283 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004284}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004285} // end: extern "C"
4286
4287//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004288// Operations for querying linkage of a cursor.
4289//===----------------------------------------------------------------------===//
4290
4291extern "C" {
4292CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004293 if (!clang_isDeclaration(cursor.kind))
4294 return CXLinkage_Invalid;
4295
Ted Kremenek16b42592010-03-03 06:36:57 +00004296 Decl *D = cxcursor::getCursorDecl(cursor);
4297 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4298 switch (ND->getLinkage()) {
4299 case NoLinkage: return CXLinkage_NoLinkage;
4300 case InternalLinkage: return CXLinkage_Internal;
4301 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4302 case ExternalLinkage: return CXLinkage_External;
4303 };
4304
4305 return CXLinkage_Invalid;
4306}
4307} // end: extern "C"
4308
4309//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004310// Operations for querying language of a cursor.
4311//===----------------------------------------------------------------------===//
4312
4313static CXLanguageKind getDeclLanguage(const Decl *D) {
4314 switch (D->getKind()) {
4315 default:
4316 break;
4317 case Decl::ImplicitParam:
4318 case Decl::ObjCAtDefsField:
4319 case Decl::ObjCCategory:
4320 case Decl::ObjCCategoryImpl:
4321 case Decl::ObjCClass:
4322 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004323 case Decl::ObjCForwardProtocol:
4324 case Decl::ObjCImplementation:
4325 case Decl::ObjCInterface:
4326 case Decl::ObjCIvar:
4327 case Decl::ObjCMethod:
4328 case Decl::ObjCProperty:
4329 case Decl::ObjCPropertyImpl:
4330 case Decl::ObjCProtocol:
4331 return CXLanguage_ObjC;
4332 case Decl::CXXConstructor:
4333 case Decl::CXXConversion:
4334 case Decl::CXXDestructor:
4335 case Decl::CXXMethod:
4336 case Decl::CXXRecord:
4337 case Decl::ClassTemplate:
4338 case Decl::ClassTemplatePartialSpecialization:
4339 case Decl::ClassTemplateSpecialization:
4340 case Decl::Friend:
4341 case Decl::FriendTemplate:
4342 case Decl::FunctionTemplate:
4343 case Decl::LinkageSpec:
4344 case Decl::Namespace:
4345 case Decl::NamespaceAlias:
4346 case Decl::NonTypeTemplateParm:
4347 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004348 case Decl::TemplateTemplateParm:
4349 case Decl::TemplateTypeParm:
4350 case Decl::UnresolvedUsingTypename:
4351 case Decl::UnresolvedUsingValue:
4352 case Decl::Using:
4353 case Decl::UsingDirective:
4354 case Decl::UsingShadow:
4355 return CXLanguage_CPlusPlus;
4356 }
4357
4358 return CXLanguage_C;
4359}
4360
4361extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004362
4363enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4364 if (clang_isDeclaration(cursor.kind))
4365 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4366 if (D->hasAttr<UnavailableAttr>() ||
4367 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4368 return CXAvailability_Available;
4369
4370 if (D->hasAttr<DeprecatedAttr>())
4371 return CXAvailability_Deprecated;
4372 }
4373
4374 return CXAvailability_Available;
4375}
4376
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004377CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4378 if (clang_isDeclaration(cursor.kind))
4379 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4380
4381 return CXLanguage_Invalid;
4382}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004383
4384CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4385 if (clang_isDeclaration(cursor.kind)) {
4386 if (Decl *D = getCursorDecl(cursor)) {
4387 DeclContext *DC = D->getDeclContext();
4388 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4389 }
4390 }
4391
4392 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4393 if (Decl *D = getCursorDecl(cursor))
4394 return MakeCXCursor(D, getCursorASTUnit(cursor));
4395 }
4396
4397 return clang_getNullCursor();
4398}
4399
4400CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4401 if (clang_isDeclaration(cursor.kind)) {
4402 if (Decl *D = getCursorDecl(cursor)) {
4403 DeclContext *DC = D->getLexicalDeclContext();
4404 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4405 }
4406 }
4407
4408 // FIXME: Note that we can't easily compute the lexical context of a
4409 // statement or expression, so we return nothing.
4410 return clang_getNullCursor();
4411}
4412
Douglas Gregor9f592342010-10-01 20:25:15 +00004413static void CollectOverriddenMethods(DeclContext *Ctx,
4414 ObjCMethodDecl *Method,
4415 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4416 if (!Ctx)
4417 return;
4418
4419 // If we have a class or category implementation, jump straight to the
4420 // interface.
4421 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4422 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4423
4424 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4425 if (!Container)
4426 return;
4427
4428 // Check whether we have a matching method at this level.
4429 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4430 Method->isInstanceMethod()))
4431 if (Method != Overridden) {
4432 // We found an override at this level; there is no need to look
4433 // into other protocols or categories.
4434 Methods.push_back(Overridden);
4435 return;
4436 }
4437
4438 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4439 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4440 PEnd = Protocol->protocol_end();
4441 P != PEnd; ++P)
4442 CollectOverriddenMethods(*P, Method, Methods);
4443 }
4444
4445 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4446 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4447 PEnd = Category->protocol_end();
4448 P != PEnd; ++P)
4449 CollectOverriddenMethods(*P, Method, Methods);
4450 }
4451
4452 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4453 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4454 PEnd = Interface->protocol_end();
4455 P != PEnd; ++P)
4456 CollectOverriddenMethods(*P, Method, Methods);
4457
4458 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4459 Category; Category = Category->getNextClassCategory())
4460 CollectOverriddenMethods(Category, Method, Methods);
4461
4462 // We only look into the superclass if we haven't found anything yet.
4463 if (Methods.empty())
4464 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4465 return CollectOverriddenMethods(Super, Method, Methods);
4466 }
4467}
4468
4469void clang_getOverriddenCursors(CXCursor cursor,
4470 CXCursor **overridden,
4471 unsigned *num_overridden) {
4472 if (overridden)
4473 *overridden = 0;
4474 if (num_overridden)
4475 *num_overridden = 0;
4476 if (!overridden || !num_overridden)
4477 return;
4478
4479 if (!clang_isDeclaration(cursor.kind))
4480 return;
4481
4482 Decl *D = getCursorDecl(cursor);
4483 if (!D)
4484 return;
4485
4486 // Handle C++ member functions.
4487 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4488 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4489 *num_overridden = CXXMethod->size_overridden_methods();
4490 if (!*num_overridden)
4491 return;
4492
4493 *overridden = new CXCursor [*num_overridden];
4494 unsigned I = 0;
4495 for (CXXMethodDecl::method_iterator
4496 M = CXXMethod->begin_overridden_methods(),
4497 MEnd = CXXMethod->end_overridden_methods();
4498 M != MEnd; (void)++M, ++I)
4499 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4500 return;
4501 }
4502
4503 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4504 if (!Method)
4505 return;
4506
4507 // Handle Objective-C methods.
4508 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4509 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4510
4511 if (Methods.empty())
4512 return;
4513
4514 *num_overridden = Methods.size();
4515 *overridden = new CXCursor [Methods.size()];
4516 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4517 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4518}
4519
4520void clang_disposeOverriddenCursors(CXCursor *overridden) {
4521 delete [] overridden;
4522}
4523
Douglas Gregorecdcb882010-10-20 22:00:55 +00004524CXFile clang_getIncludedFile(CXCursor cursor) {
4525 if (cursor.kind != CXCursor_InclusionDirective)
4526 return 0;
4527
4528 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4529 return (void *)ID->getFile();
4530}
4531
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004532} // end: extern "C"
4533
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004534
4535//===----------------------------------------------------------------------===//
4536// C++ AST instrospection.
4537//===----------------------------------------------------------------------===//
4538
4539extern "C" {
4540unsigned clang_CXXMethod_isStatic(CXCursor C) {
4541 if (!clang_isDeclaration(C.kind))
4542 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004543
4544 CXXMethodDecl *Method = 0;
4545 Decl *D = cxcursor::getCursorDecl(C);
4546 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4547 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4548 else
4549 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4550 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004551}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004552
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004553} // end: extern "C"
4554
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004555//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004556// Attribute introspection.
4557//===----------------------------------------------------------------------===//
4558
4559extern "C" {
4560CXType clang_getIBOutletCollectionType(CXCursor C) {
4561 if (C.kind != CXCursor_IBOutletCollectionAttr)
4562 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4563
4564 IBOutletCollectionAttr *A =
4565 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4566
4567 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4568}
4569} // end: extern "C"
4570
4571//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004572// CXString Operations.
4573//===----------------------------------------------------------------------===//
4574
4575extern "C" {
4576const char *clang_getCString(CXString string) {
4577 return string.Spelling;
4578}
4579
4580void clang_disposeString(CXString string) {
4581 if (string.MustFreeString && string.Spelling)
4582 free((void*)string.Spelling);
4583}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004584
Ted Kremenekfb480492010-01-13 21:46:36 +00004585} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004586
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004587namespace clang { namespace cxstring {
4588CXString createCXString(const char *String, bool DupString){
4589 CXString Str;
4590 if (DupString) {
4591 Str.Spelling = strdup(String);
4592 Str.MustFreeString = 1;
4593 } else {
4594 Str.Spelling = String;
4595 Str.MustFreeString = 0;
4596 }
4597 return Str;
4598}
4599
4600CXString createCXString(llvm::StringRef String, bool DupString) {
4601 CXString Result;
4602 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4603 char *Spelling = (char *)malloc(String.size() + 1);
4604 memmove(Spelling, String.data(), String.size());
4605 Spelling[String.size()] = 0;
4606 Result.Spelling = Spelling;
4607 Result.MustFreeString = 1;
4608 } else {
4609 Result.Spelling = String.data();
4610 Result.MustFreeString = 0;
4611 }
4612 return Result;
4613}
4614}}
4615
Ted Kremenek04bb7162010-01-22 22:44:15 +00004616//===----------------------------------------------------------------------===//
4617// Misc. utility functions.
4618//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004619
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004620/// Default to using an 8 MB stack size on "safety" threads.
4621static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004622
4623namespace clang {
4624
4625bool RunSafely(llvm::CrashRecoveryContext &CRC,
4626 void (*Fn)(void*), void *UserData) {
4627 if (unsigned Size = GetSafetyThreadStackSize())
4628 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4629 return CRC.RunSafely(Fn, UserData);
4630}
4631
4632unsigned GetSafetyThreadStackSize() {
4633 return SafetyStackThreadSize;
4634}
4635
4636void SetSafetyThreadStackSize(unsigned Value) {
4637 SafetyStackThreadSize = Value;
4638}
4639
4640}
4641
Ted Kremenek04bb7162010-01-22 22:44:15 +00004642extern "C" {
4643
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004644CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004645 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004646}
4647
4648} // end: extern "C"