blob: 633b64ccc5b0bf3ad062ef3ecda2789fe271652b [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);
Ted Kremenek3cb7ba02010-11-15 22:23:24 +0000331 bool VisitDataRecursive(Stmt *S) __attribute__((noinline));
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) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001662 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001663 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001664 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001665 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
Ted Kremenek82f3c502010-11-15 22:23:26 +00001678 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001679 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.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001871 VisitorJob LI = WL.back();
1872 WL.pop_back();
1873
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001874 // Set the Parent field, then back to its old value once we're done.
1875 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1876
1877 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001878 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001879 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001880 if (!D)
1881 continue;
1882
1883 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001884 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001885 return true;
1886
1887 continue;
1888 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001889 case VisitorJob::TypeLocVisitKind: {
1890 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001891 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001892 return true;
1893 continue;
1894 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001895 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001896 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001897 if (!S)
1898 continue;
1899
Ted Kremenekf1107452010-11-12 18:26:56 +00001900 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001901 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1902
1903 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001904 case Stmt::GotoStmtClass: {
1905 GotoStmt *GS = cast<GotoStmt>(S);
1906 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1907 GS->getLabelLoc(), TU))) {
1908 return true;
1909 }
1910 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001911 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001912 // Cases not yet handled by the data-recursion
1913 // algorithm.
1914 case Stmt::OffsetOfExprClass:
1915 case Stmt::SizeOfAlignOfExprClass:
1916 case Stmt::AddrLabelExprClass:
1917 case Stmt::TypesCompatibleExprClass:
1918 case Stmt::VAArgExprClass:
1919 case Stmt::DesignatedInitExprClass:
1920 case Stmt::CXXTypeidExprClass:
1921 case Stmt::CXXUuidofExprClass:
1922 case Stmt::CXXScalarValueInitExprClass:
1923 case Stmt::CXXPseudoDestructorExprClass:
1924 case Stmt::UnaryTypeTraitExprClass:
1925 case Stmt::DependentScopeDeclRefExprClass:
1926 case Stmt::CXXUnresolvedConstructExprClass:
1927 case Stmt::CXXDependentScopeMemberExprClass:
1928 if (Visit(Cursor))
1929 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001930 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001931 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001932 if (!IsInRegionOfInterest(Cursor))
1933 continue;
1934 switch (Visitor(Cursor, Parent, ClientData)) {
1935 case CXChildVisit_Break:
1936 return true;
1937 case CXChildVisit_Continue:
1938 break;
1939 case CXChildVisit_Recurse:
1940 EnqueueWorkList(WL, S);
1941 break;
1942 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001943 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001944 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001945 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001946 }
1947 case VisitorJob::MemberExprPartsKind: {
1948 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001949 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001950
1951 // Visit the nested-name-specifier
1952 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1953 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1954 return true;
1955
1956 // Visit the declaration name.
1957 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1958 return true;
1959
1960 // Visit the explicitly-specified template arguments, if any.
1961 if (M->hasExplicitTemplateArgs()) {
1962 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1963 *ArgEnd = Arg + M->getNumTemplateArgs();
1964 Arg != ArgEnd; ++Arg) {
1965 if (VisitTemplateArgumentLoc(*Arg))
1966 return true;
1967 }
1968 }
1969 continue;
1970 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001971 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001972 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001973 // Visit nested-name-specifier, if present.
1974 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
1975 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
1976 return true;
1977 // Visit declaration name.
1978 if (VisitDeclarationNameInfo(DR->getNameInfo()))
1979 return true;
1980 // Visit explicitly-specified template arguments.
1981 if (DR->hasExplicitTemplateArgs()) {
1982 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
1983 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1984 *ArgEnd = Arg + Args.NumTemplateArgs;
1985 Arg != ArgEnd; ++Arg)
1986 if (VisitTemplateArgumentLoc(*Arg))
1987 return true;
1988 }
1989 continue;
1990 }
Ted Kremenek60458782010-11-12 21:34:16 +00001991 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001992 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00001993 // Visit the nested-name-specifier.
1994 if (NestedNameSpecifier *Qualifier = O->getQualifier())
1995 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
1996 return true;
1997 // Visit the declaration name.
1998 if (VisitDeclarationNameInfo(O->getNameInfo()))
1999 return true;
2000 // Visit the overloaded declaration reference.
2001 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2002 return true;
2003 // Visit the explicitly-specified template arguments.
2004 if (const ExplicitTemplateArgumentList *ArgList
2005 = O->getOptionalExplicitTemplateArgs()) {
2006 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2007 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2008 Arg != ArgEnd; ++Arg) {
2009 if (VisitTemplateArgumentLoc(*Arg))
2010 return true;
2011 }
2012 }
2013 continue;
2014 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002015 }
2016 }
2017 return false;
2018}
2019
2020bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2021 VisitorWorkList WL;
2022 EnqueueWorkList(WL, S);
2023 return RunVisitorWorkList(WL);
2024}
2025
2026//===----------------------------------------------------------------------===//
2027// Misc. API hooks.
2028//===----------------------------------------------------------------------===//
2029
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002030static llvm::sys::Mutex EnableMultithreadingMutex;
2031static bool EnabledMultithreading;
2032
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002033extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002034CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2035 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002036 // Disable pretty stack trace functionality, which will otherwise be a very
2037 // poor citizen of the world and set up all sorts of signal handlers.
2038 llvm::DisablePrettyStackTrace = true;
2039
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002040 // We use crash recovery to make some of our APIs more reliable, implicitly
2041 // enable it.
2042 llvm::CrashRecoveryContext::Enable();
2043
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002044 // Enable support for multithreading in LLVM.
2045 {
2046 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2047 if (!EnabledMultithreading) {
2048 llvm::llvm_start_multithreaded();
2049 EnabledMultithreading = true;
2050 }
2051 }
2052
Douglas Gregora030b7c2010-01-22 20:35:53 +00002053 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002054 if (excludeDeclarationsFromPCH)
2055 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002056 if (displayDiagnostics)
2057 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002058 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002059}
2060
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002061void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002062 if (CIdx)
2063 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002064}
2065
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002066CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002067 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002068 if (!CIdx)
2069 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002070
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002071 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002072 FileSystemOptions FileSystemOpts;
2073 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002074
Douglas Gregor28019772010-04-05 23:52:57 +00002075 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002076 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002077 CXXIdx->getOnlyLocalDecls(),
2078 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002079}
2080
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002081unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002082 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002083 CXTranslationUnit_CacheCompletionResults |
2084 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002085}
2086
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002087CXTranslationUnit
2088clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2089 const char *source_filename,
2090 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002091 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002092 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002093 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002094 return clang_parseTranslationUnit(CIdx, source_filename,
2095 command_line_args, num_command_line_args,
2096 unsaved_files, num_unsaved_files,
2097 CXTranslationUnit_DetailedPreprocessingRecord);
2098}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002099
2100struct ParseTranslationUnitInfo {
2101 CXIndex CIdx;
2102 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002103 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002104 int num_command_line_args;
2105 struct CXUnsavedFile *unsaved_files;
2106 unsigned num_unsaved_files;
2107 unsigned options;
2108 CXTranslationUnit result;
2109};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002110static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002111 ParseTranslationUnitInfo *PTUI =
2112 static_cast<ParseTranslationUnitInfo*>(UserData);
2113 CXIndex CIdx = PTUI->CIdx;
2114 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002115 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002116 int num_command_line_args = PTUI->num_command_line_args;
2117 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2118 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2119 unsigned options = PTUI->options;
2120 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002121
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002122 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002123 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002124
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002125 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2126
Douglas Gregor44c181a2010-07-23 00:33:23 +00002127 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002128 bool CompleteTranslationUnit
2129 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002130 bool CacheCodeCompetionResults
2131 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002132 bool CXXPrecompilePreamble
2133 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2134 bool CXXChainedPCH
2135 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002136
Douglas Gregor5352ac02010-01-28 00:27:43 +00002137 // Configure the diagnostics.
2138 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002139 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2140 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002141
Douglas Gregor4db64a42010-01-23 00:14:00 +00002142 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2143 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002144 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002145 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002146 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002147 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2148 Buffer));
2149 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002150
Douglas Gregorb10daed2010-10-11 16:52:23 +00002151 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002152
Ted Kremenek139ba862009-10-22 00:03:57 +00002153 // The 'source_filename' argument is optional. If the caller does not
2154 // specify it then it is assumed that the source file is specified
2155 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002156 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002157 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002158
2159 // Since the Clang C library is primarily used by batch tools dealing with
2160 // (often very broken) source code, where spell-checking can have a
2161 // significant negative impact on performance (particularly when
2162 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002163 // Only do this if we haven't found a spell-checking-related argument.
2164 bool FoundSpellCheckingArgument = false;
2165 for (int I = 0; I != num_command_line_args; ++I) {
2166 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2167 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2168 FoundSpellCheckingArgument = true;
2169 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002170 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002171 }
2172 if (!FoundSpellCheckingArgument)
2173 Args.push_back("-fno-spell-checking");
2174
2175 Args.insert(Args.end(), command_line_args,
2176 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002177
Douglas Gregor44c181a2010-07-23 00:33:23 +00002178 // Do we need the detailed preprocessing record?
2179 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002180 Args.push_back("-Xclang");
2181 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002182 }
2183
Douglas Gregorb10daed2010-10-11 16:52:23 +00002184 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002185 llvm::OwningPtr<ASTUnit> Unit(
2186 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2187 Diags,
2188 CXXIdx->getClangResourcesPath(),
2189 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002190 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002191 RemappedFiles.data(),
2192 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002193 PrecompilePreamble,
2194 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002195 CacheCodeCompetionResults,
2196 CXXPrecompilePreamble,
2197 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002198
Douglas Gregorb10daed2010-10-11 16:52:23 +00002199 if (NumErrors != Diags->getNumErrors()) {
2200 // Make sure to check that 'Unit' is non-NULL.
2201 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2202 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2203 DEnd = Unit->stored_diag_end();
2204 D != DEnd; ++D) {
2205 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2206 CXString Msg = clang_formatDiagnostic(&Diag,
2207 clang_defaultDiagnosticDisplayOptions());
2208 fprintf(stderr, "%s\n", clang_getCString(Msg));
2209 clang_disposeString(Msg);
2210 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002211#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002212 // On Windows, force a flush, since there may be multiple copies of
2213 // stderr and stdout in the file system, all with different buffers
2214 // but writing to the same device.
2215 fflush(stderr);
2216#endif
2217 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002218 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002219
Douglas Gregorb10daed2010-10-11 16:52:23 +00002220 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002221}
2222CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2223 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002224 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002225 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002226 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002227 unsigned num_unsaved_files,
2228 unsigned options) {
2229 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002230 num_command_line_args, unsaved_files,
2231 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002232 llvm::CrashRecoveryContext CRC;
2233
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002234 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002235 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2236 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2237 fprintf(stderr, " 'command_line_args' : [");
2238 for (int i = 0; i != num_command_line_args; ++i) {
2239 if (i)
2240 fprintf(stderr, ", ");
2241 fprintf(stderr, "'%s'", command_line_args[i]);
2242 }
2243 fprintf(stderr, "],\n");
2244 fprintf(stderr, " 'unsaved_files' : [");
2245 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2246 if (i)
2247 fprintf(stderr, ", ");
2248 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2249 unsaved_files[i].Length);
2250 }
2251 fprintf(stderr, "],\n");
2252 fprintf(stderr, " 'options' : %d,\n", options);
2253 fprintf(stderr, "}\n");
2254
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002255 return 0;
2256 }
2257
2258 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002259}
2260
Douglas Gregor19998442010-08-13 15:35:05 +00002261unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2262 return CXSaveTranslationUnit_None;
2263}
2264
2265int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2266 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002267 if (!TU)
2268 return 1;
2269
2270 return static_cast<ASTUnit *>(TU)->Save(FileName);
2271}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002272
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002273void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002274 if (CTUnit) {
2275 // If the translation unit has been marked as unsafe to free, just discard
2276 // it.
2277 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2278 return;
2279
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002280 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002281 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002282}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002283
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002284unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2285 return CXReparse_None;
2286}
2287
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002288struct ReparseTranslationUnitInfo {
2289 CXTranslationUnit TU;
2290 unsigned num_unsaved_files;
2291 struct CXUnsavedFile *unsaved_files;
2292 unsigned options;
2293 int result;
2294};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002295
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002296static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002297 ReparseTranslationUnitInfo *RTUI =
2298 static_cast<ReparseTranslationUnitInfo*>(UserData);
2299 CXTranslationUnit TU = RTUI->TU;
2300 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2301 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2302 unsigned options = RTUI->options;
2303 (void) options;
2304 RTUI->result = 1;
2305
Douglas Gregorabc563f2010-07-19 21:46:24 +00002306 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002307 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002308
2309 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2310 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002311
2312 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2313 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2314 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2315 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002316 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002317 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2318 Buffer));
2319 }
2320
Douglas Gregor593b0c12010-09-23 18:47:53 +00002321 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2322 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002323}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002324
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002325int clang_reparseTranslationUnit(CXTranslationUnit TU,
2326 unsigned num_unsaved_files,
2327 struct CXUnsavedFile *unsaved_files,
2328 unsigned options) {
2329 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2330 options, 0 };
2331 llvm::CrashRecoveryContext CRC;
2332
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002333 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002334 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002335 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2336 return 1;
2337 }
2338
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002339
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002340 return RTUI.result;
2341}
2342
Douglas Gregordf95a132010-08-09 20:45:32 +00002343
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002344CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002345 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002346 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002347
Steve Naroff77accc12009-09-03 18:19:54 +00002348 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002349 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002350}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002351
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002352CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002353 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002354 return Result;
2355}
2356
Ted Kremenekfb480492010-01-13 21:46:36 +00002357} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002358
Ted Kremenekfb480492010-01-13 21:46:36 +00002359//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002360// CXSourceLocation and CXSourceRange Operations.
2361//===----------------------------------------------------------------------===//
2362
Douglas Gregorb9790342010-01-22 21:44:22 +00002363extern "C" {
2364CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002365 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002366 return Result;
2367}
2368
2369unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002370 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2371 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2372 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002373}
2374
2375CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2376 CXFile file,
2377 unsigned line,
2378 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002379 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002380 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002381
Douglas Gregorb9790342010-01-22 21:44:22 +00002382 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2383 SourceLocation SLoc
2384 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002385 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002386 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002387 if (SLoc.isInvalid()) return clang_getNullLocation();
2388
2389 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2390}
2391
2392CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2393 CXFile file,
2394 unsigned offset) {
2395 if (!tu || !file)
2396 return clang_getNullLocation();
2397
2398 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2399 SourceLocation Start
2400 = CXXUnit->getSourceManager().getLocation(
2401 static_cast<const FileEntry *>(file),
2402 1, 1);
2403 if (Start.isInvalid()) return clang_getNullLocation();
2404
2405 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2406
2407 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002408
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002409 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002410}
2411
Douglas Gregor5352ac02010-01-28 00:27:43 +00002412CXSourceRange clang_getNullRange() {
2413 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2414 return Result;
2415}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002416
Douglas Gregor5352ac02010-01-28 00:27:43 +00002417CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2418 if (begin.ptr_data[0] != end.ptr_data[0] ||
2419 begin.ptr_data[1] != end.ptr_data[1])
2420 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002421
2422 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002423 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002424 return Result;
2425}
2426
Douglas Gregor46766dc2010-01-26 19:19:08 +00002427void clang_getInstantiationLocation(CXSourceLocation location,
2428 CXFile *file,
2429 unsigned *line,
2430 unsigned *column,
2431 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002432 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2433
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002434 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002435 if (file)
2436 *file = 0;
2437 if (line)
2438 *line = 0;
2439 if (column)
2440 *column = 0;
2441 if (offset)
2442 *offset = 0;
2443 return;
2444 }
2445
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002446 const SourceManager &SM =
2447 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002448 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002449
2450 if (file)
2451 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2452 if (line)
2453 *line = SM.getInstantiationLineNumber(InstLoc);
2454 if (column)
2455 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002456 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002457 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002458}
2459
Douglas Gregora9b06d42010-11-09 06:24:54 +00002460void clang_getSpellingLocation(CXSourceLocation location,
2461 CXFile *file,
2462 unsigned *line,
2463 unsigned *column,
2464 unsigned *offset) {
2465 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2466
2467 if (!location.ptr_data[0] || Loc.isInvalid()) {
2468 if (file)
2469 *file = 0;
2470 if (line)
2471 *line = 0;
2472 if (column)
2473 *column = 0;
2474 if (offset)
2475 *offset = 0;
2476 return;
2477 }
2478
2479 const SourceManager &SM =
2480 *static_cast<const SourceManager*>(location.ptr_data[0]);
2481 SourceLocation SpellLoc = Loc;
2482 if (SpellLoc.isMacroID()) {
2483 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2484 if (SimpleSpellingLoc.isFileID() &&
2485 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2486 SpellLoc = SimpleSpellingLoc;
2487 else
2488 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2489 }
2490
2491 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2492 FileID FID = LocInfo.first;
2493 unsigned FileOffset = LocInfo.second;
2494
2495 if (file)
2496 *file = (void *)SM.getFileEntryForID(FID);
2497 if (line)
2498 *line = SM.getLineNumber(FID, FileOffset);
2499 if (column)
2500 *column = SM.getColumnNumber(FID, FileOffset);
2501 if (offset)
2502 *offset = FileOffset;
2503}
2504
Douglas Gregor1db19de2010-01-19 21:36:55 +00002505CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002506 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002507 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002508 return Result;
2509}
2510
2511CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002512 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002513 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002514 return Result;
2515}
2516
Douglas Gregorb9790342010-01-22 21:44:22 +00002517} // end: extern "C"
2518
Douglas Gregor1db19de2010-01-19 21:36:55 +00002519//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002520// CXFile Operations.
2521//===----------------------------------------------------------------------===//
2522
2523extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002524CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002525 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002526 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002527
Steve Naroff88145032009-10-27 14:35:18 +00002528 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002529 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002530}
2531
2532time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002533 if (!SFile)
2534 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002535
Steve Naroff88145032009-10-27 14:35:18 +00002536 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2537 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002538}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002539
Douglas Gregorb9790342010-01-22 21:44:22 +00002540CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2541 if (!tu)
2542 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002543
Douglas Gregorb9790342010-01-22 21:44:22 +00002544 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002545
Douglas Gregorb9790342010-01-22 21:44:22 +00002546 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002547 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2548 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002549 return const_cast<FileEntry *>(File);
2550}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002551
Ted Kremenekfb480492010-01-13 21:46:36 +00002552} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002553
Ted Kremenekfb480492010-01-13 21:46:36 +00002554//===----------------------------------------------------------------------===//
2555// CXCursor Operations.
2556//===----------------------------------------------------------------------===//
2557
Ted Kremenekfb480492010-01-13 21:46:36 +00002558static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002559 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2560 return getDeclFromExpr(CE->getSubExpr());
2561
Ted Kremenekfb480492010-01-13 21:46:36 +00002562 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2563 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002564 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2565 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002566 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2567 return ME->getMemberDecl();
2568 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2569 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002570 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2571 return PRE->getProperty();
2572
Ted Kremenekfb480492010-01-13 21:46:36 +00002573 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2574 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002575 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2576 if (!CE->isElidable())
2577 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002578 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2579 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002580
Douglas Gregordb1314e2010-10-01 21:11:22 +00002581 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2582 return PE->getProtocol();
2583
Ted Kremenekfb480492010-01-13 21:46:36 +00002584 return 0;
2585}
2586
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002587static SourceLocation getLocationFromExpr(Expr *E) {
2588 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2589 return /*FIXME:*/Msg->getLeftLoc();
2590 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2591 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002592 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2593 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002594 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2595 return Member->getMemberLoc();
2596 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2597 return Ivar->getLocation();
2598 return E->getLocStart();
2599}
2600
Ted Kremenekfb480492010-01-13 21:46:36 +00002601extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002602
2603unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002604 CXCursorVisitor visitor,
2605 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002606 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002607
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002608 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2609 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002610 return CursorVis.VisitChildren(parent);
2611}
2612
David Chisnall3387c652010-11-03 14:12:26 +00002613#ifndef __has_feature
2614#define __has_feature(x) 0
2615#endif
2616#if __has_feature(blocks)
2617typedef enum CXChildVisitResult
2618 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2619
2620static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2621 CXClientData client_data) {
2622 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2623 return block(cursor, parent);
2624}
2625#else
2626// If we are compiled with a compiler that doesn't have native blocks support,
2627// define and call the block manually, so the
2628typedef struct _CXChildVisitResult
2629{
2630 void *isa;
2631 int flags;
2632 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002633 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2634 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002635} *CXCursorVisitorBlock;
2636
2637static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2638 CXClientData client_data) {
2639 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2640 return block->invoke(block, cursor, parent);
2641}
2642#endif
2643
2644
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002645unsigned clang_visitChildrenWithBlock(CXCursor parent,
2646 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002647 return clang_visitChildren(parent, visitWithBlock, block);
2648}
2649
Douglas Gregor78205d42010-01-20 21:45:58 +00002650static CXString getDeclSpelling(Decl *D) {
2651 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2652 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002653 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002654
Douglas Gregor78205d42010-01-20 21:45:58 +00002655 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002656 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002657
Douglas Gregor78205d42010-01-20 21:45:58 +00002658 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2659 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2660 // and returns different names. NamedDecl returns the class name and
2661 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002662 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002663
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002664 if (isa<UsingDirectiveDecl>(D))
2665 return createCXString("");
2666
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002667 llvm::SmallString<1024> S;
2668 llvm::raw_svector_ostream os(S);
2669 ND->printName(os);
2670
2671 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002672}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002673
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002674CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002675 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002676 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002677
Steve Narofff334b4e2009-09-02 18:26:48 +00002678 if (clang_isReference(C.kind)) {
2679 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002680 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002681 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002682 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002683 }
2684 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002685 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002686 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002687 }
2688 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002689 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002690 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002691 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002692 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002693 case CXCursor_CXXBaseSpecifier: {
2694 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2695 return createCXString(B->getType().getAsString());
2696 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002697 case CXCursor_TypeRef: {
2698 TypeDecl *Type = getCursorTypeRef(C).first;
2699 assert(Type && "Missing type decl");
2700
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002701 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2702 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002703 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002704 case CXCursor_TemplateRef: {
2705 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002706 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002707
2708 return createCXString(Template->getNameAsString());
2709 }
Douglas Gregor69319002010-08-31 23:48:11 +00002710
2711 case CXCursor_NamespaceRef: {
2712 NamedDecl *NS = getCursorNamespaceRef(C).first;
2713 assert(NS && "Missing namespace decl");
2714
2715 return createCXString(NS->getNameAsString());
2716 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002717
Douglas Gregora67e03f2010-09-09 21:42:20 +00002718 case CXCursor_MemberRef: {
2719 FieldDecl *Field = getCursorMemberRef(C).first;
2720 assert(Field && "Missing member decl");
2721
2722 return createCXString(Field->getNameAsString());
2723 }
2724
Douglas Gregor36897b02010-09-10 00:22:18 +00002725 case CXCursor_LabelRef: {
2726 LabelStmt *Label = getCursorLabelRef(C).first;
2727 assert(Label && "Missing label");
2728
2729 return createCXString(Label->getID()->getName());
2730 }
2731
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002732 case CXCursor_OverloadedDeclRef: {
2733 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2734 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2735 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2736 return createCXString(ND->getNameAsString());
2737 return createCXString("");
2738 }
2739 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2740 return createCXString(E->getName().getAsString());
2741 OverloadedTemplateStorage *Ovl
2742 = Storage.get<OverloadedTemplateStorage*>();
2743 if (Ovl->size() == 0)
2744 return createCXString("");
2745 return createCXString((*Ovl->begin())->getNameAsString());
2746 }
2747
Daniel Dunbaracca7252009-11-30 20:42:49 +00002748 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002749 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002750 }
2751 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002752
2753 if (clang_isExpression(C.kind)) {
2754 Decl *D = getDeclFromExpr(getCursorExpr(C));
2755 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002756 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002757 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002758 }
2759
Douglas Gregor36897b02010-09-10 00:22:18 +00002760 if (clang_isStatement(C.kind)) {
2761 Stmt *S = getCursorStmt(C);
2762 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2763 return createCXString(Label->getID()->getName());
2764
2765 return createCXString("");
2766 }
2767
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002768 if (C.kind == CXCursor_MacroInstantiation)
2769 return createCXString(getCursorMacroInstantiation(C)->getName()
2770 ->getNameStart());
2771
Douglas Gregor572feb22010-03-18 18:04:21 +00002772 if (C.kind == CXCursor_MacroDefinition)
2773 return createCXString(getCursorMacroDefinition(C)->getName()
2774 ->getNameStart());
2775
Douglas Gregorecdcb882010-10-20 22:00:55 +00002776 if (C.kind == CXCursor_InclusionDirective)
2777 return createCXString(getCursorInclusionDirective(C)->getFileName());
2778
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002779 if (clang_isDeclaration(C.kind))
2780 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002781
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002782 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002783}
2784
Douglas Gregor358559d2010-10-02 22:49:11 +00002785CXString clang_getCursorDisplayName(CXCursor C) {
2786 if (!clang_isDeclaration(C.kind))
2787 return clang_getCursorSpelling(C);
2788
2789 Decl *D = getCursorDecl(C);
2790 if (!D)
2791 return createCXString("");
2792
2793 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2794 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2795 D = FunTmpl->getTemplatedDecl();
2796
2797 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2798 llvm::SmallString<64> Str;
2799 llvm::raw_svector_ostream OS(Str);
2800 OS << Function->getNameAsString();
2801 if (Function->getPrimaryTemplate())
2802 OS << "<>";
2803 OS << "(";
2804 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2805 if (I)
2806 OS << ", ";
2807 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2808 }
2809
2810 if (Function->isVariadic()) {
2811 if (Function->getNumParams())
2812 OS << ", ";
2813 OS << "...";
2814 }
2815 OS << ")";
2816 return createCXString(OS.str());
2817 }
2818
2819 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2820 llvm::SmallString<64> Str;
2821 llvm::raw_svector_ostream OS(Str);
2822 OS << ClassTemplate->getNameAsString();
2823 OS << "<";
2824 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2825 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2826 if (I)
2827 OS << ", ";
2828
2829 NamedDecl *Param = Params->getParam(I);
2830 if (Param->getIdentifier()) {
2831 OS << Param->getIdentifier()->getName();
2832 continue;
2833 }
2834
2835 // There is no parameter name, which makes this tricky. Try to come up
2836 // with something useful that isn't too long.
2837 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2838 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2839 else if (NonTypeTemplateParmDecl *NTTP
2840 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2841 OS << NTTP->getType().getAsString(Policy);
2842 else
2843 OS << "template<...> class";
2844 }
2845
2846 OS << ">";
2847 return createCXString(OS.str());
2848 }
2849
2850 if (ClassTemplateSpecializationDecl *ClassSpec
2851 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2852 // If the type was explicitly written, use that.
2853 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2854 return createCXString(TSInfo->getType().getAsString(Policy));
2855
2856 llvm::SmallString<64> Str;
2857 llvm::raw_svector_ostream OS(Str);
2858 OS << ClassSpec->getNameAsString();
2859 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002860 ClassSpec->getTemplateArgs().data(),
2861 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002862 Policy);
2863 return createCXString(OS.str());
2864 }
2865
2866 return clang_getCursorSpelling(C);
2867}
2868
Ted Kremeneke68fff62010-02-17 00:41:32 +00002869CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002870 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002871 case CXCursor_FunctionDecl:
2872 return createCXString("FunctionDecl");
2873 case CXCursor_TypedefDecl:
2874 return createCXString("TypedefDecl");
2875 case CXCursor_EnumDecl:
2876 return createCXString("EnumDecl");
2877 case CXCursor_EnumConstantDecl:
2878 return createCXString("EnumConstantDecl");
2879 case CXCursor_StructDecl:
2880 return createCXString("StructDecl");
2881 case CXCursor_UnionDecl:
2882 return createCXString("UnionDecl");
2883 case CXCursor_ClassDecl:
2884 return createCXString("ClassDecl");
2885 case CXCursor_FieldDecl:
2886 return createCXString("FieldDecl");
2887 case CXCursor_VarDecl:
2888 return createCXString("VarDecl");
2889 case CXCursor_ParmDecl:
2890 return createCXString("ParmDecl");
2891 case CXCursor_ObjCInterfaceDecl:
2892 return createCXString("ObjCInterfaceDecl");
2893 case CXCursor_ObjCCategoryDecl:
2894 return createCXString("ObjCCategoryDecl");
2895 case CXCursor_ObjCProtocolDecl:
2896 return createCXString("ObjCProtocolDecl");
2897 case CXCursor_ObjCPropertyDecl:
2898 return createCXString("ObjCPropertyDecl");
2899 case CXCursor_ObjCIvarDecl:
2900 return createCXString("ObjCIvarDecl");
2901 case CXCursor_ObjCInstanceMethodDecl:
2902 return createCXString("ObjCInstanceMethodDecl");
2903 case CXCursor_ObjCClassMethodDecl:
2904 return createCXString("ObjCClassMethodDecl");
2905 case CXCursor_ObjCImplementationDecl:
2906 return createCXString("ObjCImplementationDecl");
2907 case CXCursor_ObjCCategoryImplDecl:
2908 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002909 case CXCursor_CXXMethod:
2910 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002911 case CXCursor_UnexposedDecl:
2912 return createCXString("UnexposedDecl");
2913 case CXCursor_ObjCSuperClassRef:
2914 return createCXString("ObjCSuperClassRef");
2915 case CXCursor_ObjCProtocolRef:
2916 return createCXString("ObjCProtocolRef");
2917 case CXCursor_ObjCClassRef:
2918 return createCXString("ObjCClassRef");
2919 case CXCursor_TypeRef:
2920 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002921 case CXCursor_TemplateRef:
2922 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002923 case CXCursor_NamespaceRef:
2924 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002925 case CXCursor_MemberRef:
2926 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002927 case CXCursor_LabelRef:
2928 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002929 case CXCursor_OverloadedDeclRef:
2930 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002931 case CXCursor_UnexposedExpr:
2932 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002933 case CXCursor_BlockExpr:
2934 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002935 case CXCursor_DeclRefExpr:
2936 return createCXString("DeclRefExpr");
2937 case CXCursor_MemberRefExpr:
2938 return createCXString("MemberRefExpr");
2939 case CXCursor_CallExpr:
2940 return createCXString("CallExpr");
2941 case CXCursor_ObjCMessageExpr:
2942 return createCXString("ObjCMessageExpr");
2943 case CXCursor_UnexposedStmt:
2944 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002945 case CXCursor_LabelStmt:
2946 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002947 case CXCursor_InvalidFile:
2948 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002949 case CXCursor_InvalidCode:
2950 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002951 case CXCursor_NoDeclFound:
2952 return createCXString("NoDeclFound");
2953 case CXCursor_NotImplemented:
2954 return createCXString("NotImplemented");
2955 case CXCursor_TranslationUnit:
2956 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002957 case CXCursor_UnexposedAttr:
2958 return createCXString("UnexposedAttr");
2959 case CXCursor_IBActionAttr:
2960 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002961 case CXCursor_IBOutletAttr:
2962 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002963 case CXCursor_IBOutletCollectionAttr:
2964 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002965 case CXCursor_PreprocessingDirective:
2966 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002967 case CXCursor_MacroDefinition:
2968 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002969 case CXCursor_MacroInstantiation:
2970 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002971 case CXCursor_InclusionDirective:
2972 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002973 case CXCursor_Namespace:
2974 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002975 case CXCursor_LinkageSpec:
2976 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002977 case CXCursor_CXXBaseSpecifier:
2978 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002979 case CXCursor_Constructor:
2980 return createCXString("CXXConstructor");
2981 case CXCursor_Destructor:
2982 return createCXString("CXXDestructor");
2983 case CXCursor_ConversionFunction:
2984 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002985 case CXCursor_TemplateTypeParameter:
2986 return createCXString("TemplateTypeParameter");
2987 case CXCursor_NonTypeTemplateParameter:
2988 return createCXString("NonTypeTemplateParameter");
2989 case CXCursor_TemplateTemplateParameter:
2990 return createCXString("TemplateTemplateParameter");
2991 case CXCursor_FunctionTemplate:
2992 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002993 case CXCursor_ClassTemplate:
2994 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002995 case CXCursor_ClassTemplatePartialSpecialization:
2996 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002997 case CXCursor_NamespaceAlias:
2998 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002999 case CXCursor_UsingDirective:
3000 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003001 case CXCursor_UsingDeclaration:
3002 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003003 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003004
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003005 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003006 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003007}
Steve Naroff89922f82009-08-31 00:59:03 +00003008
Ted Kremeneke68fff62010-02-17 00:41:32 +00003009enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3010 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003011 CXClientData client_data) {
3012 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003013
3014 // If our current best cursor is the construction of a temporary object,
3015 // don't replace that cursor with a type reference, because we want
3016 // clang_getCursor() to point at the constructor.
3017 if (clang_isExpression(BestCursor->kind) &&
3018 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3019 cursor.kind == CXCursor_TypeRef)
3020 return CXChildVisit_Recurse;
3021
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003022 *BestCursor = cursor;
3023 return CXChildVisit_Recurse;
3024}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003025
Douglas Gregorb9790342010-01-22 21:44:22 +00003026CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3027 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003028 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003029
Douglas Gregorb9790342010-01-22 21:44:22 +00003030 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003031 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3032
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003033 // Translate the given source location to make it point at the beginning of
3034 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003035 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003036
3037 // Guard against an invalid SourceLocation, or we may assert in one
3038 // of the following calls.
3039 if (SLoc.isInvalid())
3040 return clang_getNullCursor();
3041
Douglas Gregor40749ee2010-11-03 00:35:38 +00003042 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003043 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3044 CXXUnit->getASTContext().getLangOptions());
3045
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003046 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3047 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003048 // FIXME: Would be great to have a "hint" cursor, then walk from that
3049 // hint cursor upward until we find a cursor whose source range encloses
3050 // the region of interest, rather than starting from the translation unit.
3051 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003052 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003053 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003054 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003055 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003056
3057 if (Logging) {
3058 CXFile SearchFile;
3059 unsigned SearchLine, SearchColumn;
3060 CXFile ResultFile;
3061 unsigned ResultLine, ResultColumn;
3062 CXString SearchFileName, ResultFileName, KindSpelling;
3063 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3064
3065 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3066 0);
3067 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3068 &ResultColumn, 0);
3069 SearchFileName = clang_getFileName(SearchFile);
3070 ResultFileName = clang_getFileName(ResultFile);
3071 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3072 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3073 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3074 clang_getCString(KindSpelling),
3075 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3076 clang_disposeString(SearchFileName);
3077 clang_disposeString(ResultFileName);
3078 clang_disposeString(KindSpelling);
3079 }
3080
Ted Kremeneke68fff62010-02-17 00:41:32 +00003081 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003082}
3083
Ted Kremenek73885552009-11-17 19:28:59 +00003084CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003085 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003086}
3087
3088unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003089 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003090}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003091
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003092unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003093 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3094}
3095
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003096unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003097 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3098}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003099
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003100unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003101 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3102}
3103
Douglas Gregor97b98722010-01-19 23:20:36 +00003104unsigned clang_isExpression(enum CXCursorKind K) {
3105 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3106}
3107
3108unsigned clang_isStatement(enum CXCursorKind K) {
3109 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3110}
3111
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003112unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3113 return K == CXCursor_TranslationUnit;
3114}
3115
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003116unsigned clang_isPreprocessing(enum CXCursorKind K) {
3117 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3118}
3119
Ted Kremenekad6eff62010-03-08 21:17:29 +00003120unsigned clang_isUnexposed(enum CXCursorKind K) {
3121 switch (K) {
3122 case CXCursor_UnexposedDecl:
3123 case CXCursor_UnexposedExpr:
3124 case CXCursor_UnexposedStmt:
3125 case CXCursor_UnexposedAttr:
3126 return true;
3127 default:
3128 return false;
3129 }
3130}
3131
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003132CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003133 return C.kind;
3134}
3135
Douglas Gregor98258af2010-01-18 22:46:11 +00003136CXSourceLocation clang_getCursorLocation(CXCursor C) {
3137 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003138 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003139 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003140 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3141 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003142 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003143 }
3144
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003145 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003146 std::pair<ObjCProtocolDecl *, SourceLocation> P
3147 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003148 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003149 }
3150
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003151 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003152 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3153 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003154 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003155 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003156
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003157 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003158 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003159 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003160 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003161
3162 case CXCursor_TemplateRef: {
3163 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3164 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3165 }
3166
Douglas Gregor69319002010-08-31 23:48:11 +00003167 case CXCursor_NamespaceRef: {
3168 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3169 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3170 }
3171
Douglas Gregora67e03f2010-09-09 21:42:20 +00003172 case CXCursor_MemberRef: {
3173 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3174 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3175 }
3176
Ted Kremenek3064ef92010-08-27 21:34:58 +00003177 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003178 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3179 if (!BaseSpec)
3180 return clang_getNullLocation();
3181
3182 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3183 return cxloc::translateSourceLocation(getCursorContext(C),
3184 TSInfo->getTypeLoc().getBeginLoc());
3185
3186 return cxloc::translateSourceLocation(getCursorContext(C),
3187 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003188 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003189
Douglas Gregor36897b02010-09-10 00:22:18 +00003190 case CXCursor_LabelRef: {
3191 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3192 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3193 }
3194
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003195 case CXCursor_OverloadedDeclRef:
3196 return cxloc::translateSourceLocation(getCursorContext(C),
3197 getCursorOverloadedDeclRef(C).second);
3198
Douglas Gregorf46034a2010-01-18 23:41:10 +00003199 default:
3200 // FIXME: Need a way to enumerate all non-reference cases.
3201 llvm_unreachable("Missed a reference kind");
3202 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003203 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003204
3205 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003206 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003207 getLocationFromExpr(getCursorExpr(C)));
3208
Douglas Gregor36897b02010-09-10 00:22:18 +00003209 if (clang_isStatement(C.kind))
3210 return cxloc::translateSourceLocation(getCursorContext(C),
3211 getCursorStmt(C)->getLocStart());
3212
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003213 if (C.kind == CXCursor_PreprocessingDirective) {
3214 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3215 return cxloc::translateSourceLocation(getCursorContext(C), L);
3216 }
Douglas Gregor48072312010-03-18 15:23:44 +00003217
3218 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003219 SourceLocation L
3220 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003221 return cxloc::translateSourceLocation(getCursorContext(C), L);
3222 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003223
3224 if (C.kind == CXCursor_MacroDefinition) {
3225 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3226 return cxloc::translateSourceLocation(getCursorContext(C), L);
3227 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003228
3229 if (C.kind == CXCursor_InclusionDirective) {
3230 SourceLocation L
3231 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3232 return cxloc::translateSourceLocation(getCursorContext(C), L);
3233 }
3234
Ted Kremenek9a700d22010-05-12 06:16:13 +00003235 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003236 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003237
Douglas Gregorf46034a2010-01-18 23:41:10 +00003238 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003239 SourceLocation Loc = D->getLocation();
3240 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3241 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003242 // FIXME: Multiple variables declared in a single declaration
3243 // currently lack the information needed to correctly determine their
3244 // ranges when accounting for the type-specifier. We use context
3245 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3246 // and if so, whether it is the first decl.
3247 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3248 if (!cxcursor::isFirstInDeclGroup(C))
3249 Loc = VD->getLocation();
3250 }
3251
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003252 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003253}
Douglas Gregora7bde202010-01-19 00:34:46 +00003254
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003255} // end extern "C"
3256
3257static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003258 if (clang_isReference(C.kind)) {
3259 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003260 case CXCursor_ObjCSuperClassRef:
3261 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003262
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003263 case CXCursor_ObjCProtocolRef:
3264 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003265
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003266 case CXCursor_ObjCClassRef:
3267 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003268
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003269 case CXCursor_TypeRef:
3270 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003271
3272 case CXCursor_TemplateRef:
3273 return getCursorTemplateRef(C).second;
3274
Douglas Gregor69319002010-08-31 23:48:11 +00003275 case CXCursor_NamespaceRef:
3276 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003277
3278 case CXCursor_MemberRef:
3279 return getCursorMemberRef(C).second;
3280
Ted Kremenek3064ef92010-08-27 21:34:58 +00003281 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003282 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003283
Douglas Gregor36897b02010-09-10 00:22:18 +00003284 case CXCursor_LabelRef:
3285 return getCursorLabelRef(C).second;
3286
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003287 case CXCursor_OverloadedDeclRef:
3288 return getCursorOverloadedDeclRef(C).second;
3289
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003290 default:
3291 // FIXME: Need a way to enumerate all non-reference cases.
3292 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003293 }
3294 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003295
3296 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003297 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003298
3299 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003300 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003301
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003302 if (C.kind == CXCursor_PreprocessingDirective)
3303 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003304
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003305 if (C.kind == CXCursor_MacroInstantiation)
3306 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003307
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003308 if (C.kind == CXCursor_MacroDefinition)
3309 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003310
3311 if (C.kind == CXCursor_InclusionDirective)
3312 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3313
Ted Kremenek007a7c92010-11-01 23:26:51 +00003314 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3315 Decl *D = cxcursor::getCursorDecl(C);
3316 SourceRange R = D->getSourceRange();
3317 // FIXME: Multiple variables declared in a single declaration
3318 // currently lack the information needed to correctly determine their
3319 // ranges when accounting for the type-specifier. We use context
3320 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3321 // and if so, whether it is the first decl.
3322 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3323 if (!cxcursor::isFirstInDeclGroup(C))
3324 R.setBegin(VD->getLocation());
3325 }
3326 return R;
3327 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003328 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003329
3330extern "C" {
3331
3332CXSourceRange clang_getCursorExtent(CXCursor C) {
3333 SourceRange R = getRawCursorExtent(C);
3334 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003335 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003336
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003337 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003338}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003339
3340CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003341 if (clang_isInvalid(C.kind))
3342 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003343
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003344 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003345 if (clang_isDeclaration(C.kind)) {
3346 Decl *D = getCursorDecl(C);
3347 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3348 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3349 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3350 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3351 if (ObjCForwardProtocolDecl *Protocols
3352 = dyn_cast<ObjCForwardProtocolDecl>(D))
3353 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3354
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003355 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003356 }
3357
Douglas Gregor97b98722010-01-19 23:20:36 +00003358 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003359 Expr *E = getCursorExpr(C);
3360 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003361 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003362 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003363
3364 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3365 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3366
Douglas Gregor97b98722010-01-19 23:20:36 +00003367 return clang_getNullCursor();
3368 }
3369
Douglas Gregor36897b02010-09-10 00:22:18 +00003370 if (clang_isStatement(C.kind)) {
3371 Stmt *S = getCursorStmt(C);
3372 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3373 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3374 getCursorASTUnit(C));
3375
3376 return clang_getNullCursor();
3377 }
3378
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003379 if (C.kind == CXCursor_MacroInstantiation) {
3380 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3381 return MakeMacroDefinitionCursor(Def, CXXUnit);
3382 }
3383
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003384 if (!clang_isReference(C.kind))
3385 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003386
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003387 switch (C.kind) {
3388 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003389 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003390
3391 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003392 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003393
3394 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003395 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003396
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003397 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003398 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003399
3400 case CXCursor_TemplateRef:
3401 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3402
Douglas Gregor69319002010-08-31 23:48:11 +00003403 case CXCursor_NamespaceRef:
3404 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3405
Douglas Gregora67e03f2010-09-09 21:42:20 +00003406 case CXCursor_MemberRef:
3407 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3408
Ted Kremenek3064ef92010-08-27 21:34:58 +00003409 case CXCursor_CXXBaseSpecifier: {
3410 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3411 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3412 CXXUnit));
3413 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003414
Douglas Gregor36897b02010-09-10 00:22:18 +00003415 case CXCursor_LabelRef:
3416 // FIXME: We end up faking the "parent" declaration here because we
3417 // don't want to make CXCursor larger.
3418 return MakeCXCursor(getCursorLabelRef(C).first,
3419 CXXUnit->getASTContext().getTranslationUnitDecl(),
3420 CXXUnit);
3421
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003422 case CXCursor_OverloadedDeclRef:
3423 return C;
3424
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003425 default:
3426 // We would prefer to enumerate all non-reference cursor kinds here.
3427 llvm_unreachable("Unhandled reference cursor kind");
3428 break;
3429 }
3430 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003431
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003432 return clang_getNullCursor();
3433}
3434
Douglas Gregorb6998662010-01-19 19:34:47 +00003435CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003436 if (clang_isInvalid(C.kind))
3437 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003439 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003440
Douglas Gregorb6998662010-01-19 19:34:47 +00003441 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003442 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003443 C = clang_getCursorReferenced(C);
3444 WasReference = true;
3445 }
3446
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003447 if (C.kind == CXCursor_MacroInstantiation)
3448 return clang_getCursorReferenced(C);
3449
Douglas Gregorb6998662010-01-19 19:34:47 +00003450 if (!clang_isDeclaration(C.kind))
3451 return clang_getNullCursor();
3452
3453 Decl *D = getCursorDecl(C);
3454 if (!D)
3455 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456
Douglas Gregorb6998662010-01-19 19:34:47 +00003457 switch (D->getKind()) {
3458 // Declaration kinds that don't really separate the notions of
3459 // declaration and definition.
3460 case Decl::Namespace:
3461 case Decl::Typedef:
3462 case Decl::TemplateTypeParm:
3463 case Decl::EnumConstant:
3464 case Decl::Field:
3465 case Decl::ObjCIvar:
3466 case Decl::ObjCAtDefsField:
3467 case Decl::ImplicitParam:
3468 case Decl::ParmVar:
3469 case Decl::NonTypeTemplateParm:
3470 case Decl::TemplateTemplateParm:
3471 case Decl::ObjCCategoryImpl:
3472 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003473 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003474 case Decl::LinkageSpec:
3475 case Decl::ObjCPropertyImpl:
3476 case Decl::FileScopeAsm:
3477 case Decl::StaticAssert:
3478 case Decl::Block:
3479 return C;
3480
3481 // Declaration kinds that don't make any sense here, but are
3482 // nonetheless harmless.
3483 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003484 break;
3485
3486 // Declaration kinds for which the definition is not resolvable.
3487 case Decl::UnresolvedUsingTypename:
3488 case Decl::UnresolvedUsingValue:
3489 break;
3490
3491 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003492 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3493 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003494
3495 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003496 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003497
3498 case Decl::Enum:
3499 case Decl::Record:
3500 case Decl::CXXRecord:
3501 case Decl::ClassTemplateSpecialization:
3502 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003503 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003504 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003505 return clang_getNullCursor();
3506
3507 case Decl::Function:
3508 case Decl::CXXMethod:
3509 case Decl::CXXConstructor:
3510 case Decl::CXXDestructor:
3511 case Decl::CXXConversion: {
3512 const FunctionDecl *Def = 0;
3513 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003514 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003515 return clang_getNullCursor();
3516 }
3517
3518 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003519 // Ask the variable if it has a definition.
3520 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3521 return MakeCXCursor(Def, CXXUnit);
3522 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003523 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003524
Douglas Gregorb6998662010-01-19 19:34:47 +00003525 case Decl::FunctionTemplate: {
3526 const FunctionDecl *Def = 0;
3527 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003528 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003529 return clang_getNullCursor();
3530 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003531
Douglas Gregorb6998662010-01-19 19:34:47 +00003532 case Decl::ClassTemplate: {
3533 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003534 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003535 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003536 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003537 return clang_getNullCursor();
3538 }
3539
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003540 case Decl::Using:
3541 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3542 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003543
3544 case Decl::UsingShadow:
3545 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003546 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003547 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003548
3549 case Decl::ObjCMethod: {
3550 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3551 if (Method->isThisDeclarationADefinition())
3552 return C;
3553
3554 // Dig out the method definition in the associated
3555 // @implementation, if we have it.
3556 // FIXME: The ASTs should make finding the definition easier.
3557 if (ObjCInterfaceDecl *Class
3558 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3559 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3560 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3561 Method->isInstanceMethod()))
3562 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003563 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003564
3565 return clang_getNullCursor();
3566 }
3567
3568 case Decl::ObjCCategory:
3569 if (ObjCCategoryImplDecl *Impl
3570 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003571 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003572 return clang_getNullCursor();
3573
3574 case Decl::ObjCProtocol:
3575 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3576 return C;
3577 return clang_getNullCursor();
3578
3579 case Decl::ObjCInterface:
3580 // There are two notions of a "definition" for an Objective-C
3581 // class: the interface and its implementation. When we resolved a
3582 // reference to an Objective-C class, produce the @interface as
3583 // the definition; when we were provided with the interface,
3584 // produce the @implementation as the definition.
3585 if (WasReference) {
3586 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3587 return C;
3588 } else if (ObjCImplementationDecl *Impl
3589 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003590 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003591 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003592
Douglas Gregorb6998662010-01-19 19:34:47 +00003593 case Decl::ObjCProperty:
3594 // FIXME: We don't really know where to find the
3595 // ObjCPropertyImplDecls that implement this property.
3596 return clang_getNullCursor();
3597
3598 case Decl::ObjCCompatibleAlias:
3599 if (ObjCInterfaceDecl *Class
3600 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3601 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003602 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003603
Douglas Gregorb6998662010-01-19 19:34:47 +00003604 return clang_getNullCursor();
3605
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003606 case Decl::ObjCForwardProtocol:
3607 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3608 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003609
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003610 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003611 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003612 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003613
3614 case Decl::Friend:
3615 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003616 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003617 return clang_getNullCursor();
3618
3619 case Decl::FriendTemplate:
3620 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003621 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003622 return clang_getNullCursor();
3623 }
3624
3625 return clang_getNullCursor();
3626}
3627
3628unsigned clang_isCursorDefinition(CXCursor C) {
3629 if (!clang_isDeclaration(C.kind))
3630 return 0;
3631
3632 return clang_getCursorDefinition(C) == C;
3633}
3634
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003635unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003636 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003637 return 0;
3638
3639 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3640 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3641 return E->getNumDecls();
3642
3643 if (OverloadedTemplateStorage *S
3644 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3645 return S->size();
3646
3647 Decl *D = Storage.get<Decl*>();
3648 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003649 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003650 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3651 return Classes->size();
3652 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3653 return Protocols->protocol_size();
3654
3655 return 0;
3656}
3657
3658CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003659 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003660 return clang_getNullCursor();
3661
3662 if (index >= clang_getNumOverloadedDecls(cursor))
3663 return clang_getNullCursor();
3664
3665 ASTUnit *Unit = getCursorASTUnit(cursor);
3666 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3667 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3668 return MakeCXCursor(E->decls_begin()[index], Unit);
3669
3670 if (OverloadedTemplateStorage *S
3671 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3672 return MakeCXCursor(S->begin()[index], Unit);
3673
3674 Decl *D = Storage.get<Decl*>();
3675 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3676 // FIXME: This is, unfortunately, linear time.
3677 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3678 std::advance(Pos, index);
3679 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3680 }
3681
3682 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3683 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3684
3685 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3686 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3687
3688 return clang_getNullCursor();
3689}
3690
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003691void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003692 const char **startBuf,
3693 const char **endBuf,
3694 unsigned *startLine,
3695 unsigned *startColumn,
3696 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003697 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003698 assert(getCursorDecl(C) && "CXCursor has null decl");
3699 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003700 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3701 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003702
Steve Naroff4ade6d62009-09-23 17:52:52 +00003703 SourceManager &SM = FD->getASTContext().getSourceManager();
3704 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3705 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3706 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3707 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3708 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3709 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3710}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003711
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003712void clang_enableStackTraces(void) {
3713 llvm::sys::PrintStackTraceOnErrorSignal();
3714}
3715
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003716void clang_executeOnThread(void (*fn)(void*), void *user_data,
3717 unsigned stack_size) {
3718 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3719}
3720
Ted Kremenekfb480492010-01-13 21:46:36 +00003721} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003722
Ted Kremenekfb480492010-01-13 21:46:36 +00003723//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003724// Token-based Operations.
3725//===----------------------------------------------------------------------===//
3726
3727/* CXToken layout:
3728 * int_data[0]: a CXTokenKind
3729 * int_data[1]: starting token location
3730 * int_data[2]: token length
3731 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003732 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003733 * otherwise unused.
3734 */
3735extern "C" {
3736
3737CXTokenKind clang_getTokenKind(CXToken CXTok) {
3738 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3739}
3740
3741CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3742 switch (clang_getTokenKind(CXTok)) {
3743 case CXToken_Identifier:
3744 case CXToken_Keyword:
3745 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003746 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3747 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003748
3749 case CXToken_Literal: {
3750 // We have stashed the starting pointer in the ptr_data field. Use it.
3751 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003752 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003753 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003754
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003755 case CXToken_Punctuation:
3756 case CXToken_Comment:
3757 break;
3758 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003759
3760 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003761 // deconstructing the source location.
3762 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3763 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003764 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003765
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003766 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3767 std::pair<FileID, unsigned> LocInfo
3768 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003769 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003770 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003771 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3772 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003773 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003774
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003775 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003776}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003777
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003778CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3779 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3780 if (!CXXUnit)
3781 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003782
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003783 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3784 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3785}
3786
3787CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3788 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003789 if (!CXXUnit)
3790 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003791
3792 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003793 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3794}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003795
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003796void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3797 CXToken **Tokens, unsigned *NumTokens) {
3798 if (Tokens)
3799 *Tokens = 0;
3800 if (NumTokens)
3801 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003802
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003803 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3804 if (!CXXUnit || !Tokens || !NumTokens)
3805 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Douglas Gregorbdf60622010-03-05 21:16:25 +00003807 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3808
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003809 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003810 if (R.isInvalid())
3811 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003812
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003813 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3814 std::pair<FileID, unsigned> BeginLocInfo
3815 = SourceMgr.getDecomposedLoc(R.getBegin());
3816 std::pair<FileID, unsigned> EndLocInfo
3817 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003818
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003819 // Cannot tokenize across files.
3820 if (BeginLocInfo.first != EndLocInfo.first)
3821 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003822
3823 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003824 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003825 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003826 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003827 if (Invalid)
3828 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003829
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003830 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3831 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003832 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003833 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003834
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003835 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003836 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837 llvm::SmallVector<CXToken, 32> CXTokens;
3838 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003839 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003840 do {
3841 // Lex the next token
3842 Lex.LexFromRawLexer(Tok);
3843 if (Tok.is(tok::eof))
3844 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003845
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003846 // Initialize the CXToken.
3847 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003848
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003849 // - Common fields
3850 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3851 CXTok.int_data[2] = Tok.getLength();
3852 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003853
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003854 // - Kind-specific fields
3855 if (Tok.isLiteral()) {
3856 CXTok.int_data[0] = CXToken_Literal;
3857 CXTok.ptr_data = (void *)Tok.getLiteralData();
3858 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003859 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003860 std::pair<FileID, unsigned> LocInfo
3861 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003862 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003863 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003864 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3865 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003866 return;
3867
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003868 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003869 IdentifierInfo *II
3870 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003871
David Chisnall096428b2010-10-13 21:44:48 +00003872 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003873 CXTok.int_data[0] = CXToken_Keyword;
3874 }
3875 else {
3876 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3877 CXToken_Identifier
3878 : CXToken_Keyword;
3879 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003880 CXTok.ptr_data = II;
3881 } else if (Tok.is(tok::comment)) {
3882 CXTok.int_data[0] = CXToken_Comment;
3883 CXTok.ptr_data = 0;
3884 } else {
3885 CXTok.int_data[0] = CXToken_Punctuation;
3886 CXTok.ptr_data = 0;
3887 }
3888 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003889 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003891
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003892 if (CXTokens.empty())
3893 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3896 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3897 *NumTokens = CXTokens.size();
3898}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003899
Ted Kremenek6db61092010-05-05 00:55:15 +00003900void clang_disposeTokens(CXTranslationUnit TU,
3901 CXToken *Tokens, unsigned NumTokens) {
3902 free(Tokens);
3903}
3904
3905} // end: extern "C"
3906
3907//===----------------------------------------------------------------------===//
3908// Token annotation APIs.
3909//===----------------------------------------------------------------------===//
3910
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003911typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003912static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3913 CXCursor parent,
3914 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003915namespace {
3916class AnnotateTokensWorker {
3917 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003918 CXToken *Tokens;
3919 CXCursor *Cursors;
3920 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003921 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003922 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003923 CursorVisitor AnnotateVis;
3924 SourceManager &SrcMgr;
3925
3926 bool MoreTokens() const { return TokIdx < NumTokens; }
3927 unsigned NextToken() const { return TokIdx; }
3928 void AdvanceToken() { ++TokIdx; }
3929 SourceLocation GetTokenLoc(unsigned tokI) {
3930 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3931 }
3932
Ted Kremenek6db61092010-05-05 00:55:15 +00003933public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003934 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003935 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3936 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003937 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003938 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003939 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3940 Decl::MaxPCHLevel, RegionOfInterest),
3941 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003942
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003943 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003944 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003945 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003946 void AnnotateTokens() {
3947 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3948 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003949};
3950}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003951
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003952void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3953 // Walk the AST within the region of interest, annotating tokens
3954 // along the way.
3955 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003956
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003957 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3958 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003959 if (Pos != Annotated.end() &&
3960 (clang_isInvalid(Cursors[I].kind) ||
3961 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003962 Cursors[I] = Pos->second;
3963 }
3964
3965 // Finish up annotating any tokens left.
3966 if (!MoreTokens())
3967 return;
3968
3969 const CXCursor &C = clang_getNullCursor();
3970 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3971 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3972 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003973 }
3974}
3975
Ted Kremenek6db61092010-05-05 00:55:15 +00003976enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003977AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003978 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003979 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003980 if (cursorRange.isInvalid())
3981 return CXChildVisit_Recurse;
3982
Douglas Gregor4419b672010-10-21 06:10:04 +00003983 if (clang_isPreprocessing(cursor.kind)) {
3984 // For macro instantiations, just note where the beginning of the macro
3985 // instantiation occurs.
3986 if (cursor.kind == CXCursor_MacroInstantiation) {
3987 Annotated[Loc.int_data] = cursor;
3988 return CXChildVisit_Recurse;
3989 }
3990
Douglas Gregor4419b672010-10-21 06:10:04 +00003991 // Items in the preprocessing record are kept separate from items in
3992 // declarations, so we keep a separate token index.
3993 unsigned SavedTokIdx = TokIdx;
3994 TokIdx = PreprocessingTokIdx;
3995
3996 // Skip tokens up until we catch up to the beginning of the preprocessing
3997 // entry.
3998 while (MoreTokens()) {
3999 const unsigned I = NextToken();
4000 SourceLocation TokLoc = GetTokenLoc(I);
4001 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4002 case RangeBefore:
4003 AdvanceToken();
4004 continue;
4005 case RangeAfter:
4006 case RangeOverlap:
4007 break;
4008 }
4009 break;
4010 }
4011
4012 // Look at all of the tokens within this range.
4013 while (MoreTokens()) {
4014 const unsigned I = NextToken();
4015 SourceLocation TokLoc = GetTokenLoc(I);
4016 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4017 case RangeBefore:
4018 assert(0 && "Infeasible");
4019 case RangeAfter:
4020 break;
4021 case RangeOverlap:
4022 Cursors[I] = cursor;
4023 AdvanceToken();
4024 continue;
4025 }
4026 break;
4027 }
4028
4029 // Save the preprocessing token index; restore the non-preprocessing
4030 // token index.
4031 PreprocessingTokIdx = TokIdx;
4032 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004033 return CXChildVisit_Recurse;
4034 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004035
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004036 if (cursorRange.isInvalid())
4037 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004038
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004039 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4040
Ted Kremeneka333c662010-05-12 05:29:33 +00004041 // Adjust the annotated range based specific declarations.
4042 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4043 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004044 Decl *D = cxcursor::getCursorDecl(cursor);
4045 // Don't visit synthesized ObjC methods, since they have no syntatic
4046 // representation in the source.
4047 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4048 if (MD->isSynthesized())
4049 return CXChildVisit_Continue;
4050 }
4051 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004052 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4053 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004054 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004055 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004056 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004057 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004058 }
4059 }
4060 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004061
Ted Kremenek3f404602010-08-14 01:14:06 +00004062 // If the location of the cursor occurs within a macro instantiation, record
4063 // the spelling location of the cursor in our annotation map. We can then
4064 // paper over the token labelings during a post-processing step to try and
4065 // get cursor mappings for tokens that are the *arguments* of a macro
4066 // instantiation.
4067 if (L.isMacroID()) {
4068 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4069 // Only invalidate the old annotation if it isn't part of a preprocessing
4070 // directive. Here we assume that the default construction of CXCursor
4071 // results in CXCursor.kind being an initialized value (i.e., 0). If
4072 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004073
Ted Kremenek3f404602010-08-14 01:14:06 +00004074 CXCursor &oldC = Annotated[rawEncoding];
4075 if (!clang_isPreprocessing(oldC.kind))
4076 oldC = cursor;
4077 }
4078
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004079 const enum CXCursorKind K = clang_getCursorKind(parent);
4080 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004081 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4082 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004083
4084 while (MoreTokens()) {
4085 const unsigned I = NextToken();
4086 SourceLocation TokLoc = GetTokenLoc(I);
4087 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4088 case RangeBefore:
4089 Cursors[I] = updateC;
4090 AdvanceToken();
4091 continue;
4092 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004093 case RangeOverlap:
4094 break;
4095 }
4096 break;
4097 }
4098
4099 // Visit children to get their cursor information.
4100 const unsigned BeforeChildren = NextToken();
4101 VisitChildren(cursor);
4102 const unsigned AfterChildren = NextToken();
4103
4104 // Adjust 'Last' to the last token within the extent of the cursor.
4105 while (MoreTokens()) {
4106 const unsigned I = NextToken();
4107 SourceLocation TokLoc = GetTokenLoc(I);
4108 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4109 case RangeBefore:
4110 assert(0 && "Infeasible");
4111 case RangeAfter:
4112 break;
4113 case RangeOverlap:
4114 Cursors[I] = updateC;
4115 AdvanceToken();
4116 continue;
4117 }
4118 break;
4119 }
4120 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004121
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004122 // Scan the tokens that are at the beginning of the cursor, but are not
4123 // capture by the child cursors.
4124
4125 // For AST elements within macros, rely on a post-annotate pass to
4126 // to correctly annotate the tokens with cursors. Otherwise we can
4127 // get confusing results of having tokens that map to cursors that really
4128 // are expanded by an instantiation.
4129 if (L.isMacroID())
4130 cursor = clang_getNullCursor();
4131
4132 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4133 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4134 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004135
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004136 Cursors[I] = cursor;
4137 }
4138 // Scan the tokens that are at the end of the cursor, but are not captured
4139 // but the child cursors.
4140 for (unsigned I = AfterChildren; I != Last; ++I)
4141 Cursors[I] = cursor;
4142
4143 TokIdx = Last;
4144 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004145}
4146
Ted Kremenek6db61092010-05-05 00:55:15 +00004147static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4148 CXCursor parent,
4149 CXClientData client_data) {
4150 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4151}
4152
Ted Kremenekab979612010-11-11 08:05:23 +00004153// This gets run a separate thread to avoid stack blowout.
4154static void runAnnotateTokensWorker(void *UserData) {
4155 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4156}
4157
Ted Kremenek6db61092010-05-05 00:55:15 +00004158extern "C" {
4159
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004160void clang_annotateTokens(CXTranslationUnit TU,
4161 CXToken *Tokens, unsigned NumTokens,
4162 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004163
4164 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004165 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004166
Douglas Gregor4419b672010-10-21 06:10:04 +00004167 // Any token we don't specifically annotate will have a NULL cursor.
4168 CXCursor C = clang_getNullCursor();
4169 for (unsigned I = 0; I != NumTokens; ++I)
4170 Cursors[I] = C;
4171
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004172 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004173 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004174 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004175
Douglas Gregorbdf60622010-03-05 21:16:25 +00004176 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004177
Douglas Gregor0396f462010-03-19 05:22:59 +00004178 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004179 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004180 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4181 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004182 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4183 clang_getTokenLocation(TU,
4184 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004185
Douglas Gregor0396f462010-03-19 05:22:59 +00004186 // A mapping from the source locations found when re-lexing or traversing the
4187 // region of interest to the corresponding cursors.
4188 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004189
4190 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004191 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004192 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4193 std::pair<FileID, unsigned> BeginLocInfo
4194 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4195 std::pair<FileID, unsigned> EndLocInfo
4196 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004197
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004198 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004199 bool Invalid = false;
4200 if (BeginLocInfo.first == EndLocInfo.first &&
4201 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4202 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004203 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4204 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004205 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004206 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004207 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004208
4209 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004210 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004211 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004212 Token Tok;
4213 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004214
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004215 reprocess:
4216 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4217 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004218 // don't see it while preprocessing these tokens later, but keep track
4219 // of all of the token locations inside this preprocessing directive so
4220 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004221 //
4222 // FIXME: Some simple tests here could identify macro definitions and
4223 // #undefs, to provide specific cursor kinds for those.
4224 std::vector<SourceLocation> Locations;
4225 do {
4226 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004228 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004230 using namespace cxcursor;
4231 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4233 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004234 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004235 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4236 Annotated[Locations[I].getRawEncoding()] = Cursor;
4237 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004239 if (Tok.isAtStartOfLine())
4240 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004241
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004242 continue;
4243 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004244
Douglas Gregor48072312010-03-18 15:23:44 +00004245 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004246 break;
4247 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004248 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004249
Douglas Gregor0396f462010-03-19 05:22:59 +00004250 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004251 // a specific cursor.
4252 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4253 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004254
4255 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004256 // FIXME: We use a ridiculous stack size here because the data-recursion
4257 // algorithm uses a large stack frame than the non-data recursive version,
4258 // and AnnotationTokensWorker currently transforms the data-recursion
4259 // algorithm back into a traditional recursion by explicitly calling
4260 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004261 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004262 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4263 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004264 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4265 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004266}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004267} // end: extern "C"
4268
4269//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004270// Operations for querying linkage of a cursor.
4271//===----------------------------------------------------------------------===//
4272
4273extern "C" {
4274CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004275 if (!clang_isDeclaration(cursor.kind))
4276 return CXLinkage_Invalid;
4277
Ted Kremenek16b42592010-03-03 06:36:57 +00004278 Decl *D = cxcursor::getCursorDecl(cursor);
4279 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4280 switch (ND->getLinkage()) {
4281 case NoLinkage: return CXLinkage_NoLinkage;
4282 case InternalLinkage: return CXLinkage_Internal;
4283 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4284 case ExternalLinkage: return CXLinkage_External;
4285 };
4286
4287 return CXLinkage_Invalid;
4288}
4289} // end: extern "C"
4290
4291//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004292// Operations for querying language of a cursor.
4293//===----------------------------------------------------------------------===//
4294
4295static CXLanguageKind getDeclLanguage(const Decl *D) {
4296 switch (D->getKind()) {
4297 default:
4298 break;
4299 case Decl::ImplicitParam:
4300 case Decl::ObjCAtDefsField:
4301 case Decl::ObjCCategory:
4302 case Decl::ObjCCategoryImpl:
4303 case Decl::ObjCClass:
4304 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004305 case Decl::ObjCForwardProtocol:
4306 case Decl::ObjCImplementation:
4307 case Decl::ObjCInterface:
4308 case Decl::ObjCIvar:
4309 case Decl::ObjCMethod:
4310 case Decl::ObjCProperty:
4311 case Decl::ObjCPropertyImpl:
4312 case Decl::ObjCProtocol:
4313 return CXLanguage_ObjC;
4314 case Decl::CXXConstructor:
4315 case Decl::CXXConversion:
4316 case Decl::CXXDestructor:
4317 case Decl::CXXMethod:
4318 case Decl::CXXRecord:
4319 case Decl::ClassTemplate:
4320 case Decl::ClassTemplatePartialSpecialization:
4321 case Decl::ClassTemplateSpecialization:
4322 case Decl::Friend:
4323 case Decl::FriendTemplate:
4324 case Decl::FunctionTemplate:
4325 case Decl::LinkageSpec:
4326 case Decl::Namespace:
4327 case Decl::NamespaceAlias:
4328 case Decl::NonTypeTemplateParm:
4329 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004330 case Decl::TemplateTemplateParm:
4331 case Decl::TemplateTypeParm:
4332 case Decl::UnresolvedUsingTypename:
4333 case Decl::UnresolvedUsingValue:
4334 case Decl::Using:
4335 case Decl::UsingDirective:
4336 case Decl::UsingShadow:
4337 return CXLanguage_CPlusPlus;
4338 }
4339
4340 return CXLanguage_C;
4341}
4342
4343extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004344
4345enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4346 if (clang_isDeclaration(cursor.kind))
4347 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4348 if (D->hasAttr<UnavailableAttr>() ||
4349 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4350 return CXAvailability_Available;
4351
4352 if (D->hasAttr<DeprecatedAttr>())
4353 return CXAvailability_Deprecated;
4354 }
4355
4356 return CXAvailability_Available;
4357}
4358
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004359CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4360 if (clang_isDeclaration(cursor.kind))
4361 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4362
4363 return CXLanguage_Invalid;
4364}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004365
4366CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4367 if (clang_isDeclaration(cursor.kind)) {
4368 if (Decl *D = getCursorDecl(cursor)) {
4369 DeclContext *DC = D->getDeclContext();
4370 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4371 }
4372 }
4373
4374 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4375 if (Decl *D = getCursorDecl(cursor))
4376 return MakeCXCursor(D, getCursorASTUnit(cursor));
4377 }
4378
4379 return clang_getNullCursor();
4380}
4381
4382CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4383 if (clang_isDeclaration(cursor.kind)) {
4384 if (Decl *D = getCursorDecl(cursor)) {
4385 DeclContext *DC = D->getLexicalDeclContext();
4386 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4387 }
4388 }
4389
4390 // FIXME: Note that we can't easily compute the lexical context of a
4391 // statement or expression, so we return nothing.
4392 return clang_getNullCursor();
4393}
4394
Douglas Gregor9f592342010-10-01 20:25:15 +00004395static void CollectOverriddenMethods(DeclContext *Ctx,
4396 ObjCMethodDecl *Method,
4397 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4398 if (!Ctx)
4399 return;
4400
4401 // If we have a class or category implementation, jump straight to the
4402 // interface.
4403 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4404 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4405
4406 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4407 if (!Container)
4408 return;
4409
4410 // Check whether we have a matching method at this level.
4411 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4412 Method->isInstanceMethod()))
4413 if (Method != Overridden) {
4414 // We found an override at this level; there is no need to look
4415 // into other protocols or categories.
4416 Methods.push_back(Overridden);
4417 return;
4418 }
4419
4420 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4421 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4422 PEnd = Protocol->protocol_end();
4423 P != PEnd; ++P)
4424 CollectOverriddenMethods(*P, Method, Methods);
4425 }
4426
4427 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4428 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4429 PEnd = Category->protocol_end();
4430 P != PEnd; ++P)
4431 CollectOverriddenMethods(*P, Method, Methods);
4432 }
4433
4434 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4435 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4436 PEnd = Interface->protocol_end();
4437 P != PEnd; ++P)
4438 CollectOverriddenMethods(*P, Method, Methods);
4439
4440 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4441 Category; Category = Category->getNextClassCategory())
4442 CollectOverriddenMethods(Category, Method, Methods);
4443
4444 // We only look into the superclass if we haven't found anything yet.
4445 if (Methods.empty())
4446 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4447 return CollectOverriddenMethods(Super, Method, Methods);
4448 }
4449}
4450
4451void clang_getOverriddenCursors(CXCursor cursor,
4452 CXCursor **overridden,
4453 unsigned *num_overridden) {
4454 if (overridden)
4455 *overridden = 0;
4456 if (num_overridden)
4457 *num_overridden = 0;
4458 if (!overridden || !num_overridden)
4459 return;
4460
4461 if (!clang_isDeclaration(cursor.kind))
4462 return;
4463
4464 Decl *D = getCursorDecl(cursor);
4465 if (!D)
4466 return;
4467
4468 // Handle C++ member functions.
4469 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4470 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4471 *num_overridden = CXXMethod->size_overridden_methods();
4472 if (!*num_overridden)
4473 return;
4474
4475 *overridden = new CXCursor [*num_overridden];
4476 unsigned I = 0;
4477 for (CXXMethodDecl::method_iterator
4478 M = CXXMethod->begin_overridden_methods(),
4479 MEnd = CXXMethod->end_overridden_methods();
4480 M != MEnd; (void)++M, ++I)
4481 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4482 return;
4483 }
4484
4485 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4486 if (!Method)
4487 return;
4488
4489 // Handle Objective-C methods.
4490 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4491 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4492
4493 if (Methods.empty())
4494 return;
4495
4496 *num_overridden = Methods.size();
4497 *overridden = new CXCursor [Methods.size()];
4498 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4499 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4500}
4501
4502void clang_disposeOverriddenCursors(CXCursor *overridden) {
4503 delete [] overridden;
4504}
4505
Douglas Gregorecdcb882010-10-20 22:00:55 +00004506CXFile clang_getIncludedFile(CXCursor cursor) {
4507 if (cursor.kind != CXCursor_InclusionDirective)
4508 return 0;
4509
4510 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4511 return (void *)ID->getFile();
4512}
4513
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004514} // end: extern "C"
4515
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004516
4517//===----------------------------------------------------------------------===//
4518// C++ AST instrospection.
4519//===----------------------------------------------------------------------===//
4520
4521extern "C" {
4522unsigned clang_CXXMethod_isStatic(CXCursor C) {
4523 if (!clang_isDeclaration(C.kind))
4524 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004525
4526 CXXMethodDecl *Method = 0;
4527 Decl *D = cxcursor::getCursorDecl(C);
4528 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4529 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4530 else
4531 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4532 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004533}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004534
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004535} // end: extern "C"
4536
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004537//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004538// Attribute introspection.
4539//===----------------------------------------------------------------------===//
4540
4541extern "C" {
4542CXType clang_getIBOutletCollectionType(CXCursor C) {
4543 if (C.kind != CXCursor_IBOutletCollectionAttr)
4544 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4545
4546 IBOutletCollectionAttr *A =
4547 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4548
4549 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4550}
4551} // end: extern "C"
4552
4553//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004554// CXString Operations.
4555//===----------------------------------------------------------------------===//
4556
4557extern "C" {
4558const char *clang_getCString(CXString string) {
4559 return string.Spelling;
4560}
4561
4562void clang_disposeString(CXString string) {
4563 if (string.MustFreeString && string.Spelling)
4564 free((void*)string.Spelling);
4565}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004566
Ted Kremenekfb480492010-01-13 21:46:36 +00004567} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004568
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004569namespace clang { namespace cxstring {
4570CXString createCXString(const char *String, bool DupString){
4571 CXString Str;
4572 if (DupString) {
4573 Str.Spelling = strdup(String);
4574 Str.MustFreeString = 1;
4575 } else {
4576 Str.Spelling = String;
4577 Str.MustFreeString = 0;
4578 }
4579 return Str;
4580}
4581
4582CXString createCXString(llvm::StringRef String, bool DupString) {
4583 CXString Result;
4584 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4585 char *Spelling = (char *)malloc(String.size() + 1);
4586 memmove(Spelling, String.data(), String.size());
4587 Spelling[String.size()] = 0;
4588 Result.Spelling = Spelling;
4589 Result.MustFreeString = 1;
4590 } else {
4591 Result.Spelling = String.data();
4592 Result.MustFreeString = 0;
4593 }
4594 return Result;
4595}
4596}}
4597
Ted Kremenek04bb7162010-01-22 22:44:15 +00004598//===----------------------------------------------------------------------===//
4599// Misc. utility functions.
4600//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004601
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004602/// Default to using an 8 MB stack size on "safety" threads.
4603static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004604
4605namespace clang {
4606
4607bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004608 void (*Fn)(void*), void *UserData,
4609 unsigned Size) {
4610 if (!Size)
4611 Size = GetSafetyThreadStackSize();
4612 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004613 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4614 return CRC.RunSafely(Fn, UserData);
4615}
4616
4617unsigned GetSafetyThreadStackSize() {
4618 return SafetyStackThreadSize;
4619}
4620
4621void SetSafetyThreadStackSize(unsigned Value) {
4622 SafetyStackThreadSize = Value;
4623}
4624
4625}
4626
Ted Kremenek04bb7162010-01-22 22:44:15 +00004627extern "C" {
4628
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004629CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004630 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004631}
4632
4633} // end: extern "C"