blob: 6b8bec767ebafcf687df3a47eed756e27a9ebd35 [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
Steve Naroff50398192009-08-28 15:28:48 +000046using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000047using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000048using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000049
Douglas Gregor33e9abd2010-01-22 19:49:59 +000050/// \brief The result of comparing two source ranges.
51enum RangeComparisonResult {
52 /// \brief Either the ranges overlap or one of the ranges is invalid.
53 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000054
Douglas Gregor33e9abd2010-01-22 19:49:59 +000055 /// \brief The first range ends before the second range starts.
56 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range starts after the second range ends.
59 RangeAfter
60};
61
Ted Kremenekf0e23e82010-02-17 00:41:40 +000062/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000063/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000064static RangeComparisonResult RangeCompare(SourceManager &SM,
65 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066 SourceRange R2) {
67 assert(R1.isValid() && "First range is invalid?");
68 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000069 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000070 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000071 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeAfter;
75 return RangeOverlap;
76}
77
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000078/// \brief Determine if a source location falls within, before, or after a
79/// a given source range.
80static RangeComparisonResult LocationCompare(SourceManager &SM,
81 SourceLocation L, SourceRange R) {
82 assert(R.isValid() && "First range is invalid?");
83 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000085 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000086 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
87 return RangeBefore;
88 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
89 return RangeAfter;
90 return RangeOverlap;
91}
92
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000093/// \brief Translate a Clang source range into a CIndex source range.
94///
95/// Clang internally represents ranges where the end location points to the
96/// start of the token at the end. However, for external clients it is more
97/// useful to have a CXSourceRange be a proper half-open interval. This routine
98/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000099CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000100 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000101 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000102 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000103 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000104 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000105 if (EndLoc.isValid() && EndLoc.isMacroID())
106 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000107 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000108 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000109 EndLoc = EndLoc.getFileLocWithOffset(Length);
110 }
111
112 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
113 R.getBegin().getRawEncoding(),
114 EndLoc.getRawEncoding() };
115 return Result;
116}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000117
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000118//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000119// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000120//===----------------------------------------------------------------------===//
121
Steve Naroff89922f82009-08-31 00:59:03 +0000122namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000123
124class VisitorJob {
125public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000126 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000127 TypeLocVisitKind, OverloadExprPartsKind,
128 DeclRefExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000129protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000130 void *dataA;
131 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000132 CXCursor parent;
133 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000134 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
135 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000136public:
137 Kind getKind() const { return K; }
138 const CXCursor &getParent() const { return parent; }
139 static bool classof(VisitorJob *VJ) { return true; }
140};
141
142typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
143
Douglas Gregorb1373d02010-01-20 20:59:29 +0000144// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000145class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000146 public TypeLocVisitor<CursorVisitor, bool>,
147 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000148{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000149 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000150 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000151
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000153 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000154
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000155 /// \brief The declaration that serves at the parent of any statement or
156 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000157 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000158
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000159 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000160 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000161
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000162 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000165 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
166 // to the visitor. Declarations with a PCH level greater than this value will
167 // be suppressed.
168 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000169
170 /// \brief When valid, a source range to which the cursor should restrict
171 /// its search.
172 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000174 // FIXME: Eventually remove. This part of a hack to support proper
175 // iteration over all Decls contained lexically within an ObjC container.
176 DeclContext::decl_iterator *DI_current;
177 DeclContext::decl_iterator DE_current;
178
Douglas Gregorb1373d02010-01-20 20:59:29 +0000179 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000180 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000181 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
183 /// \brief Determine whether this particular source range comes before, comes
184 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000185 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000186 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000187 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
188
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000189 class SetParentRAII {
190 CXCursor &Parent;
191 Decl *&StmtParent;
192 CXCursor OldParent;
193
194 public:
195 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
196 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
197 {
198 Parent = NewParent;
199 if (clang_isDeclaration(Parent.kind))
200 StmtParent = getCursorDecl(Parent);
201 }
202
203 ~SetParentRAII() {
204 Parent = OldParent;
205 if (clang_isDeclaration(Parent.kind))
206 StmtParent = getCursorDecl(Parent);
207 }
208 };
209
Steve Naroff89922f82009-08-31 00:59:03 +0000210public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
212 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000215 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
216 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000217 {
218 Parent.kind = CXCursor_NoDeclFound;
219 Parent.data[0] = 0;
220 Parent.data[1] = 0;
221 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000222 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000223 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000224
Ted Kremenekab979612010-11-11 08:05:23 +0000225 ASTUnit *getASTUnit() const { return TU; }
226
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000228
229 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
230 getPreprocessedEntities();
231
Douglas Gregorb1373d02010-01-20 20:59:29 +0000232 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000233
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000234 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000235 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000236 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000237 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000238 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000239 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000240 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
241 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000242 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000243 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000244 bool VisitClassTemplatePartialSpecializationDecl(
245 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000246 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000247 bool VisitEnumConstantDecl(EnumConstantDecl *D);
248 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
249 bool VisitFunctionDecl(FunctionDecl *ND);
250 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000251 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000252 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000253 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000254 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000255 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000256 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
257 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
258 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
259 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000260 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000261 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
262 bool VisitObjCImplDecl(ObjCImplDecl *D);
263 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
264 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000265 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
266 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
267 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000268 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000269 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000270 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000271 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000272 bool VisitUsingDecl(UsingDecl *D);
273 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
274 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000275
Douglas Gregor01829d32010-08-31 14:41:23 +0000276 // Name visitor
277 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000278 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000279
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000280 // Template visitors
281 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000282 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000283 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
284
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000285 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000286 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000287 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000288 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000289 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
290 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000291 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000292 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000293 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000294 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
295 bool VisitPointerTypeLoc(PointerTypeLoc TL);
296 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
297 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
298 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
299 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000300 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000301 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000302 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000303 // FIXME: Implement visitors here when the unimplemented TypeLocs get
304 // implemented
305 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
306 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000307
Douglas Gregora59e3902010-01-21 23:27:09 +0000308 // Statement visitors
309 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000310
Douglas Gregor336fd812010-01-23 00:40:08 +0000311 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000312 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000313 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000314 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000315 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
316 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000317 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000318 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000319 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000320 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000321 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000322 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000323 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000324 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000325 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000326
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000327 // Data-recursive visitor functions.
328 bool IsInRegionOfInterest(CXCursor C);
329 bool RunVisitorWorkList(VisitorWorkList &WL);
330 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
331 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000332};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000333
Ted Kremenekab188932010-01-05 19:32:54 +0000334} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000335
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000336static SourceRange getRawCursorExtent(CXCursor C);
337
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000338RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000339 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
340}
341
Douglas Gregorb1373d02010-01-20 20:59:29 +0000342/// \brief Visit the given cursor and, if requested by the visitor,
343/// its children.
344///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000345/// \param Cursor the cursor to visit.
346///
347/// \param CheckRegionOfInterest if true, then the caller already checked that
348/// this cursor is within the region of interest.
349///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000350/// \returns true if the visitation should be aborted, false if it
351/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000352bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000353 if (clang_isInvalid(Cursor.kind))
354 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000355
Douglas Gregorb1373d02010-01-20 20:59:29 +0000356 if (clang_isDeclaration(Cursor.kind)) {
357 Decl *D = getCursorDecl(Cursor);
358 assert(D && "Invalid declaration cursor");
359 if (D->getPCHLevel() > MaxPCHLevel)
360 return false;
361
362 if (D->isImplicit())
363 return false;
364 }
365
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366 // If we have a range of interest, and this cursor doesn't intersect with it,
367 // we're done.
368 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000369 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000370 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371 return false;
372 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000373
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 switch (Visitor(Cursor, Parent, ClientData)) {
375 case CXChildVisit_Break:
376 return true;
377
378 case CXChildVisit_Continue:
379 return false;
380
381 case CXChildVisit_Recurse:
382 return VisitChildren(Cursor);
383 }
384
Douglas Gregorfd643772010-01-25 16:45:46 +0000385 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000386}
387
Douglas Gregor788f5a12010-03-20 00:41:21 +0000388std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
389CursorVisitor::getPreprocessedEntities() {
390 PreprocessingRecord &PPRec
391 = *TU->getPreprocessor().getPreprocessingRecord();
392
393 bool OnlyLocalDecls
394 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
395
396 // There is no region of interest; we have to walk everything.
397 if (RegionOfInterest.isInvalid())
398 return std::make_pair(PPRec.begin(OnlyLocalDecls),
399 PPRec.end(OnlyLocalDecls));
400
401 // Find the file in which the region of interest lands.
402 SourceManager &SM = TU->getSourceManager();
403 std::pair<FileID, unsigned> Begin
404 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
405 std::pair<FileID, unsigned> End
406 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
407
408 // The region of interest spans files; we have to walk everything.
409 if (Begin.first != End.first)
410 return std::make_pair(PPRec.begin(OnlyLocalDecls),
411 PPRec.end(OnlyLocalDecls));
412
413 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
414 = TU->getPreprocessedEntitiesByFile();
415 if (ByFileMap.empty()) {
416 // Build the mapping from files to sets of preprocessed entities.
417 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
418 EEnd = PPRec.end(OnlyLocalDecls);
419 E != EEnd; ++E) {
420 std::pair<FileID, unsigned> P
421 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
422 ByFileMap[P.first].push_back(*E);
423 }
424 }
425
426 return std::make_pair(ByFileMap[Begin.first].begin(),
427 ByFileMap[Begin.first].end());
428}
429
Douglas Gregorb1373d02010-01-20 20:59:29 +0000430/// \brief Visit the children of the given cursor.
431///
432/// \returns true if the visitation should be aborted, false if it
433/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000434bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000435 if (clang_isReference(Cursor.kind)) {
436 // By definition, references have no children.
437 return false;
438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439
440 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000441 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000442 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000443
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444 if (clang_isDeclaration(Cursor.kind)) {
445 Decl *D = getCursorDecl(Cursor);
446 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000447 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000448 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000449
Douglas Gregora59e3902010-01-21 23:27:09 +0000450 if (clang_isStatement(Cursor.kind))
451 return Visit(getCursorStmt(Cursor));
452 if (clang_isExpression(Cursor.kind))
453 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000454
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000456 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000457 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
458 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000459 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
460 TLEnd = CXXUnit->top_level_end();
461 TL != TLEnd; ++TL) {
462 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000463 return true;
464 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000465 } else if (VisitDeclContext(
466 CXXUnit->getASTContext().getTranslationUnitDecl()))
467 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000468
Douglas Gregor0396f462010-03-19 05:22:59 +0000469 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000470 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000471 // FIXME: Once we have the ability to deserialize a preprocessing record,
472 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000473 PreprocessingRecord::iterator E, EEnd;
474 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000475 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
476 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
477 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000478
Douglas Gregor0396f462010-03-19 05:22:59 +0000479 continue;
480 }
481
482 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
483 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
484 return true;
485
486 continue;
487 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000488
489 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
490 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
491 return true;
492
493 continue;
494 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 }
496 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000497 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000499
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501 return false;
502}
503
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000504bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000505 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
506 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000507
Ted Kremenek664cffd2010-07-22 11:30:19 +0000508 if (Stmt *Body = B->getBody())
509 return Visit(MakeCXCursor(Body, StmtParent, TU));
510
511 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000512}
513
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000514llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
515 if (RegionOfInterest.isValid()) {
516 SourceRange Range = getRawCursorExtent(Cursor);
517 if (Range.isInvalid())
518 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000519
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000520 switch (CompareRegionOfInterest(Range)) {
521 case RangeBefore:
522 // This declaration comes before the region of interest; skip it.
523 return llvm::Optional<bool>();
524
525 case RangeAfter:
526 // This declaration comes after the region of interest; we're done.
527 return false;
528
529 case RangeOverlap:
530 // This declaration overlaps the region of interest; visit it.
531 break;
532 }
533 }
534 return true;
535}
536
537bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
538 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
539
540 // FIXME: Eventually remove. This part of a hack to support proper
541 // iteration over all Decls contained lexically within an ObjC container.
542 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
543 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
544
545 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000546 Decl *D = *I;
547 if (D->getLexicalDeclContext() != DC)
548 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000549 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000550 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
551 if (!V.hasValue())
552 continue;
553 if (!V.getValue())
554 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000555 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 return true;
557 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000559}
560
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000561bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
562 llvm_unreachable("Translation units are visited directly by Visit()");
563 return false;
564}
565
566bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
567 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
568 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000569
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000570 return false;
571}
572
573bool CursorVisitor::VisitTagDecl(TagDecl *D) {
574 return VisitDeclContext(D);
575}
576
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000577bool CursorVisitor::VisitClassTemplateSpecializationDecl(
578 ClassTemplateSpecializationDecl *D) {
579 bool ShouldVisitBody = false;
580 switch (D->getSpecializationKind()) {
581 case TSK_Undeclared:
582 case TSK_ImplicitInstantiation:
583 // Nothing to visit
584 return false;
585
586 case TSK_ExplicitInstantiationDeclaration:
587 case TSK_ExplicitInstantiationDefinition:
588 break;
589
590 case TSK_ExplicitSpecialization:
591 ShouldVisitBody = true;
592 break;
593 }
594
595 // Visit the template arguments used in the specialization.
596 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
597 TypeLoc TL = SpecType->getTypeLoc();
598 if (TemplateSpecializationTypeLoc *TSTLoc
599 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
600 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
601 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
602 return true;
603 }
604 }
605
606 if (ShouldVisitBody && VisitCXXRecordDecl(D))
607 return true;
608
609 return false;
610}
611
Douglas Gregor74dbe642010-08-31 19:31:58 +0000612bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
613 ClassTemplatePartialSpecializationDecl *D) {
614 // FIXME: Visit the "outer" template parameter lists on the TagDecl
615 // before visiting these template parameters.
616 if (VisitTemplateParameters(D->getTemplateParameters()))
617 return true;
618
619 // Visit the partial specialization arguments.
620 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
621 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
622 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
623 return true;
624
625 return VisitCXXRecordDecl(D);
626}
627
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000628bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000629 // Visit the default argument.
630 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
631 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
632 if (Visit(DefArg->getTypeLoc()))
633 return true;
634
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000635 return false;
636}
637
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000638bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
639 if (Expr *Init = D->getInitExpr())
640 return Visit(MakeCXCursor(Init, StmtParent, TU));
641 return false;
642}
643
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000644bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
645 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
646 if (Visit(TSInfo->getTypeLoc()))
647 return true;
648
649 return false;
650}
651
Douglas Gregora67e03f2010-09-09 21:42:20 +0000652/// \brief Compare two base or member initializers based on their source order.
653static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
654 CXXBaseOrMemberInitializer const * const *X
655 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
656 CXXBaseOrMemberInitializer const * const *Y
657 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
658
659 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
660 return -1;
661 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
662 return 1;
663 else
664 return 0;
665}
666
Douglas Gregorb1373d02010-01-20 20:59:29 +0000667bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000668 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
669 // Visit the function declaration's syntactic components in the order
670 // written. This requires a bit of work.
671 TypeLoc TL = TSInfo->getTypeLoc();
672 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
673
674 // If we have a function declared directly (without the use of a typedef),
675 // visit just the return type. Otherwise, just visit the function's type
676 // now.
677 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
678 (!FTL && Visit(TL)))
679 return true;
680
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000681 // Visit the nested-name-specifier, if present.
682 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
683 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
684 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000685
686 // Visit the declaration name.
687 if (VisitDeclarationNameInfo(ND->getNameInfo()))
688 return true;
689
690 // FIXME: Visit explicitly-specified template arguments!
691
692 // Visit the function parameters, if we have a function type.
693 if (FTL && VisitFunctionTypeLoc(*FTL, true))
694 return true;
695
696 // FIXME: Attributes?
697 }
698
Douglas Gregora67e03f2010-09-09 21:42:20 +0000699 if (ND->isThisDeclarationADefinition()) {
700 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
701 // Find the initializers that were written in the source.
702 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
703 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
704 IEnd = Constructor->init_end();
705 I != IEnd; ++I) {
706 if (!(*I)->isWritten())
707 continue;
708
709 WrittenInits.push_back(*I);
710 }
711
712 // Sort the initializers in source order
713 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
714 &CompareCXXBaseOrMemberInitializers);
715
716 // Visit the initializers in source order
717 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
718 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
719 if (Init->isMemberInitializer()) {
720 if (Visit(MakeCursorMemberRef(Init->getMember(),
721 Init->getMemberLocation(), TU)))
722 return true;
723 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
724 if (Visit(BaseInfo->getTypeLoc()))
725 return true;
726 }
727
728 // Visit the initializer value.
729 if (Expr *Initializer = Init->getInit())
730 if (Visit(MakeCXCursor(Initializer, ND, TU)))
731 return true;
732 }
733 }
734
735 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
736 return true;
737 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000738
Douglas Gregorb1373d02010-01-20 20:59:29 +0000739 return false;
740}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000741
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000742bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
743 if (VisitDeclaratorDecl(D))
744 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000746 if (Expr *BitWidth = D->getBitWidth())
747 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000748
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000749 return false;
750}
751
752bool CursorVisitor::VisitVarDecl(VarDecl *D) {
753 if (VisitDeclaratorDecl(D))
754 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000755
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000756 if (Expr *Init = D->getInit())
757 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000758
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000759 return false;
760}
761
Douglas Gregor84b51d72010-09-01 20:16:53 +0000762bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
763 if (VisitDeclaratorDecl(D))
764 return true;
765
766 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
767 if (Expr *DefArg = D->getDefaultArgument())
768 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
769
770 return false;
771}
772
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000773bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
774 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
775 // before visiting these template parameters.
776 if (VisitTemplateParameters(D->getTemplateParameters()))
777 return true;
778
779 return VisitFunctionDecl(D->getTemplatedDecl());
780}
781
Douglas Gregor39d6f072010-08-31 19:02:00 +0000782bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
783 // FIXME: Visit the "outer" template parameter lists on the TagDecl
784 // before visiting these template parameters.
785 if (VisitTemplateParameters(D->getTemplateParameters()))
786 return true;
787
788 return VisitCXXRecordDecl(D->getTemplatedDecl());
789}
790
Douglas Gregor84b51d72010-09-01 20:16:53 +0000791bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
792 if (VisitTemplateParameters(D->getTemplateParameters()))
793 return true;
794
795 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
796 VisitTemplateArgumentLoc(D->getDefaultArgument()))
797 return true;
798
799 return false;
800}
801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000803 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
804 if (Visit(TSInfo->getTypeLoc()))
805 return true;
806
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000807 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000808 PEnd = ND->param_end();
809 P != PEnd; ++P) {
810 if (Visit(MakeCXCursor(*P, TU)))
811 return true;
812 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000813
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000814 if (ND->isThisDeclarationADefinition() &&
815 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
816 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000817
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000818 return false;
819}
820
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000821namespace {
822 struct ContainerDeclsSort {
823 SourceManager &SM;
824 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
825 bool operator()(Decl *A, Decl *B) {
826 SourceLocation L_A = A->getLocStart();
827 SourceLocation L_B = B->getLocStart();
828 assert(L_A.isValid() && L_B.isValid());
829 return SM.isBeforeInTranslationUnit(L_A, L_B);
830 }
831 };
832}
833
Douglas Gregora59e3902010-01-21 23:27:09 +0000834bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000835 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
836 // an @implementation can lexically contain Decls that are not properly
837 // nested in the AST. When we identify such cases, we need to retrofit
838 // this nesting here.
839 if (!DI_current)
840 return VisitDeclContext(D);
841
842 // Scan the Decls that immediately come after the container
843 // in the current DeclContext. If any fall within the
844 // container's lexical region, stash them into a vector
845 // for later processing.
846 llvm::SmallVector<Decl *, 24> DeclsInContainer;
847 SourceLocation EndLoc = D->getSourceRange().getEnd();
848 SourceManager &SM = TU->getSourceManager();
849 if (EndLoc.isValid()) {
850 DeclContext::decl_iterator next = *DI_current;
851 while (++next != DE_current) {
852 Decl *D_next = *next;
853 if (!D_next)
854 break;
855 SourceLocation L = D_next->getLocStart();
856 if (!L.isValid())
857 break;
858 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
859 *DI_current = next;
860 DeclsInContainer.push_back(D_next);
861 continue;
862 }
863 break;
864 }
865 }
866
867 // The common case.
868 if (DeclsInContainer.empty())
869 return VisitDeclContext(D);
870
871 // Get all the Decls in the DeclContext, and sort them with the
872 // additional ones we've collected. Then visit them.
873 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
874 I!=E; ++I) {
875 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000876 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
877 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000878 continue;
879 DeclsInContainer.push_back(subDecl);
880 }
881
882 // Now sort the Decls so that they appear in lexical order.
883 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
884 ContainerDeclsSort(SM));
885
886 // Now visit the decls.
887 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
888 E = DeclsInContainer.end(); I != E; ++I) {
889 CXCursor Cursor = MakeCXCursor(*I, TU);
890 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
891 if (!V.hasValue())
892 continue;
893 if (!V.getValue())
894 return false;
895 if (Visit(Cursor, true))
896 return true;
897 }
898 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000899}
900
Douglas Gregorb1373d02010-01-20 20:59:29 +0000901bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000902 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
903 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000904 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000905
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000906 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
907 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
908 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000909 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000910 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000911
Douglas Gregora59e3902010-01-21 23:27:09 +0000912 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000913}
914
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000915bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
916 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
917 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
918 E = PID->protocol_end(); I != E; ++I, ++PL)
919 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
920 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000921
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000922 return VisitObjCContainerDecl(PID);
923}
924
Ted Kremenek23173d72010-05-18 21:09:07 +0000925bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000926 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000927 return true;
928
Ted Kremenek23173d72010-05-18 21:09:07 +0000929 // FIXME: This implements a workaround with @property declarations also being
930 // installed in the DeclContext for the @interface. Eventually this code
931 // should be removed.
932 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
933 if (!CDecl || !CDecl->IsClassExtension())
934 return false;
935
936 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
937 if (!ID)
938 return false;
939
940 IdentifierInfo *PropertyId = PD->getIdentifier();
941 ObjCPropertyDecl *prevDecl =
942 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
943
944 if (!prevDecl)
945 return false;
946
947 // Visit synthesized methods since they will be skipped when visiting
948 // the @interface.
949 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000950 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000951 if (Visit(MakeCXCursor(MD, TU)))
952 return true;
953
954 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000955 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000956 if (Visit(MakeCXCursor(MD, TU)))
957 return true;
958
959 return false;
960}
961
Douglas Gregorb1373d02010-01-20 20:59:29 +0000962bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000963 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000964 if (D->getSuperClass() &&
965 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000966 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000967 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000968 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000969
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000970 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
971 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
972 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000973 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000974 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000975
Douglas Gregora59e3902010-01-21 23:27:09 +0000976 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000977}
978
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000979bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
980 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000981}
982
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000983bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000984 // 'ID' could be null when dealing with invalid code.
985 if (ObjCInterfaceDecl *ID = D->getClassInterface())
986 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
987 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000988
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000989 return VisitObjCImplDecl(D);
990}
991
992bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
993#if 0
994 // Issue callbacks for super class.
995 // FIXME: No source location information!
996 if (D->getSuperClass() &&
997 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000999 TU)))
1000 return true;
1001#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001002
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001003 return VisitObjCImplDecl(D);
1004}
1005
1006bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1007 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1008 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1009 E = D->protocol_end();
1010 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
1014 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001015}
1016
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001017bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1018 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1019 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1020 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001023}
1024
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001025bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1026 return VisitDeclContext(D);
1027}
1028
Douglas Gregor69319002010-08-31 23:48:11 +00001029bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001030 // Visit nested-name-specifier.
1031 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1032 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1033 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001034
1035 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1036 D->getTargetNameLoc(), TU));
1037}
1038
Douglas Gregor7e242562010-09-01 19:52:22 +00001039bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001040 // Visit nested-name-specifier.
1041 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1042 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1043 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001044
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001045 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1046 return true;
1047
Douglas Gregor7e242562010-09-01 19:52:22 +00001048 return VisitDeclarationNameInfo(D->getNameInfo());
1049}
1050
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001051bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001052 // Visit nested-name-specifier.
1053 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1054 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1055 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001056
1057 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1058 D->getIdentLocation(), TU));
1059}
1060
Douglas Gregor7e242562010-09-01 19:52:22 +00001061bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001062 // Visit nested-name-specifier.
1063 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1064 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1065 return true;
1066
Douglas Gregor7e242562010-09-01 19:52:22 +00001067 return VisitDeclarationNameInfo(D->getNameInfo());
1068}
1069
1070bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1071 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001072 // Visit nested-name-specifier.
1073 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1074 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1075 return true;
1076
Douglas Gregor7e242562010-09-01 19:52:22 +00001077 return false;
1078}
1079
Douglas Gregor01829d32010-08-31 14:41:23 +00001080bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1081 switch (Name.getName().getNameKind()) {
1082 case clang::DeclarationName::Identifier:
1083 case clang::DeclarationName::CXXLiteralOperatorName:
1084 case clang::DeclarationName::CXXOperatorName:
1085 case clang::DeclarationName::CXXUsingDirective:
1086 return false;
1087
1088 case clang::DeclarationName::CXXConstructorName:
1089 case clang::DeclarationName::CXXDestructorName:
1090 case clang::DeclarationName::CXXConversionFunctionName:
1091 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1092 return Visit(TSInfo->getTypeLoc());
1093 return false;
1094
1095 case clang::DeclarationName::ObjCZeroArgSelector:
1096 case clang::DeclarationName::ObjCOneArgSelector:
1097 case clang::DeclarationName::ObjCMultiArgSelector:
1098 // FIXME: Per-identifier location info?
1099 return false;
1100 }
1101
1102 return false;
1103}
1104
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001105bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1106 SourceRange Range) {
1107 // FIXME: This whole routine is a hack to work around the lack of proper
1108 // source information in nested-name-specifiers (PR5791). Since we do have
1109 // a beginning source location, we can visit the first component of the
1110 // nested-name-specifier, if it's a single-token component.
1111 if (!NNS)
1112 return false;
1113
1114 // Get the first component in the nested-name-specifier.
1115 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1116 NNS = Prefix;
1117
1118 switch (NNS->getKind()) {
1119 case NestedNameSpecifier::Namespace:
1120 // FIXME: The token at this source location might actually have been a
1121 // namespace alias, but we don't model that. Lame!
1122 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1123 TU));
1124
1125 case NestedNameSpecifier::TypeSpec: {
1126 // If the type has a form where we know that the beginning of the source
1127 // range matches up with a reference cursor. Visit the appropriate reference
1128 // cursor.
1129 Type *T = NNS->getAsType();
1130 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1131 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1132 if (const TagType *Tag = dyn_cast<TagType>(T))
1133 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1134 if (const TemplateSpecializationType *TST
1135 = dyn_cast<TemplateSpecializationType>(T))
1136 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1137 break;
1138 }
1139
1140 case NestedNameSpecifier::TypeSpecWithTemplate:
1141 case NestedNameSpecifier::Global:
1142 case NestedNameSpecifier::Identifier:
1143 break;
1144 }
1145
1146 return false;
1147}
1148
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001149bool CursorVisitor::VisitTemplateParameters(
1150 const TemplateParameterList *Params) {
1151 if (!Params)
1152 return false;
1153
1154 for (TemplateParameterList::const_iterator P = Params->begin(),
1155 PEnd = Params->end();
1156 P != PEnd; ++P) {
1157 if (Visit(MakeCXCursor(*P, TU)))
1158 return true;
1159 }
1160
1161 return false;
1162}
1163
Douglas Gregor0b36e612010-08-31 20:37:03 +00001164bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1165 switch (Name.getKind()) {
1166 case TemplateName::Template:
1167 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1168
1169 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001170 // Visit the overloaded template set.
1171 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1172 return true;
1173
Douglas Gregor0b36e612010-08-31 20:37:03 +00001174 return false;
1175
1176 case TemplateName::DependentTemplate:
1177 // FIXME: Visit nested-name-specifier.
1178 return false;
1179
1180 case TemplateName::QualifiedTemplate:
1181 // FIXME: Visit nested-name-specifier.
1182 return Visit(MakeCursorTemplateRef(
1183 Name.getAsQualifiedTemplateName()->getDecl(),
1184 Loc, TU));
1185 }
1186
1187 return false;
1188}
1189
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001190bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1191 switch (TAL.getArgument().getKind()) {
1192 case TemplateArgument::Null:
1193 case TemplateArgument::Integral:
1194 return false;
1195
1196 case TemplateArgument::Pack:
1197 // FIXME: Implement when variadic templates come along.
1198 return false;
1199
1200 case TemplateArgument::Type:
1201 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1202 return Visit(TSInfo->getTypeLoc());
1203 return false;
1204
1205 case TemplateArgument::Declaration:
1206 if (Expr *E = TAL.getSourceDeclExpression())
1207 return Visit(MakeCXCursor(E, StmtParent, TU));
1208 return false;
1209
1210 case TemplateArgument::Expression:
1211 if (Expr *E = TAL.getSourceExpression())
1212 return Visit(MakeCXCursor(E, StmtParent, TU));
1213 return false;
1214
1215 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001216 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1217 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001218 }
1219
1220 return false;
1221}
1222
Ted Kremeneka0536d82010-05-07 01:04:29 +00001223bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1224 return VisitDeclContext(D);
1225}
1226
Douglas Gregor01829d32010-08-31 14:41:23 +00001227bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1228 return Visit(TL.getUnqualifiedLoc());
1229}
1230
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001231bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1232 ASTContext &Context = TU->getASTContext();
1233
1234 // Some builtin types (such as Objective-C's "id", "sel", and
1235 // "Class") have associated declarations. Create cursors for those.
1236 QualType VisitType;
1237 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001238 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001239 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001240 case BuiltinType::Char_U:
1241 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001242 case BuiltinType::Char16:
1243 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001244 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001245 case BuiltinType::UInt:
1246 case BuiltinType::ULong:
1247 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001248 case BuiltinType::UInt128:
1249 case BuiltinType::Char_S:
1250 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001251 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001252 case BuiltinType::Short:
1253 case BuiltinType::Int:
1254 case BuiltinType::Long:
1255 case BuiltinType::LongLong:
1256 case BuiltinType::Int128:
1257 case BuiltinType::Float:
1258 case BuiltinType::Double:
1259 case BuiltinType::LongDouble:
1260 case BuiltinType::NullPtr:
1261 case BuiltinType::Overload:
1262 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001263 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001264
1265 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001266 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001267
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001268 case BuiltinType::ObjCId:
1269 VisitType = Context.getObjCIdType();
1270 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001271
1272 case BuiltinType::ObjCClass:
1273 VisitType = Context.getObjCClassType();
1274 break;
1275
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 case BuiltinType::ObjCSel:
1277 VisitType = Context.getObjCSelType();
1278 break;
1279 }
1280
1281 if (!VisitType.isNull()) {
1282 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001283 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001284 TU));
1285 }
1286
1287 return false;
1288}
1289
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001290bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1291 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1292}
1293
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001294bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1295 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1296}
1297
1298bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1299 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1300}
1301
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001302bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001303 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001304 // no context information with which we can match up the depth/index in the
1305 // type to the appropriate
1306 return false;
1307}
1308
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001309bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1310 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1311 return true;
1312
John McCallc12c5bb2010-05-15 11:32:37 +00001313 return false;
1314}
1315
1316bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1317 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1318 return true;
1319
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001320 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1321 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1322 TU)))
1323 return true;
1324 }
1325
1326 return false;
1327}
1328
1329bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001330 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331}
1332
1333bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1334 return Visit(TL.getPointeeLoc());
1335}
1336
1337bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1338 return Visit(TL.getPointeeLoc());
1339}
1340
1341bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1342 return Visit(TL.getPointeeLoc());
1343}
1344
1345bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001346 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001347}
1348
1349bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001350 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001351}
1352
Douglas Gregor01829d32010-08-31 14:41:23 +00001353bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1354 bool SkipResultType) {
1355 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001356 return true;
1357
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001358 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001359 if (Decl *D = TL.getArg(I))
1360 if (Visit(MakeCXCursor(D, TU)))
1361 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001362
1363 return false;
1364}
1365
1366bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1367 if (Visit(TL.getElementLoc()))
1368 return true;
1369
1370 if (Expr *Size = TL.getSizeExpr())
1371 return Visit(MakeCXCursor(Size, StmtParent, TU));
1372
1373 return false;
1374}
1375
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001376bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1377 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001378 // Visit the template name.
1379 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1380 TL.getTemplateNameLoc()))
1381 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001382
1383 // Visit the template arguments.
1384 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1385 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1386 return true;
1387
1388 return false;
1389}
1390
Douglas Gregor2332c112010-01-21 20:48:56 +00001391bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1392 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1393}
1394
1395bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1396 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1397 return Visit(TSInfo->getTypeLoc());
1398
1399 return false;
1400}
1401
Douglas Gregora59e3902010-01-21 23:27:09 +00001402bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001403 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001404}
1405
Ted Kremenek3064ef92010-08-27 21:34:58 +00001406bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1407 if (D->isDefinition()) {
1408 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1409 E = D->bases_end(); I != E; ++I) {
1410 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1411 return true;
1412 }
1413 }
1414
1415 return VisitTagDecl(D);
1416}
1417
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001418bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001419 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001420 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1421 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001422
1423 // Visit the components of the offsetof expression.
1424 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1425 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1426 const OffsetOfNode &Node = E->getComponent(I);
1427 switch (Node.getKind()) {
1428 case OffsetOfNode::Array:
1429 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1430 StmtParent, TU)))
1431 return true;
1432 break;
1433
1434 case OffsetOfNode::Field:
1435 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1436 TU)))
1437 return true;
1438 break;
1439
1440 case OffsetOfNode::Identifier:
1441 case OffsetOfNode::Base:
1442 continue;
1443 }
1444 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001445
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001446 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001447}
1448
Douglas Gregor336fd812010-01-23 00:40:08 +00001449bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1450 if (E->isArgumentType()) {
1451 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1452 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001453
Douglas Gregor336fd812010-01-23 00:40:08 +00001454 return false;
1455 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001456
Douglas Gregor336fd812010-01-23 00:40:08 +00001457 return VisitExpr(E);
1458}
1459
Douglas Gregor36897b02010-09-10 00:22:18 +00001460bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1461 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1462}
1463
Douglas Gregor648220e2010-08-10 15:02:34 +00001464bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1465 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1466 Visit(E->getArgTInfo2()->getTypeLoc());
1467}
1468
1469bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1470 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1471 return true;
1472
1473 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1474}
1475
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001476bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1477 // Visit the designators.
1478 typedef DesignatedInitExpr::Designator Designator;
1479 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1480 DEnd = E->designators_end();
1481 D != DEnd; ++D) {
1482 if (D->isFieldDesignator()) {
1483 if (FieldDecl *Field = D->getField())
1484 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1485 return true;
1486
1487 continue;
1488 }
1489
1490 if (D->isArrayDesignator()) {
1491 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1492 return true;
1493
1494 continue;
1495 }
1496
1497 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1498 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1499 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1500 return true;
1501 }
1502
1503 // Visit the initializer value itself.
1504 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1505}
1506
Douglas Gregor94802292010-09-02 21:20:16 +00001507bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1508 if (E->isTypeOperand()) {
1509 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1510 return Visit(TSInfo->getTypeLoc());
1511
1512 return false;
1513 }
1514
1515 return VisitExpr(E);
1516}
1517
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001518bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1519 if (E->isTypeOperand()) {
1520 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1521 return Visit(TSInfo->getTypeLoc());
1522
1523 return false;
1524 }
1525
1526 return VisitExpr(E);
1527}
1528
Douglas Gregorab6677e2010-09-08 00:15:04 +00001529bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1530 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1531 return Visit(TSInfo->getTypeLoc());
1532
1533 return false;
1534}
1535
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001536bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1537 // Visit base expression.
1538 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1539 return true;
1540
1541 // Visit the nested-name-specifier.
1542 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1543 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1544 return true;
1545
1546 // Visit the scope type that looks disturbingly like the nested-name-specifier
1547 // but isn't.
1548 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1549 if (Visit(TSInfo->getTypeLoc()))
1550 return true;
1551
1552 // Visit the name of the type being destroyed.
1553 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1554 if (Visit(TSInfo->getTypeLoc()))
1555 return true;
1556
1557 return false;
1558}
1559
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001560bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1561 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1562}
1563
Douglas Gregorbfebed22010-09-03 17:24:10 +00001564bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1565 DependentScopeDeclRefExpr *E) {
1566 // Visit the nested-name-specifier.
1567 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1568 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1569 return true;
1570
1571 // Visit the declaration name.
1572 if (VisitDeclarationNameInfo(E->getNameInfo()))
1573 return true;
1574
1575 // Visit the explicitly-specified template arguments.
1576 if (const ExplicitTemplateArgumentList *ArgList
1577 = E->getOptionalExplicitTemplateArgs()) {
1578 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1579 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1580 Arg != ArgEnd; ++Arg) {
1581 if (VisitTemplateArgumentLoc(*Arg))
1582 return true;
1583 }
1584 }
1585
1586 return false;
1587}
1588
Douglas Gregorab6677e2010-09-08 00:15:04 +00001589bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1590 CXXUnresolvedConstructExpr *E) {
1591 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1592 if (Visit(TSInfo->getTypeLoc()))
1593 return true;
1594
1595 return VisitExpr(E);
1596}
1597
Douglas Gregor25d63622010-09-03 17:35:34 +00001598bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1599 CXXDependentScopeMemberExpr *E) {
1600 // Visit the base expression, if there is one.
1601 if (!E->isImplicitAccess() &&
1602 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1603 return true;
1604
1605 // Visit the nested-name-specifier.
1606 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1607 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1608 return true;
1609
1610 // Visit the declaration name.
1611 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1612 return true;
1613
1614 // Visit the explicitly-specified template arguments.
1615 if (const ExplicitTemplateArgumentList *ArgList
1616 = E->getOptionalExplicitTemplateArgs()) {
1617 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1618 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1619 Arg != ArgEnd; ++Arg) {
1620 if (VisitTemplateArgumentLoc(*Arg))
1621 return true;
1622 }
1623 }
1624
1625 return false;
1626}
1627
Ted Kremenek09dfa372010-02-18 05:46:33 +00001628bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001629 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1630 i != e; ++i)
1631 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001632 return true;
1633
1634 return false;
1635}
1636
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001637//===----------------------------------------------------------------------===//
1638// Data-recursive visitor methods.
1639//===----------------------------------------------------------------------===//
1640
Ted Kremenek28a71942010-11-13 00:36:47 +00001641namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001642#define DEF_JOB(NAME, DATA, KIND)\
1643class NAME : public VisitorJob {\
1644public:\
1645 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1646 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1647 DATA *get() const { return static_cast<DATA*>(dataA); }\
1648};
1649
1650DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1651DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001652DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001653DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1654#undef DEF_JOB
1655
1656class DeclVisit : public VisitorJob {
1657public:
1658 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1659 VisitorJob(parent, VisitorJob::DeclVisitKind,
1660 d, isFirst ? (void*) 1 : (void*) 0) {}
1661 static bool classof(const VisitorJob *VJ) {
1662 return VJ->getKind () == DeclVisitKind;
1663 }
1664 Decl *get() { return static_cast<Decl*>(dataA);}
1665 bool isFirst() const { return dataB ? true : false; }
1666};
1667
1668class TypeLocVisit : public VisitorJob {
1669public:
1670 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1671 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1672 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1673
1674 static bool classof(const VisitorJob *VJ) {
1675 return VJ->getKind() == TypeLocVisitKind;
1676 }
1677
1678 TypeLoc get() {
1679 QualType T = QualType::getFromOpaquePtr(dataA);
1680 return TypeLoc(T, dataB);
1681 }
1682};
1683
Ted Kremenek28a71942010-11-13 00:36:47 +00001684class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1685 VisitorWorkList &WL;
1686 CXCursor Parent;
1687public:
1688 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1689 : WL(wl), Parent(parent) {}
1690
Ted Kremenek73d15c42010-11-13 01:09:29 +00001691 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001692 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001693 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001694 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1695 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001697 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001698 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001699 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001700 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1701 void VisitForStmt(ForStmt *FS);
1702 void VisitIfStmt(IfStmt *If);
1703 void VisitInitListExpr(InitListExpr *IE);
1704 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001705 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001706 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1707 void VisitOverloadExpr(OverloadExpr *E);
1708 void VisitStmt(Stmt *S);
1709 void VisitSwitchStmt(SwitchStmt *S);
1710 void VisitWhileStmt(WhileStmt *W);
1711 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1712
1713private:
1714 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001715 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001716 void AddTypeLoc(TypeSourceInfo *TI);
1717 void EnqueueChildren(Stmt *S);
1718};
1719} // end anonyous namespace
1720
1721void EnqueueVisitor::AddStmt(Stmt *S) {
1722 if (S)
1723 WL.push_back(StmtVisit(S, Parent));
1724}
Ted Kremenek035dc412010-11-13 00:36:50 +00001725void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001726 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001727 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001728}
1729void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1730 if (TI)
1731 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1732 }
1733void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001734 unsigned size = WL.size();
1735 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1736 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001737 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001738 }
1739 if (size == WL.size())
1740 return;
1741 // Now reverse the entries we just added. This will match the DFS
1742 // ordering performed by the worklist.
1743 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1744 std::reverse(I, E);
1745}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001746void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1747 AddDecl(B->getBlockDecl());
1748}
Ted Kremenek28a71942010-11-13 00:36:47 +00001749void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1750 EnqueueChildren(E);
1751 AddTypeLoc(E->getTypeSourceInfo());
1752}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001753void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1754 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1755 E = S->body_rend(); I != E; ++I) {
1756 AddStmt(*I);
1757 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001758}
1759void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1760 // Enqueue the initializer or constructor arguments.
1761 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1762 AddStmt(E->getConstructorArg(I-1));
1763 // Enqueue the array size, if any.
1764 AddStmt(E->getArraySize());
1765 // Enqueue the allocated type.
1766 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1767 // Enqueue the placement arguments.
1768 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1769 AddStmt(E->getPlacementArg(I-1));
1770}
Ted Kremenek28a71942010-11-13 00:36:47 +00001771void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001772 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1773 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001774 AddStmt(CE->getCallee());
1775 AddStmt(CE->getArg(0));
1776}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001777void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1778 EnqueueChildren(E);
1779 AddTypeLoc(E->getTypeSourceInfo());
1780}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001781void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1782 WL.push_back(DeclRefExprParts(DR, Parent));
1783}
Ted Kremenek035dc412010-11-13 00:36:50 +00001784void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1785 unsigned size = WL.size();
1786 bool isFirst = true;
1787 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1788 D != DEnd; ++D) {
1789 AddDecl(*D, isFirst);
1790 isFirst = false;
1791 }
1792 if (size == WL.size())
1793 return;
1794 // Now reverse the entries we just added. This will match the DFS
1795 // ordering performed by the worklist.
1796 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1797 std::reverse(I, E);
1798}
Ted Kremenek28a71942010-11-13 00:36:47 +00001799void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1800 EnqueueChildren(E);
1801 AddTypeLoc(E->getTypeInfoAsWritten());
1802}
1803void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1804 AddStmt(FS->getBody());
1805 AddStmt(FS->getInc());
1806 AddStmt(FS->getCond());
1807 AddDecl(FS->getConditionVariable());
1808 AddStmt(FS->getInit());
1809}
1810void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1811 AddStmt(If->getElse());
1812 AddStmt(If->getThen());
1813 AddStmt(If->getCond());
1814 AddDecl(If->getConditionVariable());
1815}
1816void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1817 // We care about the syntactic form of the initializer list, only.
1818 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1819 IE = Syntactic;
1820 EnqueueChildren(IE);
1821}
1822void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1823 WL.push_back(MemberExprParts(M, Parent));
1824 AddStmt(M->getBase());
1825}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001826void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1827 AddTypeLoc(E->getEncodedTypeSourceInfo());
1828}
Ted Kremenek28a71942010-11-13 00:36:47 +00001829void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1830 EnqueueChildren(M);
1831 AddTypeLoc(M->getClassReceiverTypeInfo());
1832}
1833void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001834 WL.push_back(OverloadExprParts(E, Parent));
1835}
Ted Kremenek28a71942010-11-13 00:36:47 +00001836void EnqueueVisitor::VisitStmt(Stmt *S) {
1837 EnqueueChildren(S);
1838}
1839void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1840 AddStmt(S->getBody());
1841 AddStmt(S->getCond());
1842 AddDecl(S->getConditionVariable());
1843}
1844void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1845 AddStmt(W->getBody());
1846 AddStmt(W->getCond());
1847 AddDecl(W->getConditionVariable());
1848}
1849void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1850 VisitOverloadExpr(U);
1851 if (!U->isImplicitAccess())
1852 AddStmt(U->getBase());
1853}
Ted Kremenek60458782010-11-12 21:34:16 +00001854
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001855void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001856 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001857}
1858
1859bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1860 if (RegionOfInterest.isValid()) {
1861 SourceRange Range = getRawCursorExtent(C);
1862 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1863 return false;
1864 }
1865 return true;
1866}
1867
1868bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1869 while (!WL.empty()) {
1870 // Dequeue the worklist item.
1871 VisitorJob LI = WL.back(); WL.pop_back();
1872
1873 // Set the Parent field, then back to its old value once we're done.
1874 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1875
1876 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001877 case VisitorJob::DeclVisitKind: {
1878 Decl *D = cast<DeclVisit>(LI).get();
1879 if (!D)
1880 continue;
1881
1882 // For now, perform default visitation for Decls.
Ted Kremenek035dc412010-11-13 00:36:50 +00001883 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(LI).isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001884 return true;
1885
1886 continue;
1887 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001888 case VisitorJob::TypeLocVisitKind: {
1889 // Perform default visitation for TypeLocs.
1890 if (Visit(cast<TypeLocVisit>(LI).get()))
1891 return true;
1892 continue;
1893 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001894 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001895 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001896 if (!S)
1897 continue;
1898
Ted Kremenekf1107452010-11-12 18:26:56 +00001899 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001900 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1901
1902 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001903 case Stmt::GotoStmtClass: {
1904 GotoStmt *GS = cast<GotoStmt>(S);
1905 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1906 GS->getLabelLoc(), TU))) {
1907 return true;
1908 }
1909 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001910 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001911 // Cases not yet handled by the data-recursion
1912 // algorithm.
1913 case Stmt::OffsetOfExprClass:
1914 case Stmt::SizeOfAlignOfExprClass:
1915 case Stmt::AddrLabelExprClass:
1916 case Stmt::TypesCompatibleExprClass:
1917 case Stmt::VAArgExprClass:
1918 case Stmt::DesignatedInitExprClass:
1919 case Stmt::CXXTypeidExprClass:
1920 case Stmt::CXXUuidofExprClass:
1921 case Stmt::CXXScalarValueInitExprClass:
1922 case Stmt::CXXPseudoDestructorExprClass:
1923 case Stmt::UnaryTypeTraitExprClass:
1924 case Stmt::DependentScopeDeclRefExprClass:
1925 case Stmt::CXXUnresolvedConstructExprClass:
1926 case Stmt::CXXDependentScopeMemberExprClass:
1927 if (Visit(Cursor))
1928 return true;
1929 continue;
1930 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001931 if (!IsInRegionOfInterest(Cursor))
1932 continue;
1933 switch (Visitor(Cursor, Parent, ClientData)) {
1934 case CXChildVisit_Break:
1935 return true;
1936 case CXChildVisit_Continue:
1937 break;
1938 case CXChildVisit_Recurse:
1939 EnqueueWorkList(WL, S);
1940 break;
1941 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001942 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001943 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001944 }
1945 case VisitorJob::MemberExprPartsKind: {
1946 // Handle the other pieces in the MemberExpr besides the base.
1947 MemberExpr *M = cast<MemberExprParts>(LI).get();
1948
1949 // Visit the nested-name-specifier
1950 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1951 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1952 return true;
1953
1954 // Visit the declaration name.
1955 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1956 return true;
1957
1958 // Visit the explicitly-specified template arguments, if any.
1959 if (M->hasExplicitTemplateArgs()) {
1960 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1961 *ArgEnd = Arg + M->getNumTemplateArgs();
1962 Arg != ArgEnd; ++Arg) {
1963 if (VisitTemplateArgumentLoc(*Arg))
1964 return true;
1965 }
1966 }
1967 continue;
1968 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001969 case VisitorJob::DeclRefExprPartsKind: {
1970 DeclRefExpr *DR = cast<DeclRefExprParts>(LI).get();
1971 // Visit nested-name-specifier, if present.
1972 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
1973 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
1974 return true;
1975 // Visit declaration name.
1976 if (VisitDeclarationNameInfo(DR->getNameInfo()))
1977 return true;
1978 // Visit explicitly-specified template arguments.
1979 if (DR->hasExplicitTemplateArgs()) {
1980 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
1981 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1982 *ArgEnd = Arg + Args.NumTemplateArgs;
1983 Arg != ArgEnd; ++Arg)
1984 if (VisitTemplateArgumentLoc(*Arg))
1985 return true;
1986 }
1987 continue;
1988 }
Ted Kremenek60458782010-11-12 21:34:16 +00001989 case VisitorJob::OverloadExprPartsKind: {
1990 OverloadExpr *O = cast<OverloadExprParts>(LI).get();
1991 // Visit the nested-name-specifier.
1992 if (NestedNameSpecifier *Qualifier = O->getQualifier())
1993 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
1994 return true;
1995 // Visit the declaration name.
1996 if (VisitDeclarationNameInfo(O->getNameInfo()))
1997 return true;
1998 // Visit the overloaded declaration reference.
1999 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2000 return true;
2001 // Visit the explicitly-specified template arguments.
2002 if (const ExplicitTemplateArgumentList *ArgList
2003 = O->getOptionalExplicitTemplateArgs()) {
2004 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2005 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2006 Arg != ArgEnd; ++Arg) {
2007 if (VisitTemplateArgumentLoc(*Arg))
2008 return true;
2009 }
2010 }
2011 continue;
2012 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002013 }
2014 }
2015 return false;
2016}
2017
2018bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2019 VisitorWorkList WL;
2020 EnqueueWorkList(WL, S);
2021 return RunVisitorWorkList(WL);
2022}
2023
2024//===----------------------------------------------------------------------===//
2025// Misc. API hooks.
2026//===----------------------------------------------------------------------===//
2027
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002028static llvm::sys::Mutex EnableMultithreadingMutex;
2029static bool EnabledMultithreading;
2030
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002031extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002032CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2033 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002034 // Disable pretty stack trace functionality, which will otherwise be a very
2035 // poor citizen of the world and set up all sorts of signal handlers.
2036 llvm::DisablePrettyStackTrace = true;
2037
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002038 // We use crash recovery to make some of our APIs more reliable, implicitly
2039 // enable it.
2040 llvm::CrashRecoveryContext::Enable();
2041
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002042 // Enable support for multithreading in LLVM.
2043 {
2044 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2045 if (!EnabledMultithreading) {
2046 llvm::llvm_start_multithreaded();
2047 EnabledMultithreading = true;
2048 }
2049 }
2050
Douglas Gregora030b7c2010-01-22 20:35:53 +00002051 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002052 if (excludeDeclarationsFromPCH)
2053 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002054 if (displayDiagnostics)
2055 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002056 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002057}
2058
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002059void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002060 if (CIdx)
2061 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002062}
2063
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002064CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002065 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002066 if (!CIdx)
2067 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002068
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002069 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002070 FileSystemOptions FileSystemOpts;
2071 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002072
Douglas Gregor28019772010-04-05 23:52:57 +00002073 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002074 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002075 CXXIdx->getOnlyLocalDecls(),
2076 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002077}
2078
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002079unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002080 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002081 CXTranslationUnit_CacheCompletionResults |
2082 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002083}
2084
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002085CXTranslationUnit
2086clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2087 const char *source_filename,
2088 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002089 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002090 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002091 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002092 return clang_parseTranslationUnit(CIdx, source_filename,
2093 command_line_args, num_command_line_args,
2094 unsaved_files, num_unsaved_files,
2095 CXTranslationUnit_DetailedPreprocessingRecord);
2096}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002097
2098struct ParseTranslationUnitInfo {
2099 CXIndex CIdx;
2100 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002101 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002102 int num_command_line_args;
2103 struct CXUnsavedFile *unsaved_files;
2104 unsigned num_unsaved_files;
2105 unsigned options;
2106 CXTranslationUnit result;
2107};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002108static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002109 ParseTranslationUnitInfo *PTUI =
2110 static_cast<ParseTranslationUnitInfo*>(UserData);
2111 CXIndex CIdx = PTUI->CIdx;
2112 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002113 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002114 int num_command_line_args = PTUI->num_command_line_args;
2115 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2116 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2117 unsigned options = PTUI->options;
2118 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002119
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002120 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002121 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002122
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002123 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2124
Douglas Gregor44c181a2010-07-23 00:33:23 +00002125 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002126 bool CompleteTranslationUnit
2127 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002128 bool CacheCodeCompetionResults
2129 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002130 bool CXXPrecompilePreamble
2131 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2132 bool CXXChainedPCH
2133 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002134
Douglas Gregor5352ac02010-01-28 00:27:43 +00002135 // Configure the diagnostics.
2136 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002137 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2138 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002139
Douglas Gregor4db64a42010-01-23 00:14:00 +00002140 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2141 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002142 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002144 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002145 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2146 Buffer));
2147 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
Douglas Gregorb10daed2010-10-11 16:52:23 +00002149 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002150
Ted Kremenek139ba862009-10-22 00:03:57 +00002151 // The 'source_filename' argument is optional. If the caller does not
2152 // specify it then it is assumed that the source file is specified
2153 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002154 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002155 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002156
2157 // Since the Clang C library is primarily used by batch tools dealing with
2158 // (often very broken) source code, where spell-checking can have a
2159 // significant negative impact on performance (particularly when
2160 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002161 // Only do this if we haven't found a spell-checking-related argument.
2162 bool FoundSpellCheckingArgument = false;
2163 for (int I = 0; I != num_command_line_args; ++I) {
2164 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2165 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2166 FoundSpellCheckingArgument = true;
2167 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002168 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002169 }
2170 if (!FoundSpellCheckingArgument)
2171 Args.push_back("-fno-spell-checking");
2172
2173 Args.insert(Args.end(), command_line_args,
2174 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002175
Douglas Gregor44c181a2010-07-23 00:33:23 +00002176 // Do we need the detailed preprocessing record?
2177 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002178 Args.push_back("-Xclang");
2179 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002180 }
2181
Douglas Gregorb10daed2010-10-11 16:52:23 +00002182 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002183 llvm::OwningPtr<ASTUnit> Unit(
2184 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2185 Diags,
2186 CXXIdx->getClangResourcesPath(),
2187 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002188 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002189 RemappedFiles.data(),
2190 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002191 PrecompilePreamble,
2192 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002193 CacheCodeCompetionResults,
2194 CXXPrecompilePreamble,
2195 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002196
Douglas Gregorb10daed2010-10-11 16:52:23 +00002197 if (NumErrors != Diags->getNumErrors()) {
2198 // Make sure to check that 'Unit' is non-NULL.
2199 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2200 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2201 DEnd = Unit->stored_diag_end();
2202 D != DEnd; ++D) {
2203 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2204 CXString Msg = clang_formatDiagnostic(&Diag,
2205 clang_defaultDiagnosticDisplayOptions());
2206 fprintf(stderr, "%s\n", clang_getCString(Msg));
2207 clang_disposeString(Msg);
2208 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002209#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002210 // On Windows, force a flush, since there may be multiple copies of
2211 // stderr and stdout in the file system, all with different buffers
2212 // but writing to the same device.
2213 fflush(stderr);
2214#endif
2215 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002216 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002217
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002219}
2220CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2221 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002222 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002223 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002224 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002225 unsigned num_unsaved_files,
2226 unsigned options) {
2227 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002228 num_command_line_args, unsaved_files,
2229 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002230 llvm::CrashRecoveryContext CRC;
2231
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002232 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002233 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2234 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2235 fprintf(stderr, " 'command_line_args' : [");
2236 for (int i = 0; i != num_command_line_args; ++i) {
2237 if (i)
2238 fprintf(stderr, ", ");
2239 fprintf(stderr, "'%s'", command_line_args[i]);
2240 }
2241 fprintf(stderr, "],\n");
2242 fprintf(stderr, " 'unsaved_files' : [");
2243 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2244 if (i)
2245 fprintf(stderr, ", ");
2246 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2247 unsaved_files[i].Length);
2248 }
2249 fprintf(stderr, "],\n");
2250 fprintf(stderr, " 'options' : %d,\n", options);
2251 fprintf(stderr, "}\n");
2252
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002253 return 0;
2254 }
2255
2256 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002257}
2258
Douglas Gregor19998442010-08-13 15:35:05 +00002259unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2260 return CXSaveTranslationUnit_None;
2261}
2262
2263int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2264 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002265 if (!TU)
2266 return 1;
2267
2268 return static_cast<ASTUnit *>(TU)->Save(FileName);
2269}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002270
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002271void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002272 if (CTUnit) {
2273 // If the translation unit has been marked as unsafe to free, just discard
2274 // it.
2275 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2276 return;
2277
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002278 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002279 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002280}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002281
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002282unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2283 return CXReparse_None;
2284}
2285
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002286struct ReparseTranslationUnitInfo {
2287 CXTranslationUnit TU;
2288 unsigned num_unsaved_files;
2289 struct CXUnsavedFile *unsaved_files;
2290 unsigned options;
2291 int result;
2292};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002293
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002294static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002295 ReparseTranslationUnitInfo *RTUI =
2296 static_cast<ReparseTranslationUnitInfo*>(UserData);
2297 CXTranslationUnit TU = RTUI->TU;
2298 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2299 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2300 unsigned options = RTUI->options;
2301 (void) options;
2302 RTUI->result = 1;
2303
Douglas Gregorabc563f2010-07-19 21:46:24 +00002304 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002305 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002306
2307 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2308 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002309
2310 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2311 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2312 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2313 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002314 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002315 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2316 Buffer));
2317 }
2318
Douglas Gregor593b0c12010-09-23 18:47:53 +00002319 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2320 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002321}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002322
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002323int clang_reparseTranslationUnit(CXTranslationUnit TU,
2324 unsigned num_unsaved_files,
2325 struct CXUnsavedFile *unsaved_files,
2326 unsigned options) {
2327 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2328 options, 0 };
2329 llvm::CrashRecoveryContext CRC;
2330
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002331 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002332 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002333 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2334 return 1;
2335 }
2336
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002337
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002338 return RTUI.result;
2339}
2340
Douglas Gregordf95a132010-08-09 20:45:32 +00002341
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002342CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002343 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002344 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002345
Steve Naroff77accc12009-09-03 18:19:54 +00002346 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002347 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002348}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002349
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002350CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002351 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002352 return Result;
2353}
2354
Ted Kremenekfb480492010-01-13 21:46:36 +00002355} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002356
Ted Kremenekfb480492010-01-13 21:46:36 +00002357//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002358// CXSourceLocation and CXSourceRange Operations.
2359//===----------------------------------------------------------------------===//
2360
Douglas Gregorb9790342010-01-22 21:44:22 +00002361extern "C" {
2362CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002363 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002364 return Result;
2365}
2366
2367unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002368 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2369 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2370 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002371}
2372
2373CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2374 CXFile file,
2375 unsigned line,
2376 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002377 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002378 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002379
Douglas Gregorb9790342010-01-22 21:44:22 +00002380 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2381 SourceLocation SLoc
2382 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002383 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002384 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002385 if (SLoc.isInvalid()) return clang_getNullLocation();
2386
2387 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2388}
2389
2390CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2391 CXFile file,
2392 unsigned offset) {
2393 if (!tu || !file)
2394 return clang_getNullLocation();
2395
2396 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2397 SourceLocation Start
2398 = CXXUnit->getSourceManager().getLocation(
2399 static_cast<const FileEntry *>(file),
2400 1, 1);
2401 if (Start.isInvalid()) return clang_getNullLocation();
2402
2403 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2404
2405 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002406
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002407 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002408}
2409
Douglas Gregor5352ac02010-01-28 00:27:43 +00002410CXSourceRange clang_getNullRange() {
2411 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2412 return Result;
2413}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002414
Douglas Gregor5352ac02010-01-28 00:27:43 +00002415CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2416 if (begin.ptr_data[0] != end.ptr_data[0] ||
2417 begin.ptr_data[1] != end.ptr_data[1])
2418 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419
2420 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002421 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002422 return Result;
2423}
2424
Douglas Gregor46766dc2010-01-26 19:19:08 +00002425void clang_getInstantiationLocation(CXSourceLocation location,
2426 CXFile *file,
2427 unsigned *line,
2428 unsigned *column,
2429 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002430 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2431
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002432 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002433 if (file)
2434 *file = 0;
2435 if (line)
2436 *line = 0;
2437 if (column)
2438 *column = 0;
2439 if (offset)
2440 *offset = 0;
2441 return;
2442 }
2443
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002444 const SourceManager &SM =
2445 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002446 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002447
2448 if (file)
2449 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2450 if (line)
2451 *line = SM.getInstantiationLineNumber(InstLoc);
2452 if (column)
2453 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002454 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002455 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002456}
2457
Douglas Gregora9b06d42010-11-09 06:24:54 +00002458void clang_getSpellingLocation(CXSourceLocation location,
2459 CXFile *file,
2460 unsigned *line,
2461 unsigned *column,
2462 unsigned *offset) {
2463 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2464
2465 if (!location.ptr_data[0] || Loc.isInvalid()) {
2466 if (file)
2467 *file = 0;
2468 if (line)
2469 *line = 0;
2470 if (column)
2471 *column = 0;
2472 if (offset)
2473 *offset = 0;
2474 return;
2475 }
2476
2477 const SourceManager &SM =
2478 *static_cast<const SourceManager*>(location.ptr_data[0]);
2479 SourceLocation SpellLoc = Loc;
2480 if (SpellLoc.isMacroID()) {
2481 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2482 if (SimpleSpellingLoc.isFileID() &&
2483 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2484 SpellLoc = SimpleSpellingLoc;
2485 else
2486 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2487 }
2488
2489 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2490 FileID FID = LocInfo.first;
2491 unsigned FileOffset = LocInfo.second;
2492
2493 if (file)
2494 *file = (void *)SM.getFileEntryForID(FID);
2495 if (line)
2496 *line = SM.getLineNumber(FID, FileOffset);
2497 if (column)
2498 *column = SM.getColumnNumber(FID, FileOffset);
2499 if (offset)
2500 *offset = FileOffset;
2501}
2502
Douglas Gregor1db19de2010-01-19 21:36:55 +00002503CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002504 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002505 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002506 return Result;
2507}
2508
2509CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002510 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002511 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002512 return Result;
2513}
2514
Douglas Gregorb9790342010-01-22 21:44:22 +00002515} // end: extern "C"
2516
Douglas Gregor1db19de2010-01-19 21:36:55 +00002517//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002518// CXFile Operations.
2519//===----------------------------------------------------------------------===//
2520
2521extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002522CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002523 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002524 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002525
Steve Naroff88145032009-10-27 14:35:18 +00002526 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002527 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002528}
2529
2530time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002531 if (!SFile)
2532 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002533
Steve Naroff88145032009-10-27 14:35:18 +00002534 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2535 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002536}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002537
Douglas Gregorb9790342010-01-22 21:44:22 +00002538CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2539 if (!tu)
2540 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002541
Douglas Gregorb9790342010-01-22 21:44:22 +00002542 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002543
Douglas Gregorb9790342010-01-22 21:44:22 +00002544 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002545 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2546 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002547 return const_cast<FileEntry *>(File);
2548}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002549
Ted Kremenekfb480492010-01-13 21:46:36 +00002550} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002551
Ted Kremenekfb480492010-01-13 21:46:36 +00002552//===----------------------------------------------------------------------===//
2553// CXCursor Operations.
2554//===----------------------------------------------------------------------===//
2555
Ted Kremenekfb480492010-01-13 21:46:36 +00002556static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002557 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2558 return getDeclFromExpr(CE->getSubExpr());
2559
Ted Kremenekfb480492010-01-13 21:46:36 +00002560 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2561 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002562 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2563 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002564 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2565 return ME->getMemberDecl();
2566 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2567 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002568 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2569 return PRE->getProperty();
2570
Ted Kremenekfb480492010-01-13 21:46:36 +00002571 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2572 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002573 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2574 if (!CE->isElidable())
2575 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002576 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2577 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002578
Douglas Gregordb1314e2010-10-01 21:11:22 +00002579 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2580 return PE->getProtocol();
2581
Ted Kremenekfb480492010-01-13 21:46:36 +00002582 return 0;
2583}
2584
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002585static SourceLocation getLocationFromExpr(Expr *E) {
2586 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2587 return /*FIXME:*/Msg->getLeftLoc();
2588 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2589 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002590 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2591 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002592 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2593 return Member->getMemberLoc();
2594 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2595 return Ivar->getLocation();
2596 return E->getLocStart();
2597}
2598
Ted Kremenekfb480492010-01-13 21:46:36 +00002599extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002600
2601unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002602 CXCursorVisitor visitor,
2603 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002604 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002605
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002606 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2607 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002608 return CursorVis.VisitChildren(parent);
2609}
2610
David Chisnall3387c652010-11-03 14:12:26 +00002611#ifndef __has_feature
2612#define __has_feature(x) 0
2613#endif
2614#if __has_feature(blocks)
2615typedef enum CXChildVisitResult
2616 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2617
2618static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2619 CXClientData client_data) {
2620 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2621 return block(cursor, parent);
2622}
2623#else
2624// If we are compiled with a compiler that doesn't have native blocks support,
2625// define and call the block manually, so the
2626typedef struct _CXChildVisitResult
2627{
2628 void *isa;
2629 int flags;
2630 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002631 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2632 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002633} *CXCursorVisitorBlock;
2634
2635static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2636 CXClientData client_data) {
2637 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2638 return block->invoke(block, cursor, parent);
2639}
2640#endif
2641
2642
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002643unsigned clang_visitChildrenWithBlock(CXCursor parent,
2644 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002645 return clang_visitChildren(parent, visitWithBlock, block);
2646}
2647
Douglas Gregor78205d42010-01-20 21:45:58 +00002648static CXString getDeclSpelling(Decl *D) {
2649 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2650 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002651 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002652
Douglas Gregor78205d42010-01-20 21:45:58 +00002653 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002654 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002655
Douglas Gregor78205d42010-01-20 21:45:58 +00002656 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2657 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2658 // and returns different names. NamedDecl returns the class name and
2659 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002660 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002661
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002662 if (isa<UsingDirectiveDecl>(D))
2663 return createCXString("");
2664
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002665 llvm::SmallString<1024> S;
2666 llvm::raw_svector_ostream os(S);
2667 ND->printName(os);
2668
2669 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002670}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002671
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002672CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002673 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002674 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002675
Steve Narofff334b4e2009-09-02 18:26:48 +00002676 if (clang_isReference(C.kind)) {
2677 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002678 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002679 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002680 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002681 }
2682 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002683 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002684 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002685 }
2686 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002687 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002688 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002689 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002690 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002691 case CXCursor_CXXBaseSpecifier: {
2692 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2693 return createCXString(B->getType().getAsString());
2694 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002695 case CXCursor_TypeRef: {
2696 TypeDecl *Type = getCursorTypeRef(C).first;
2697 assert(Type && "Missing type decl");
2698
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002699 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2700 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002701 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002702 case CXCursor_TemplateRef: {
2703 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002704 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002705
2706 return createCXString(Template->getNameAsString());
2707 }
Douglas Gregor69319002010-08-31 23:48:11 +00002708
2709 case CXCursor_NamespaceRef: {
2710 NamedDecl *NS = getCursorNamespaceRef(C).first;
2711 assert(NS && "Missing namespace decl");
2712
2713 return createCXString(NS->getNameAsString());
2714 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002715
Douglas Gregora67e03f2010-09-09 21:42:20 +00002716 case CXCursor_MemberRef: {
2717 FieldDecl *Field = getCursorMemberRef(C).first;
2718 assert(Field && "Missing member decl");
2719
2720 return createCXString(Field->getNameAsString());
2721 }
2722
Douglas Gregor36897b02010-09-10 00:22:18 +00002723 case CXCursor_LabelRef: {
2724 LabelStmt *Label = getCursorLabelRef(C).first;
2725 assert(Label && "Missing label");
2726
2727 return createCXString(Label->getID()->getName());
2728 }
2729
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002730 case CXCursor_OverloadedDeclRef: {
2731 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2732 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2733 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2734 return createCXString(ND->getNameAsString());
2735 return createCXString("");
2736 }
2737 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2738 return createCXString(E->getName().getAsString());
2739 OverloadedTemplateStorage *Ovl
2740 = Storage.get<OverloadedTemplateStorage*>();
2741 if (Ovl->size() == 0)
2742 return createCXString("");
2743 return createCXString((*Ovl->begin())->getNameAsString());
2744 }
2745
Daniel Dunbaracca7252009-11-30 20:42:49 +00002746 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002747 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002748 }
2749 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002750
2751 if (clang_isExpression(C.kind)) {
2752 Decl *D = getDeclFromExpr(getCursorExpr(C));
2753 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002754 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002755 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002756 }
2757
Douglas Gregor36897b02010-09-10 00:22:18 +00002758 if (clang_isStatement(C.kind)) {
2759 Stmt *S = getCursorStmt(C);
2760 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2761 return createCXString(Label->getID()->getName());
2762
2763 return createCXString("");
2764 }
2765
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002766 if (C.kind == CXCursor_MacroInstantiation)
2767 return createCXString(getCursorMacroInstantiation(C)->getName()
2768 ->getNameStart());
2769
Douglas Gregor572feb22010-03-18 18:04:21 +00002770 if (C.kind == CXCursor_MacroDefinition)
2771 return createCXString(getCursorMacroDefinition(C)->getName()
2772 ->getNameStart());
2773
Douglas Gregorecdcb882010-10-20 22:00:55 +00002774 if (C.kind == CXCursor_InclusionDirective)
2775 return createCXString(getCursorInclusionDirective(C)->getFileName());
2776
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002777 if (clang_isDeclaration(C.kind))
2778 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002779
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002780 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002781}
2782
Douglas Gregor358559d2010-10-02 22:49:11 +00002783CXString clang_getCursorDisplayName(CXCursor C) {
2784 if (!clang_isDeclaration(C.kind))
2785 return clang_getCursorSpelling(C);
2786
2787 Decl *D = getCursorDecl(C);
2788 if (!D)
2789 return createCXString("");
2790
2791 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2792 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2793 D = FunTmpl->getTemplatedDecl();
2794
2795 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2796 llvm::SmallString<64> Str;
2797 llvm::raw_svector_ostream OS(Str);
2798 OS << Function->getNameAsString();
2799 if (Function->getPrimaryTemplate())
2800 OS << "<>";
2801 OS << "(";
2802 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2803 if (I)
2804 OS << ", ";
2805 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2806 }
2807
2808 if (Function->isVariadic()) {
2809 if (Function->getNumParams())
2810 OS << ", ";
2811 OS << "...";
2812 }
2813 OS << ")";
2814 return createCXString(OS.str());
2815 }
2816
2817 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2818 llvm::SmallString<64> Str;
2819 llvm::raw_svector_ostream OS(Str);
2820 OS << ClassTemplate->getNameAsString();
2821 OS << "<";
2822 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2823 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2824 if (I)
2825 OS << ", ";
2826
2827 NamedDecl *Param = Params->getParam(I);
2828 if (Param->getIdentifier()) {
2829 OS << Param->getIdentifier()->getName();
2830 continue;
2831 }
2832
2833 // There is no parameter name, which makes this tricky. Try to come up
2834 // with something useful that isn't too long.
2835 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2836 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2837 else if (NonTypeTemplateParmDecl *NTTP
2838 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2839 OS << NTTP->getType().getAsString(Policy);
2840 else
2841 OS << "template<...> class";
2842 }
2843
2844 OS << ">";
2845 return createCXString(OS.str());
2846 }
2847
2848 if (ClassTemplateSpecializationDecl *ClassSpec
2849 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2850 // If the type was explicitly written, use that.
2851 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2852 return createCXString(TSInfo->getType().getAsString(Policy));
2853
2854 llvm::SmallString<64> Str;
2855 llvm::raw_svector_ostream OS(Str);
2856 OS << ClassSpec->getNameAsString();
2857 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002858 ClassSpec->getTemplateArgs().data(),
2859 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002860 Policy);
2861 return createCXString(OS.str());
2862 }
2863
2864 return clang_getCursorSpelling(C);
2865}
2866
Ted Kremeneke68fff62010-02-17 00:41:32 +00002867CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002868 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002869 case CXCursor_FunctionDecl:
2870 return createCXString("FunctionDecl");
2871 case CXCursor_TypedefDecl:
2872 return createCXString("TypedefDecl");
2873 case CXCursor_EnumDecl:
2874 return createCXString("EnumDecl");
2875 case CXCursor_EnumConstantDecl:
2876 return createCXString("EnumConstantDecl");
2877 case CXCursor_StructDecl:
2878 return createCXString("StructDecl");
2879 case CXCursor_UnionDecl:
2880 return createCXString("UnionDecl");
2881 case CXCursor_ClassDecl:
2882 return createCXString("ClassDecl");
2883 case CXCursor_FieldDecl:
2884 return createCXString("FieldDecl");
2885 case CXCursor_VarDecl:
2886 return createCXString("VarDecl");
2887 case CXCursor_ParmDecl:
2888 return createCXString("ParmDecl");
2889 case CXCursor_ObjCInterfaceDecl:
2890 return createCXString("ObjCInterfaceDecl");
2891 case CXCursor_ObjCCategoryDecl:
2892 return createCXString("ObjCCategoryDecl");
2893 case CXCursor_ObjCProtocolDecl:
2894 return createCXString("ObjCProtocolDecl");
2895 case CXCursor_ObjCPropertyDecl:
2896 return createCXString("ObjCPropertyDecl");
2897 case CXCursor_ObjCIvarDecl:
2898 return createCXString("ObjCIvarDecl");
2899 case CXCursor_ObjCInstanceMethodDecl:
2900 return createCXString("ObjCInstanceMethodDecl");
2901 case CXCursor_ObjCClassMethodDecl:
2902 return createCXString("ObjCClassMethodDecl");
2903 case CXCursor_ObjCImplementationDecl:
2904 return createCXString("ObjCImplementationDecl");
2905 case CXCursor_ObjCCategoryImplDecl:
2906 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002907 case CXCursor_CXXMethod:
2908 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002909 case CXCursor_UnexposedDecl:
2910 return createCXString("UnexposedDecl");
2911 case CXCursor_ObjCSuperClassRef:
2912 return createCXString("ObjCSuperClassRef");
2913 case CXCursor_ObjCProtocolRef:
2914 return createCXString("ObjCProtocolRef");
2915 case CXCursor_ObjCClassRef:
2916 return createCXString("ObjCClassRef");
2917 case CXCursor_TypeRef:
2918 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002919 case CXCursor_TemplateRef:
2920 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002921 case CXCursor_NamespaceRef:
2922 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002923 case CXCursor_MemberRef:
2924 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002925 case CXCursor_LabelRef:
2926 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002927 case CXCursor_OverloadedDeclRef:
2928 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002929 case CXCursor_UnexposedExpr:
2930 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002931 case CXCursor_BlockExpr:
2932 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002933 case CXCursor_DeclRefExpr:
2934 return createCXString("DeclRefExpr");
2935 case CXCursor_MemberRefExpr:
2936 return createCXString("MemberRefExpr");
2937 case CXCursor_CallExpr:
2938 return createCXString("CallExpr");
2939 case CXCursor_ObjCMessageExpr:
2940 return createCXString("ObjCMessageExpr");
2941 case CXCursor_UnexposedStmt:
2942 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002943 case CXCursor_LabelStmt:
2944 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002945 case CXCursor_InvalidFile:
2946 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002947 case CXCursor_InvalidCode:
2948 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002949 case CXCursor_NoDeclFound:
2950 return createCXString("NoDeclFound");
2951 case CXCursor_NotImplemented:
2952 return createCXString("NotImplemented");
2953 case CXCursor_TranslationUnit:
2954 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002955 case CXCursor_UnexposedAttr:
2956 return createCXString("UnexposedAttr");
2957 case CXCursor_IBActionAttr:
2958 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002959 case CXCursor_IBOutletAttr:
2960 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002961 case CXCursor_IBOutletCollectionAttr:
2962 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002963 case CXCursor_PreprocessingDirective:
2964 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002965 case CXCursor_MacroDefinition:
2966 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002967 case CXCursor_MacroInstantiation:
2968 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002969 case CXCursor_InclusionDirective:
2970 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002971 case CXCursor_Namespace:
2972 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002973 case CXCursor_LinkageSpec:
2974 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002975 case CXCursor_CXXBaseSpecifier:
2976 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002977 case CXCursor_Constructor:
2978 return createCXString("CXXConstructor");
2979 case CXCursor_Destructor:
2980 return createCXString("CXXDestructor");
2981 case CXCursor_ConversionFunction:
2982 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002983 case CXCursor_TemplateTypeParameter:
2984 return createCXString("TemplateTypeParameter");
2985 case CXCursor_NonTypeTemplateParameter:
2986 return createCXString("NonTypeTemplateParameter");
2987 case CXCursor_TemplateTemplateParameter:
2988 return createCXString("TemplateTemplateParameter");
2989 case CXCursor_FunctionTemplate:
2990 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002991 case CXCursor_ClassTemplate:
2992 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002993 case CXCursor_ClassTemplatePartialSpecialization:
2994 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002995 case CXCursor_NamespaceAlias:
2996 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002997 case CXCursor_UsingDirective:
2998 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002999 case CXCursor_UsingDeclaration:
3000 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003001 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003002
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003003 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003004 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003005}
Steve Naroff89922f82009-08-31 00:59:03 +00003006
Ted Kremeneke68fff62010-02-17 00:41:32 +00003007enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3008 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003009 CXClientData client_data) {
3010 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003011
3012 // If our current best cursor is the construction of a temporary object,
3013 // don't replace that cursor with a type reference, because we want
3014 // clang_getCursor() to point at the constructor.
3015 if (clang_isExpression(BestCursor->kind) &&
3016 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3017 cursor.kind == CXCursor_TypeRef)
3018 return CXChildVisit_Recurse;
3019
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003020 *BestCursor = cursor;
3021 return CXChildVisit_Recurse;
3022}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003023
Douglas Gregorb9790342010-01-22 21:44:22 +00003024CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3025 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003026 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003027
Douglas Gregorb9790342010-01-22 21:44:22 +00003028 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003029 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3030
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003031 // Translate the given source location to make it point at the beginning of
3032 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003033 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003034
3035 // Guard against an invalid SourceLocation, or we may assert in one
3036 // of the following calls.
3037 if (SLoc.isInvalid())
3038 return clang_getNullCursor();
3039
Douglas Gregor40749ee2010-11-03 00:35:38 +00003040 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003041 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3042 CXXUnit->getASTContext().getLangOptions());
3043
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003044 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3045 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003046 // FIXME: Would be great to have a "hint" cursor, then walk from that
3047 // hint cursor upward until we find a cursor whose source range encloses
3048 // the region of interest, rather than starting from the translation unit.
3049 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003050 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003051 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003052 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003053 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003054
3055 if (Logging) {
3056 CXFile SearchFile;
3057 unsigned SearchLine, SearchColumn;
3058 CXFile ResultFile;
3059 unsigned ResultLine, ResultColumn;
3060 CXString SearchFileName, ResultFileName, KindSpelling;
3061 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3062
3063 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3064 0);
3065 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3066 &ResultColumn, 0);
3067 SearchFileName = clang_getFileName(SearchFile);
3068 ResultFileName = clang_getFileName(ResultFile);
3069 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3070 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3071 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3072 clang_getCString(KindSpelling),
3073 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3074 clang_disposeString(SearchFileName);
3075 clang_disposeString(ResultFileName);
3076 clang_disposeString(KindSpelling);
3077 }
3078
Ted Kremeneke68fff62010-02-17 00:41:32 +00003079 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003080}
3081
Ted Kremenek73885552009-11-17 19:28:59 +00003082CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003083 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003084}
3085
3086unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003087 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003088}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003089
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003090unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003091 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3092}
3093
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003094unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003095 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3096}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003097
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003098unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003099 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3100}
3101
Douglas Gregor97b98722010-01-19 23:20:36 +00003102unsigned clang_isExpression(enum CXCursorKind K) {
3103 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3104}
3105
3106unsigned clang_isStatement(enum CXCursorKind K) {
3107 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3108}
3109
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003110unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3111 return K == CXCursor_TranslationUnit;
3112}
3113
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003114unsigned clang_isPreprocessing(enum CXCursorKind K) {
3115 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3116}
3117
Ted Kremenekad6eff62010-03-08 21:17:29 +00003118unsigned clang_isUnexposed(enum CXCursorKind K) {
3119 switch (K) {
3120 case CXCursor_UnexposedDecl:
3121 case CXCursor_UnexposedExpr:
3122 case CXCursor_UnexposedStmt:
3123 case CXCursor_UnexposedAttr:
3124 return true;
3125 default:
3126 return false;
3127 }
3128}
3129
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003130CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003131 return C.kind;
3132}
3133
Douglas Gregor98258af2010-01-18 22:46:11 +00003134CXSourceLocation clang_getCursorLocation(CXCursor C) {
3135 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003136 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003137 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003138 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3139 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003140 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003141 }
3142
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003143 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003144 std::pair<ObjCProtocolDecl *, SourceLocation> P
3145 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003146 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003147 }
3148
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003149 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003150 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3151 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003152 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003153 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003154
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003155 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003156 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003157 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003158 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003159
3160 case CXCursor_TemplateRef: {
3161 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3162 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3163 }
3164
Douglas Gregor69319002010-08-31 23:48:11 +00003165 case CXCursor_NamespaceRef: {
3166 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3167 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3168 }
3169
Douglas Gregora67e03f2010-09-09 21:42:20 +00003170 case CXCursor_MemberRef: {
3171 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3172 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3173 }
3174
Ted Kremenek3064ef92010-08-27 21:34:58 +00003175 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003176 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3177 if (!BaseSpec)
3178 return clang_getNullLocation();
3179
3180 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3181 return cxloc::translateSourceLocation(getCursorContext(C),
3182 TSInfo->getTypeLoc().getBeginLoc());
3183
3184 return cxloc::translateSourceLocation(getCursorContext(C),
3185 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003186 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003187
Douglas Gregor36897b02010-09-10 00:22:18 +00003188 case CXCursor_LabelRef: {
3189 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3190 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3191 }
3192
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003193 case CXCursor_OverloadedDeclRef:
3194 return cxloc::translateSourceLocation(getCursorContext(C),
3195 getCursorOverloadedDeclRef(C).second);
3196
Douglas Gregorf46034a2010-01-18 23:41:10 +00003197 default:
3198 // FIXME: Need a way to enumerate all non-reference cases.
3199 llvm_unreachable("Missed a reference kind");
3200 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003201 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003202
3203 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003204 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003205 getLocationFromExpr(getCursorExpr(C)));
3206
Douglas Gregor36897b02010-09-10 00:22:18 +00003207 if (clang_isStatement(C.kind))
3208 return cxloc::translateSourceLocation(getCursorContext(C),
3209 getCursorStmt(C)->getLocStart());
3210
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003211 if (C.kind == CXCursor_PreprocessingDirective) {
3212 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3213 return cxloc::translateSourceLocation(getCursorContext(C), L);
3214 }
Douglas Gregor48072312010-03-18 15:23:44 +00003215
3216 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003217 SourceLocation L
3218 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003219 return cxloc::translateSourceLocation(getCursorContext(C), L);
3220 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003221
3222 if (C.kind == CXCursor_MacroDefinition) {
3223 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3224 return cxloc::translateSourceLocation(getCursorContext(C), L);
3225 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003226
3227 if (C.kind == CXCursor_InclusionDirective) {
3228 SourceLocation L
3229 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3230 return cxloc::translateSourceLocation(getCursorContext(C), L);
3231 }
3232
Ted Kremenek9a700d22010-05-12 06:16:13 +00003233 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003234 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003235
Douglas Gregorf46034a2010-01-18 23:41:10 +00003236 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003237 SourceLocation Loc = D->getLocation();
3238 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3239 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003240 // FIXME: Multiple variables declared in a single declaration
3241 // currently lack the information needed to correctly determine their
3242 // ranges when accounting for the type-specifier. We use context
3243 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3244 // and if so, whether it is the first decl.
3245 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3246 if (!cxcursor::isFirstInDeclGroup(C))
3247 Loc = VD->getLocation();
3248 }
3249
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003250 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003251}
Douglas Gregora7bde202010-01-19 00:34:46 +00003252
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003253} // end extern "C"
3254
3255static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003256 if (clang_isReference(C.kind)) {
3257 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003258 case CXCursor_ObjCSuperClassRef:
3259 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003260
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003261 case CXCursor_ObjCProtocolRef:
3262 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003263
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003264 case CXCursor_ObjCClassRef:
3265 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003266
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003267 case CXCursor_TypeRef:
3268 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003269
3270 case CXCursor_TemplateRef:
3271 return getCursorTemplateRef(C).second;
3272
Douglas Gregor69319002010-08-31 23:48:11 +00003273 case CXCursor_NamespaceRef:
3274 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003275
3276 case CXCursor_MemberRef:
3277 return getCursorMemberRef(C).second;
3278
Ted Kremenek3064ef92010-08-27 21:34:58 +00003279 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003280 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003281
Douglas Gregor36897b02010-09-10 00:22:18 +00003282 case CXCursor_LabelRef:
3283 return getCursorLabelRef(C).second;
3284
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003285 case CXCursor_OverloadedDeclRef:
3286 return getCursorOverloadedDeclRef(C).second;
3287
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003288 default:
3289 // FIXME: Need a way to enumerate all non-reference cases.
3290 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003291 }
3292 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003293
3294 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003295 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003296
3297 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003298 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003299
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003300 if (C.kind == CXCursor_PreprocessingDirective)
3301 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003302
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003303 if (C.kind == CXCursor_MacroInstantiation)
3304 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003305
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003306 if (C.kind == CXCursor_MacroDefinition)
3307 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003308
3309 if (C.kind == CXCursor_InclusionDirective)
3310 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3311
Ted Kremenek007a7c92010-11-01 23:26:51 +00003312 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3313 Decl *D = cxcursor::getCursorDecl(C);
3314 SourceRange R = D->getSourceRange();
3315 // FIXME: Multiple variables declared in a single declaration
3316 // currently lack the information needed to correctly determine their
3317 // ranges when accounting for the type-specifier. We use context
3318 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3319 // and if so, whether it is the first decl.
3320 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3321 if (!cxcursor::isFirstInDeclGroup(C))
3322 R.setBegin(VD->getLocation());
3323 }
3324 return R;
3325 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003326 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003327
3328extern "C" {
3329
3330CXSourceRange clang_getCursorExtent(CXCursor C) {
3331 SourceRange R = getRawCursorExtent(C);
3332 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003333 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003334
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003335 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003336}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003337
3338CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003339 if (clang_isInvalid(C.kind))
3340 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003341
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003342 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003343 if (clang_isDeclaration(C.kind)) {
3344 Decl *D = getCursorDecl(C);
3345 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3346 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3347 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3348 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3349 if (ObjCForwardProtocolDecl *Protocols
3350 = dyn_cast<ObjCForwardProtocolDecl>(D))
3351 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3352
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003353 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003354 }
3355
Douglas Gregor97b98722010-01-19 23:20:36 +00003356 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003357 Expr *E = getCursorExpr(C);
3358 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003359 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003360 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003361
3362 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3363 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3364
Douglas Gregor97b98722010-01-19 23:20:36 +00003365 return clang_getNullCursor();
3366 }
3367
Douglas Gregor36897b02010-09-10 00:22:18 +00003368 if (clang_isStatement(C.kind)) {
3369 Stmt *S = getCursorStmt(C);
3370 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3371 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3372 getCursorASTUnit(C));
3373
3374 return clang_getNullCursor();
3375 }
3376
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003377 if (C.kind == CXCursor_MacroInstantiation) {
3378 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3379 return MakeMacroDefinitionCursor(Def, CXXUnit);
3380 }
3381
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003382 if (!clang_isReference(C.kind))
3383 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003384
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003385 switch (C.kind) {
3386 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003387 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003388
3389 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003390 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003391
3392 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003393 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003394
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003395 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003396 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003397
3398 case CXCursor_TemplateRef:
3399 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3400
Douglas Gregor69319002010-08-31 23:48:11 +00003401 case CXCursor_NamespaceRef:
3402 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3403
Douglas Gregora67e03f2010-09-09 21:42:20 +00003404 case CXCursor_MemberRef:
3405 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3406
Ted Kremenek3064ef92010-08-27 21:34:58 +00003407 case CXCursor_CXXBaseSpecifier: {
3408 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3409 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3410 CXXUnit));
3411 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003412
Douglas Gregor36897b02010-09-10 00:22:18 +00003413 case CXCursor_LabelRef:
3414 // FIXME: We end up faking the "parent" declaration here because we
3415 // don't want to make CXCursor larger.
3416 return MakeCXCursor(getCursorLabelRef(C).first,
3417 CXXUnit->getASTContext().getTranslationUnitDecl(),
3418 CXXUnit);
3419
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003420 case CXCursor_OverloadedDeclRef:
3421 return C;
3422
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003423 default:
3424 // We would prefer to enumerate all non-reference cursor kinds here.
3425 llvm_unreachable("Unhandled reference cursor kind");
3426 break;
3427 }
3428 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003429
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003430 return clang_getNullCursor();
3431}
3432
Douglas Gregorb6998662010-01-19 19:34:47 +00003433CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003434 if (clang_isInvalid(C.kind))
3435 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003436
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003437 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438
Douglas Gregorb6998662010-01-19 19:34:47 +00003439 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003440 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003441 C = clang_getCursorReferenced(C);
3442 WasReference = true;
3443 }
3444
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003445 if (C.kind == CXCursor_MacroInstantiation)
3446 return clang_getCursorReferenced(C);
3447
Douglas Gregorb6998662010-01-19 19:34:47 +00003448 if (!clang_isDeclaration(C.kind))
3449 return clang_getNullCursor();
3450
3451 Decl *D = getCursorDecl(C);
3452 if (!D)
3453 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003454
Douglas Gregorb6998662010-01-19 19:34:47 +00003455 switch (D->getKind()) {
3456 // Declaration kinds that don't really separate the notions of
3457 // declaration and definition.
3458 case Decl::Namespace:
3459 case Decl::Typedef:
3460 case Decl::TemplateTypeParm:
3461 case Decl::EnumConstant:
3462 case Decl::Field:
3463 case Decl::ObjCIvar:
3464 case Decl::ObjCAtDefsField:
3465 case Decl::ImplicitParam:
3466 case Decl::ParmVar:
3467 case Decl::NonTypeTemplateParm:
3468 case Decl::TemplateTemplateParm:
3469 case Decl::ObjCCategoryImpl:
3470 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003471 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003472 case Decl::LinkageSpec:
3473 case Decl::ObjCPropertyImpl:
3474 case Decl::FileScopeAsm:
3475 case Decl::StaticAssert:
3476 case Decl::Block:
3477 return C;
3478
3479 // Declaration kinds that don't make any sense here, but are
3480 // nonetheless harmless.
3481 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003482 break;
3483
3484 // Declaration kinds for which the definition is not resolvable.
3485 case Decl::UnresolvedUsingTypename:
3486 case Decl::UnresolvedUsingValue:
3487 break;
3488
3489 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003490 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3491 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003492
3493 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003494 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003495
3496 case Decl::Enum:
3497 case Decl::Record:
3498 case Decl::CXXRecord:
3499 case Decl::ClassTemplateSpecialization:
3500 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003501 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003502 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003503 return clang_getNullCursor();
3504
3505 case Decl::Function:
3506 case Decl::CXXMethod:
3507 case Decl::CXXConstructor:
3508 case Decl::CXXDestructor:
3509 case Decl::CXXConversion: {
3510 const FunctionDecl *Def = 0;
3511 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003512 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003513 return clang_getNullCursor();
3514 }
3515
3516 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003517 // Ask the variable if it has a definition.
3518 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3519 return MakeCXCursor(Def, CXXUnit);
3520 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003521 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003522
Douglas Gregorb6998662010-01-19 19:34:47 +00003523 case Decl::FunctionTemplate: {
3524 const FunctionDecl *Def = 0;
3525 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003526 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003527 return clang_getNullCursor();
3528 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003529
Douglas Gregorb6998662010-01-19 19:34:47 +00003530 case Decl::ClassTemplate: {
3531 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003532 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003533 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003534 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003535 return clang_getNullCursor();
3536 }
3537
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003538 case Decl::Using:
3539 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3540 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003541
3542 case Decl::UsingShadow:
3543 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003544 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003545 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003546
3547 case Decl::ObjCMethod: {
3548 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3549 if (Method->isThisDeclarationADefinition())
3550 return C;
3551
3552 // Dig out the method definition in the associated
3553 // @implementation, if we have it.
3554 // FIXME: The ASTs should make finding the definition easier.
3555 if (ObjCInterfaceDecl *Class
3556 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3557 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3558 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3559 Method->isInstanceMethod()))
3560 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003561 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003562
3563 return clang_getNullCursor();
3564 }
3565
3566 case Decl::ObjCCategory:
3567 if (ObjCCategoryImplDecl *Impl
3568 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003569 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003570 return clang_getNullCursor();
3571
3572 case Decl::ObjCProtocol:
3573 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3574 return C;
3575 return clang_getNullCursor();
3576
3577 case Decl::ObjCInterface:
3578 // There are two notions of a "definition" for an Objective-C
3579 // class: the interface and its implementation. When we resolved a
3580 // reference to an Objective-C class, produce the @interface as
3581 // the definition; when we were provided with the interface,
3582 // produce the @implementation as the definition.
3583 if (WasReference) {
3584 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3585 return C;
3586 } else if (ObjCImplementationDecl *Impl
3587 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003588 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003589 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003590
Douglas Gregorb6998662010-01-19 19:34:47 +00003591 case Decl::ObjCProperty:
3592 // FIXME: We don't really know where to find the
3593 // ObjCPropertyImplDecls that implement this property.
3594 return clang_getNullCursor();
3595
3596 case Decl::ObjCCompatibleAlias:
3597 if (ObjCInterfaceDecl *Class
3598 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3599 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003600 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003601
Douglas Gregorb6998662010-01-19 19:34:47 +00003602 return clang_getNullCursor();
3603
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003604 case Decl::ObjCForwardProtocol:
3605 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3606 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003607
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003608 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003609 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003610 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003611
3612 case Decl::Friend:
3613 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003614 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003615 return clang_getNullCursor();
3616
3617 case Decl::FriendTemplate:
3618 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003619 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003620 return clang_getNullCursor();
3621 }
3622
3623 return clang_getNullCursor();
3624}
3625
3626unsigned clang_isCursorDefinition(CXCursor C) {
3627 if (!clang_isDeclaration(C.kind))
3628 return 0;
3629
3630 return clang_getCursorDefinition(C) == C;
3631}
3632
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003633unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003634 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003635 return 0;
3636
3637 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3638 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3639 return E->getNumDecls();
3640
3641 if (OverloadedTemplateStorage *S
3642 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3643 return S->size();
3644
3645 Decl *D = Storage.get<Decl*>();
3646 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003647 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003648 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3649 return Classes->size();
3650 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3651 return Protocols->protocol_size();
3652
3653 return 0;
3654}
3655
3656CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003657 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003658 return clang_getNullCursor();
3659
3660 if (index >= clang_getNumOverloadedDecls(cursor))
3661 return clang_getNullCursor();
3662
3663 ASTUnit *Unit = getCursorASTUnit(cursor);
3664 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3665 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3666 return MakeCXCursor(E->decls_begin()[index], Unit);
3667
3668 if (OverloadedTemplateStorage *S
3669 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3670 return MakeCXCursor(S->begin()[index], Unit);
3671
3672 Decl *D = Storage.get<Decl*>();
3673 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3674 // FIXME: This is, unfortunately, linear time.
3675 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3676 std::advance(Pos, index);
3677 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3678 }
3679
3680 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3681 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3682
3683 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3684 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3685
3686 return clang_getNullCursor();
3687}
3688
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003689void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003690 const char **startBuf,
3691 const char **endBuf,
3692 unsigned *startLine,
3693 unsigned *startColumn,
3694 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003695 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003696 assert(getCursorDecl(C) && "CXCursor has null decl");
3697 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003698 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3699 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003700
Steve Naroff4ade6d62009-09-23 17:52:52 +00003701 SourceManager &SM = FD->getASTContext().getSourceManager();
3702 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3703 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3704 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3705 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3706 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3707 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3708}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003709
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003710void clang_enableStackTraces(void) {
3711 llvm::sys::PrintStackTraceOnErrorSignal();
3712}
3713
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003714void clang_executeOnThread(void (*fn)(void*), void *user_data,
3715 unsigned stack_size) {
3716 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3717}
3718
Ted Kremenekfb480492010-01-13 21:46:36 +00003719} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003720
Ted Kremenekfb480492010-01-13 21:46:36 +00003721//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003722// Token-based Operations.
3723//===----------------------------------------------------------------------===//
3724
3725/* CXToken layout:
3726 * int_data[0]: a CXTokenKind
3727 * int_data[1]: starting token location
3728 * int_data[2]: token length
3729 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003730 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003731 * otherwise unused.
3732 */
3733extern "C" {
3734
3735CXTokenKind clang_getTokenKind(CXToken CXTok) {
3736 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3737}
3738
3739CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3740 switch (clang_getTokenKind(CXTok)) {
3741 case CXToken_Identifier:
3742 case CXToken_Keyword:
3743 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003744 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3745 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003746
3747 case CXToken_Literal: {
3748 // We have stashed the starting pointer in the ptr_data field. Use it.
3749 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003750 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003751 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003752
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003753 case CXToken_Punctuation:
3754 case CXToken_Comment:
3755 break;
3756 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003757
3758 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003759 // deconstructing the source location.
3760 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3761 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003762 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003763
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003764 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3765 std::pair<FileID, unsigned> LocInfo
3766 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003767 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003768 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003769 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3770 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003771 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003772
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003773 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003774}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003775
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003776CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3777 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3778 if (!CXXUnit)
3779 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003780
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003781 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3782 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3783}
3784
3785CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3786 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003787 if (!CXXUnit)
3788 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003789
3790 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003791 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3792}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003793
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003794void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3795 CXToken **Tokens, unsigned *NumTokens) {
3796 if (Tokens)
3797 *Tokens = 0;
3798 if (NumTokens)
3799 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003800
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003801 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3802 if (!CXXUnit || !Tokens || !NumTokens)
3803 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003804
Douglas Gregorbdf60622010-03-05 21:16:25 +00003805 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3806
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003807 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003808 if (R.isInvalid())
3809 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003810
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003811 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3812 std::pair<FileID, unsigned> BeginLocInfo
3813 = SourceMgr.getDecomposedLoc(R.getBegin());
3814 std::pair<FileID, unsigned> EndLocInfo
3815 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003816
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003817 // Cannot tokenize across files.
3818 if (BeginLocInfo.first != EndLocInfo.first)
3819 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003820
3821 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003822 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003823 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003824 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003825 if (Invalid)
3826 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003827
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003828 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3829 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003830 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003831 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003833 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003834 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003835 llvm::SmallVector<CXToken, 32> CXTokens;
3836 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003837 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003838 do {
3839 // Lex the next token
3840 Lex.LexFromRawLexer(Tok);
3841 if (Tok.is(tok::eof))
3842 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003844 // Initialize the CXToken.
3845 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003847 // - Common fields
3848 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3849 CXTok.int_data[2] = Tok.getLength();
3850 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003852 // - Kind-specific fields
3853 if (Tok.isLiteral()) {
3854 CXTok.int_data[0] = CXToken_Literal;
3855 CXTok.ptr_data = (void *)Tok.getLiteralData();
3856 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003857 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003858 std::pair<FileID, unsigned> LocInfo
3859 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003860 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003861 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003862 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3863 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003864 return;
3865
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003866 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003867 IdentifierInfo *II
3868 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003869
David Chisnall096428b2010-10-13 21:44:48 +00003870 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003871 CXTok.int_data[0] = CXToken_Keyword;
3872 }
3873 else {
3874 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3875 CXToken_Identifier
3876 : CXToken_Keyword;
3877 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 CXTok.ptr_data = II;
3879 } else if (Tok.is(tok::comment)) {
3880 CXTok.int_data[0] = CXToken_Comment;
3881 CXTok.ptr_data = 0;
3882 } else {
3883 CXTok.int_data[0] = CXToken_Punctuation;
3884 CXTok.ptr_data = 0;
3885 }
3886 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003887 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003888 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003889
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 if (CXTokens.empty())
3891 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003892
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3894 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3895 *NumTokens = CXTokens.size();
3896}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003897
Ted Kremenek6db61092010-05-05 00:55:15 +00003898void clang_disposeTokens(CXTranslationUnit TU,
3899 CXToken *Tokens, unsigned NumTokens) {
3900 free(Tokens);
3901}
3902
3903} // end: extern "C"
3904
3905//===----------------------------------------------------------------------===//
3906// Token annotation APIs.
3907//===----------------------------------------------------------------------===//
3908
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003909typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003910static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3911 CXCursor parent,
3912 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003913namespace {
3914class AnnotateTokensWorker {
3915 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003916 CXToken *Tokens;
3917 CXCursor *Cursors;
3918 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003919 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003920 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003921 CursorVisitor AnnotateVis;
3922 SourceManager &SrcMgr;
3923
3924 bool MoreTokens() const { return TokIdx < NumTokens; }
3925 unsigned NextToken() const { return TokIdx; }
3926 void AdvanceToken() { ++TokIdx; }
3927 SourceLocation GetTokenLoc(unsigned tokI) {
3928 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3929 }
3930
Ted Kremenek6db61092010-05-05 00:55:15 +00003931public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003932 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003933 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3934 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003935 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003936 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003937 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3938 Decl::MaxPCHLevel, RegionOfInterest),
3939 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003940
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003941 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003942 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003943 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003944 void AnnotateTokens() {
3945 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3946 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003947};
3948}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003949
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003950void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3951 // Walk the AST within the region of interest, annotating tokens
3952 // along the way.
3953 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003954
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003955 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3956 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003957 if (Pos != Annotated.end() &&
3958 (clang_isInvalid(Cursors[I].kind) ||
3959 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003960 Cursors[I] = Pos->second;
3961 }
3962
3963 // Finish up annotating any tokens left.
3964 if (!MoreTokens())
3965 return;
3966
3967 const CXCursor &C = clang_getNullCursor();
3968 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3969 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3970 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003971 }
3972}
3973
Ted Kremenek6db61092010-05-05 00:55:15 +00003974enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003975AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003976 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003977 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003978 if (cursorRange.isInvalid())
3979 return CXChildVisit_Recurse;
3980
Douglas Gregor4419b672010-10-21 06:10:04 +00003981 if (clang_isPreprocessing(cursor.kind)) {
3982 // For macro instantiations, just note where the beginning of the macro
3983 // instantiation occurs.
3984 if (cursor.kind == CXCursor_MacroInstantiation) {
3985 Annotated[Loc.int_data] = cursor;
3986 return CXChildVisit_Recurse;
3987 }
3988
Douglas Gregor4419b672010-10-21 06:10:04 +00003989 // Items in the preprocessing record are kept separate from items in
3990 // declarations, so we keep a separate token index.
3991 unsigned SavedTokIdx = TokIdx;
3992 TokIdx = PreprocessingTokIdx;
3993
3994 // Skip tokens up until we catch up to the beginning of the preprocessing
3995 // entry.
3996 while (MoreTokens()) {
3997 const unsigned I = NextToken();
3998 SourceLocation TokLoc = GetTokenLoc(I);
3999 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4000 case RangeBefore:
4001 AdvanceToken();
4002 continue;
4003 case RangeAfter:
4004 case RangeOverlap:
4005 break;
4006 }
4007 break;
4008 }
4009
4010 // Look at all of the tokens within this range.
4011 while (MoreTokens()) {
4012 const unsigned I = NextToken();
4013 SourceLocation TokLoc = GetTokenLoc(I);
4014 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4015 case RangeBefore:
4016 assert(0 && "Infeasible");
4017 case RangeAfter:
4018 break;
4019 case RangeOverlap:
4020 Cursors[I] = cursor;
4021 AdvanceToken();
4022 continue;
4023 }
4024 break;
4025 }
4026
4027 // Save the preprocessing token index; restore the non-preprocessing
4028 // token index.
4029 PreprocessingTokIdx = TokIdx;
4030 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004031 return CXChildVisit_Recurse;
4032 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004033
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004034 if (cursorRange.isInvalid())
4035 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004036
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004037 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4038
Ted Kremeneka333c662010-05-12 05:29:33 +00004039 // Adjust the annotated range based specific declarations.
4040 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4041 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004042 Decl *D = cxcursor::getCursorDecl(cursor);
4043 // Don't visit synthesized ObjC methods, since they have no syntatic
4044 // representation in the source.
4045 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4046 if (MD->isSynthesized())
4047 return CXChildVisit_Continue;
4048 }
4049 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004050 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4051 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004052 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004053 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004054 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004055 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004056 }
4057 }
4058 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004059
Ted Kremenek3f404602010-08-14 01:14:06 +00004060 // If the location of the cursor occurs within a macro instantiation, record
4061 // the spelling location of the cursor in our annotation map. We can then
4062 // paper over the token labelings during a post-processing step to try and
4063 // get cursor mappings for tokens that are the *arguments* of a macro
4064 // instantiation.
4065 if (L.isMacroID()) {
4066 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4067 // Only invalidate the old annotation if it isn't part of a preprocessing
4068 // directive. Here we assume that the default construction of CXCursor
4069 // results in CXCursor.kind being an initialized value (i.e., 0). If
4070 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004071
Ted Kremenek3f404602010-08-14 01:14:06 +00004072 CXCursor &oldC = Annotated[rawEncoding];
4073 if (!clang_isPreprocessing(oldC.kind))
4074 oldC = cursor;
4075 }
4076
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004077 const enum CXCursorKind K = clang_getCursorKind(parent);
4078 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004079 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4080 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004081
4082 while (MoreTokens()) {
4083 const unsigned I = NextToken();
4084 SourceLocation TokLoc = GetTokenLoc(I);
4085 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4086 case RangeBefore:
4087 Cursors[I] = updateC;
4088 AdvanceToken();
4089 continue;
4090 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004091 case RangeOverlap:
4092 break;
4093 }
4094 break;
4095 }
4096
4097 // Visit children to get their cursor information.
4098 const unsigned BeforeChildren = NextToken();
4099 VisitChildren(cursor);
4100 const unsigned AfterChildren = NextToken();
4101
4102 // Adjust 'Last' to the last token within the extent of the cursor.
4103 while (MoreTokens()) {
4104 const unsigned I = NextToken();
4105 SourceLocation TokLoc = GetTokenLoc(I);
4106 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4107 case RangeBefore:
4108 assert(0 && "Infeasible");
4109 case RangeAfter:
4110 break;
4111 case RangeOverlap:
4112 Cursors[I] = updateC;
4113 AdvanceToken();
4114 continue;
4115 }
4116 break;
4117 }
4118 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004119
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004120 // Scan the tokens that are at the beginning of the cursor, but are not
4121 // capture by the child cursors.
4122
4123 // For AST elements within macros, rely on a post-annotate pass to
4124 // to correctly annotate the tokens with cursors. Otherwise we can
4125 // get confusing results of having tokens that map to cursors that really
4126 // are expanded by an instantiation.
4127 if (L.isMacroID())
4128 cursor = clang_getNullCursor();
4129
4130 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4131 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4132 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004133
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004134 Cursors[I] = cursor;
4135 }
4136 // Scan the tokens that are at the end of the cursor, but are not captured
4137 // but the child cursors.
4138 for (unsigned I = AfterChildren; I != Last; ++I)
4139 Cursors[I] = cursor;
4140
4141 TokIdx = Last;
4142 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004143}
4144
Ted Kremenek6db61092010-05-05 00:55:15 +00004145static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4146 CXCursor parent,
4147 CXClientData client_data) {
4148 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4149}
4150
Ted Kremenekab979612010-11-11 08:05:23 +00004151// This gets run a separate thread to avoid stack blowout.
4152static void runAnnotateTokensWorker(void *UserData) {
4153 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4154}
4155
Ted Kremenek6db61092010-05-05 00:55:15 +00004156extern "C" {
4157
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004158void clang_annotateTokens(CXTranslationUnit TU,
4159 CXToken *Tokens, unsigned NumTokens,
4160 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004161
4162 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004163 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004164
Douglas Gregor4419b672010-10-21 06:10:04 +00004165 // Any token we don't specifically annotate will have a NULL cursor.
4166 CXCursor C = clang_getNullCursor();
4167 for (unsigned I = 0; I != NumTokens; ++I)
4168 Cursors[I] = C;
4169
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004170 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004171 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004172 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004173
Douglas Gregorbdf60622010-03-05 21:16:25 +00004174 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004175
Douglas Gregor0396f462010-03-19 05:22:59 +00004176 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004177 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004178 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4179 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004180 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4181 clang_getTokenLocation(TU,
4182 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004183
Douglas Gregor0396f462010-03-19 05:22:59 +00004184 // A mapping from the source locations found when re-lexing or traversing the
4185 // region of interest to the corresponding cursors.
4186 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004187
4188 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004189 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004190 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4191 std::pair<FileID, unsigned> BeginLocInfo
4192 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4193 std::pair<FileID, unsigned> EndLocInfo
4194 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004195
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004196 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004197 bool Invalid = false;
4198 if (BeginLocInfo.first == EndLocInfo.first &&
4199 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4200 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004201 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4202 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004203 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004204 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004205 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004206
4207 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004208 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004209 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004210 Token Tok;
4211 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004212
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004213 reprocess:
4214 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4215 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004216 // don't see it while preprocessing these tokens later, but keep track
4217 // of all of the token locations inside this preprocessing directive so
4218 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004219 //
4220 // FIXME: Some simple tests here could identify macro definitions and
4221 // #undefs, to provide specific cursor kinds for those.
4222 std::vector<SourceLocation> Locations;
4223 do {
4224 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004225 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004226 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004228 using namespace cxcursor;
4229 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004230 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4231 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004232 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004233 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4234 Annotated[Locations[I].getRawEncoding()] = Cursor;
4235 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004236
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004237 if (Tok.isAtStartOfLine())
4238 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004240 continue;
4241 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004242
Douglas Gregor48072312010-03-18 15:23:44 +00004243 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004244 break;
4245 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004246 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004247
Douglas Gregor0396f462010-03-19 05:22:59 +00004248 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004249 // a specific cursor.
4250 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4251 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004252
4253 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004254 // FIXME: We use a ridiculous stack size here because the data-recursion
4255 // algorithm uses a large stack frame than the non-data recursive version,
4256 // and AnnotationTokensWorker currently transforms the data-recursion
4257 // algorithm back into a traditional recursion by explicitly calling
4258 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004259 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004260 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4261 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004262 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4263 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004264}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004265} // end: extern "C"
4266
4267//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004268// Operations for querying linkage of a cursor.
4269//===----------------------------------------------------------------------===//
4270
4271extern "C" {
4272CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004273 if (!clang_isDeclaration(cursor.kind))
4274 return CXLinkage_Invalid;
4275
Ted Kremenek16b42592010-03-03 06:36:57 +00004276 Decl *D = cxcursor::getCursorDecl(cursor);
4277 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4278 switch (ND->getLinkage()) {
4279 case NoLinkage: return CXLinkage_NoLinkage;
4280 case InternalLinkage: return CXLinkage_Internal;
4281 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4282 case ExternalLinkage: return CXLinkage_External;
4283 };
4284
4285 return CXLinkage_Invalid;
4286}
4287} // end: extern "C"
4288
4289//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004290// Operations for querying language of a cursor.
4291//===----------------------------------------------------------------------===//
4292
4293static CXLanguageKind getDeclLanguage(const Decl *D) {
4294 switch (D->getKind()) {
4295 default:
4296 break;
4297 case Decl::ImplicitParam:
4298 case Decl::ObjCAtDefsField:
4299 case Decl::ObjCCategory:
4300 case Decl::ObjCCategoryImpl:
4301 case Decl::ObjCClass:
4302 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004303 case Decl::ObjCForwardProtocol:
4304 case Decl::ObjCImplementation:
4305 case Decl::ObjCInterface:
4306 case Decl::ObjCIvar:
4307 case Decl::ObjCMethod:
4308 case Decl::ObjCProperty:
4309 case Decl::ObjCPropertyImpl:
4310 case Decl::ObjCProtocol:
4311 return CXLanguage_ObjC;
4312 case Decl::CXXConstructor:
4313 case Decl::CXXConversion:
4314 case Decl::CXXDestructor:
4315 case Decl::CXXMethod:
4316 case Decl::CXXRecord:
4317 case Decl::ClassTemplate:
4318 case Decl::ClassTemplatePartialSpecialization:
4319 case Decl::ClassTemplateSpecialization:
4320 case Decl::Friend:
4321 case Decl::FriendTemplate:
4322 case Decl::FunctionTemplate:
4323 case Decl::LinkageSpec:
4324 case Decl::Namespace:
4325 case Decl::NamespaceAlias:
4326 case Decl::NonTypeTemplateParm:
4327 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004328 case Decl::TemplateTemplateParm:
4329 case Decl::TemplateTypeParm:
4330 case Decl::UnresolvedUsingTypename:
4331 case Decl::UnresolvedUsingValue:
4332 case Decl::Using:
4333 case Decl::UsingDirective:
4334 case Decl::UsingShadow:
4335 return CXLanguage_CPlusPlus;
4336 }
4337
4338 return CXLanguage_C;
4339}
4340
4341extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004342
4343enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4344 if (clang_isDeclaration(cursor.kind))
4345 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4346 if (D->hasAttr<UnavailableAttr>() ||
4347 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4348 return CXAvailability_Available;
4349
4350 if (D->hasAttr<DeprecatedAttr>())
4351 return CXAvailability_Deprecated;
4352 }
4353
4354 return CXAvailability_Available;
4355}
4356
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004357CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4358 if (clang_isDeclaration(cursor.kind))
4359 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4360
4361 return CXLanguage_Invalid;
4362}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004363
4364CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4365 if (clang_isDeclaration(cursor.kind)) {
4366 if (Decl *D = getCursorDecl(cursor)) {
4367 DeclContext *DC = D->getDeclContext();
4368 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4369 }
4370 }
4371
4372 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4373 if (Decl *D = getCursorDecl(cursor))
4374 return MakeCXCursor(D, getCursorASTUnit(cursor));
4375 }
4376
4377 return clang_getNullCursor();
4378}
4379
4380CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4381 if (clang_isDeclaration(cursor.kind)) {
4382 if (Decl *D = getCursorDecl(cursor)) {
4383 DeclContext *DC = D->getLexicalDeclContext();
4384 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4385 }
4386 }
4387
4388 // FIXME: Note that we can't easily compute the lexical context of a
4389 // statement or expression, so we return nothing.
4390 return clang_getNullCursor();
4391}
4392
Douglas Gregor9f592342010-10-01 20:25:15 +00004393static void CollectOverriddenMethods(DeclContext *Ctx,
4394 ObjCMethodDecl *Method,
4395 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4396 if (!Ctx)
4397 return;
4398
4399 // If we have a class or category implementation, jump straight to the
4400 // interface.
4401 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4402 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4403
4404 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4405 if (!Container)
4406 return;
4407
4408 // Check whether we have a matching method at this level.
4409 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4410 Method->isInstanceMethod()))
4411 if (Method != Overridden) {
4412 // We found an override at this level; there is no need to look
4413 // into other protocols or categories.
4414 Methods.push_back(Overridden);
4415 return;
4416 }
4417
4418 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4419 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4420 PEnd = Protocol->protocol_end();
4421 P != PEnd; ++P)
4422 CollectOverriddenMethods(*P, Method, Methods);
4423 }
4424
4425 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4426 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4427 PEnd = Category->protocol_end();
4428 P != PEnd; ++P)
4429 CollectOverriddenMethods(*P, Method, Methods);
4430 }
4431
4432 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4433 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4434 PEnd = Interface->protocol_end();
4435 P != PEnd; ++P)
4436 CollectOverriddenMethods(*P, Method, Methods);
4437
4438 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4439 Category; Category = Category->getNextClassCategory())
4440 CollectOverriddenMethods(Category, Method, Methods);
4441
4442 // We only look into the superclass if we haven't found anything yet.
4443 if (Methods.empty())
4444 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4445 return CollectOverriddenMethods(Super, Method, Methods);
4446 }
4447}
4448
4449void clang_getOverriddenCursors(CXCursor cursor,
4450 CXCursor **overridden,
4451 unsigned *num_overridden) {
4452 if (overridden)
4453 *overridden = 0;
4454 if (num_overridden)
4455 *num_overridden = 0;
4456 if (!overridden || !num_overridden)
4457 return;
4458
4459 if (!clang_isDeclaration(cursor.kind))
4460 return;
4461
4462 Decl *D = getCursorDecl(cursor);
4463 if (!D)
4464 return;
4465
4466 // Handle C++ member functions.
4467 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4468 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4469 *num_overridden = CXXMethod->size_overridden_methods();
4470 if (!*num_overridden)
4471 return;
4472
4473 *overridden = new CXCursor [*num_overridden];
4474 unsigned I = 0;
4475 for (CXXMethodDecl::method_iterator
4476 M = CXXMethod->begin_overridden_methods(),
4477 MEnd = CXXMethod->end_overridden_methods();
4478 M != MEnd; (void)++M, ++I)
4479 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4480 return;
4481 }
4482
4483 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4484 if (!Method)
4485 return;
4486
4487 // Handle Objective-C methods.
4488 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4489 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4490
4491 if (Methods.empty())
4492 return;
4493
4494 *num_overridden = Methods.size();
4495 *overridden = new CXCursor [Methods.size()];
4496 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4497 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4498}
4499
4500void clang_disposeOverriddenCursors(CXCursor *overridden) {
4501 delete [] overridden;
4502}
4503
Douglas Gregorecdcb882010-10-20 22:00:55 +00004504CXFile clang_getIncludedFile(CXCursor cursor) {
4505 if (cursor.kind != CXCursor_InclusionDirective)
4506 return 0;
4507
4508 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4509 return (void *)ID->getFile();
4510}
4511
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004512} // end: extern "C"
4513
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004514
4515//===----------------------------------------------------------------------===//
4516// C++ AST instrospection.
4517//===----------------------------------------------------------------------===//
4518
4519extern "C" {
4520unsigned clang_CXXMethod_isStatic(CXCursor C) {
4521 if (!clang_isDeclaration(C.kind))
4522 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004523
4524 CXXMethodDecl *Method = 0;
4525 Decl *D = cxcursor::getCursorDecl(C);
4526 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4527 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4528 else
4529 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4530 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004531}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004532
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004533} // end: extern "C"
4534
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004535//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004536// Attribute introspection.
4537//===----------------------------------------------------------------------===//
4538
4539extern "C" {
4540CXType clang_getIBOutletCollectionType(CXCursor C) {
4541 if (C.kind != CXCursor_IBOutletCollectionAttr)
4542 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4543
4544 IBOutletCollectionAttr *A =
4545 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4546
4547 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4548}
4549} // end: extern "C"
4550
4551//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004552// CXString Operations.
4553//===----------------------------------------------------------------------===//
4554
4555extern "C" {
4556const char *clang_getCString(CXString string) {
4557 return string.Spelling;
4558}
4559
4560void clang_disposeString(CXString string) {
4561 if (string.MustFreeString && string.Spelling)
4562 free((void*)string.Spelling);
4563}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004564
Ted Kremenekfb480492010-01-13 21:46:36 +00004565} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004566
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004567namespace clang { namespace cxstring {
4568CXString createCXString(const char *String, bool DupString){
4569 CXString Str;
4570 if (DupString) {
4571 Str.Spelling = strdup(String);
4572 Str.MustFreeString = 1;
4573 } else {
4574 Str.Spelling = String;
4575 Str.MustFreeString = 0;
4576 }
4577 return Str;
4578}
4579
4580CXString createCXString(llvm::StringRef String, bool DupString) {
4581 CXString Result;
4582 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4583 char *Spelling = (char *)malloc(String.size() + 1);
4584 memmove(Spelling, String.data(), String.size());
4585 Spelling[String.size()] = 0;
4586 Result.Spelling = Spelling;
4587 Result.MustFreeString = 1;
4588 } else {
4589 Result.Spelling = String.data();
4590 Result.MustFreeString = 0;
4591 }
4592 return Result;
4593}
4594}}
4595
Ted Kremenek04bb7162010-01-22 22:44:15 +00004596//===----------------------------------------------------------------------===//
4597// Misc. utility functions.
4598//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004599
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004600/// Default to using an 8 MB stack size on "safety" threads.
4601static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004602
4603namespace clang {
4604
4605bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004606 void (*Fn)(void*), void *UserData,
4607 unsigned Size) {
4608 if (!Size)
4609 Size = GetSafetyThreadStackSize();
4610 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004611 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4612 return CRC.RunSafely(Fn, UserData);
4613}
4614
4615unsigned GetSafetyThreadStackSize() {
4616 return SafetyStackThreadSize;
4617}
4618
4619void SetSafetyThreadStackSize(unsigned Value) {
4620 SafetyStackThreadSize = Value;
4621}
4622
4623}
4624
Ted Kremenek04bb7162010-01-22 22:44:15 +00004625extern "C" {
4626
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004627CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004628 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004629}
4630
4631} // end: extern "C"