blob: b573c067a808fa889e3c5a6a3f709298d0be4138 [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 Kremenek37f1ea02010-11-15 23:11:54 +000045#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000046
Steve Naroff50398192009-08-28 15:28:48 +000047using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000048using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000049using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000050
Douglas Gregor33e9abd2010-01-22 19:49:59 +000051/// \brief The result of comparing two source ranges.
52enum RangeComparisonResult {
53 /// \brief Either the ranges overlap or one of the ranges is invalid.
54 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000055
Douglas Gregor33e9abd2010-01-22 19:49:59 +000056 /// \brief The first range ends before the second range starts.
57 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000058
Douglas Gregor33e9abd2010-01-22 19:49:59 +000059 /// \brief The first range starts after the second range ends.
60 RangeAfter
61};
62
Ted Kremenekf0e23e82010-02-17 00:41:40 +000063/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000064/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065static RangeComparisonResult RangeCompare(SourceManager &SM,
66 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000067 SourceRange R2) {
68 assert(R1.isValid() && "First range is invalid?");
69 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000070 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000071 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000072 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000073 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000074 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075 return RangeAfter;
76 return RangeOverlap;
77}
78
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000079/// \brief Determine if a source location falls within, before, or after a
80/// a given source range.
81static RangeComparisonResult LocationCompare(SourceManager &SM,
82 SourceLocation L, SourceRange R) {
83 assert(R.isValid() && "First range is invalid?");
84 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000085 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000086 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000087 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
88 return RangeBefore;
89 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
90 return RangeAfter;
91 return RangeOverlap;
92}
93
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000094/// \brief Translate a Clang source range into a CIndex source range.
95///
96/// Clang internally represents ranges where the end location points to the
97/// start of the token at the end. However, for external clients it is more
98/// useful to have a CXSourceRange be a proper half-open interval. This routine
99/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000100CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000101 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000102 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000104 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000106 if (EndLoc.isValid() && EndLoc.isMacroID())
107 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000108 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000109 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000110 EndLoc = EndLoc.getFileLocWithOffset(Length);
111 }
112
113 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
114 R.getBegin().getRawEncoding(),
115 EndLoc.getRawEncoding() };
116 return Result;
117}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000118
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000119//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000120// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
122
Steve Naroff89922f82009-08-31 00:59:03 +0000123namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000124
125class VisitorJob {
126public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000127 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000128 TypeLocVisitKind, OverloadExprPartsKind,
129 DeclRefExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000130protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000131 void *dataA;
132 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000133 CXCursor parent;
134 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000135 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
136 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000137public:
138 Kind getKind() const { return K; }
139 const CXCursor &getParent() const { return parent; }
140 static bool classof(VisitorJob *VJ) { return true; }
141};
142
143typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
144
Douglas Gregorb1373d02010-01-20 20:59:29 +0000145// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000146class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000147 public TypeLocVisitor<CursorVisitor, bool>,
148 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000149{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000150 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000151 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000152
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000153 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000154 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000155
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000156 /// \brief The declaration that serves at the parent of any statement or
157 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000158 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000159
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000160 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000161 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000162
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000163 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000164 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000165
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000166 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
167 // to the visitor. Declarations with a PCH level greater than this value will
168 // be suppressed.
169 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170
171 /// \brief When valid, a source range to which the cursor should restrict
172 /// its search.
173 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000175 // FIXME: Eventually remove. This part of a hack to support proper
176 // iteration over all Decls contained lexically within an ObjC container.
177 DeclContext::decl_iterator *DI_current;
178 DeclContext::decl_iterator DE_current;
179
Ted Kremenekd1ded662010-11-15 23:31:32 +0000180 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
181 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
182 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
183
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000185 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000186 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000187
188 /// \brief Determine whether this particular source range comes before, comes
189 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000191 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
193
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000194 class SetParentRAII {
195 CXCursor &Parent;
196 Decl *&StmtParent;
197 CXCursor OldParent;
198
199 public:
200 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
201 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
202 {
203 Parent = NewParent;
204 if (clang_isDeclaration(Parent.kind))
205 StmtParent = getCursorDecl(Parent);
206 }
207
208 ~SetParentRAII() {
209 Parent = OldParent;
210 if (clang_isDeclaration(Parent.kind))
211 StmtParent = getCursorDecl(Parent);
212 }
213 };
214
Steve Naroff89922f82009-08-31 00:59:03 +0000215public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000216 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
217 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000219 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000220 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
221 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000222 {
223 Parent.kind = CXCursor_NoDeclFound;
224 Parent.data[0] = 0;
225 Parent.data[1] = 0;
226 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000227 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000228 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000229
Ted Kremenekd1ded662010-11-15 23:31:32 +0000230 ~CursorVisitor() {
231 // Free the pre-allocated worklists for data-recursion.
232 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
233 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
234 delete *I;
235 }
236 }
237
Ted Kremenekab979612010-11-11 08:05:23 +0000238 ASTUnit *getASTUnit() const { return TU; }
239
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000240 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000241
242 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
243 getPreprocessedEntities();
244
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000246
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000247 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000248 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000249 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000250 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000251 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000252 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000253 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
254 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000255 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000256 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000257 bool VisitClassTemplatePartialSpecializationDecl(
258 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000259 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000260 bool VisitEnumConstantDecl(EnumConstantDecl *D);
261 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
262 bool VisitFunctionDecl(FunctionDecl *ND);
263 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000264 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000265 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000266 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000267 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000268 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
270 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
271 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
272 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000273 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000274 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
275 bool VisitObjCImplDecl(ObjCImplDecl *D);
276 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
277 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000278 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
279 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
280 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000281 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000282 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000283 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000284 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000285 bool VisitUsingDecl(UsingDecl *D);
286 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
287 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000288
Douglas Gregor01829d32010-08-31 14:41:23 +0000289 // Name visitor
290 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000291 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000292
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000293 // Template visitors
294 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000295 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000296 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
297
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000298 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000299 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000300 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000301 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000302 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
303 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000304 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000305 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000306 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000307 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
308 bool VisitPointerTypeLoc(PointerTypeLoc TL);
309 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
310 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
311 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
312 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000313 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000315 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000316 // FIXME: Implement visitors here when the unimplemented TypeLocs get
317 // implemented
318 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
319 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000320
Douglas Gregora59e3902010-01-21 23:27:09 +0000321 // Statement visitors
322 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000323
Douglas Gregor336fd812010-01-23 00:40:08 +0000324 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000325 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000326 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000327 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000328 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
329 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000330 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000331 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000332 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000333 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000334 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000335 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000336 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000337 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000338 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000339
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000340 // Data-recursive visitor functions.
341 bool IsInRegionOfInterest(CXCursor C);
342 bool RunVisitorWorkList(VisitorWorkList &WL);
343 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenek37f1ea02010-11-15 23:11:54 +0000344 bool VisitDataRecursive(Stmt *S) LLVM_ATTRIBUTE_NOINLINE;
Steve Naroff89922f82009-08-31 00:59:03 +0000345};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000346
Ted Kremenekab188932010-01-05 19:32:54 +0000347} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000348
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000349static SourceRange getRawCursorExtent(CXCursor C);
350
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000351RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000352 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
353}
354
Douglas Gregorb1373d02010-01-20 20:59:29 +0000355/// \brief Visit the given cursor and, if requested by the visitor,
356/// its children.
357///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000358/// \param Cursor the cursor to visit.
359///
360/// \param CheckRegionOfInterest if true, then the caller already checked that
361/// this cursor is within the region of interest.
362///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \returns true if the visitation should be aborted, false if it
364/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000366 if (clang_isInvalid(Cursor.kind))
367 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000368
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369 if (clang_isDeclaration(Cursor.kind)) {
370 Decl *D = getCursorDecl(Cursor);
371 assert(D && "Invalid declaration cursor");
372 if (D->getPCHLevel() > MaxPCHLevel)
373 return false;
374
375 if (D->isImplicit())
376 return false;
377 }
378
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000379 // If we have a range of interest, and this cursor doesn't intersect with it,
380 // we're done.
381 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000382 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000383 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000384 return false;
385 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000386
Douglas Gregorb1373d02010-01-20 20:59:29 +0000387 switch (Visitor(Cursor, Parent, ClientData)) {
388 case CXChildVisit_Break:
389 return true;
390
391 case CXChildVisit_Continue:
392 return false;
393
394 case CXChildVisit_Recurse:
395 return VisitChildren(Cursor);
396 }
397
Douglas Gregorfd643772010-01-25 16:45:46 +0000398 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399}
400
Douglas Gregor788f5a12010-03-20 00:41:21 +0000401std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
402CursorVisitor::getPreprocessedEntities() {
403 PreprocessingRecord &PPRec
404 = *TU->getPreprocessor().getPreprocessingRecord();
405
406 bool OnlyLocalDecls
407 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
408
409 // There is no region of interest; we have to walk everything.
410 if (RegionOfInterest.isInvalid())
411 return std::make_pair(PPRec.begin(OnlyLocalDecls),
412 PPRec.end(OnlyLocalDecls));
413
414 // Find the file in which the region of interest lands.
415 SourceManager &SM = TU->getSourceManager();
416 std::pair<FileID, unsigned> Begin
417 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
418 std::pair<FileID, unsigned> End
419 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
420
421 // The region of interest spans files; we have to walk everything.
422 if (Begin.first != End.first)
423 return std::make_pair(PPRec.begin(OnlyLocalDecls),
424 PPRec.end(OnlyLocalDecls));
425
426 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
427 = TU->getPreprocessedEntitiesByFile();
428 if (ByFileMap.empty()) {
429 // Build the mapping from files to sets of preprocessed entities.
430 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
431 EEnd = PPRec.end(OnlyLocalDecls);
432 E != EEnd; ++E) {
433 std::pair<FileID, unsigned> P
434 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
435 ByFileMap[P.first].push_back(*E);
436 }
437 }
438
439 return std::make_pair(ByFileMap[Begin.first].begin(),
440 ByFileMap[Begin.first].end());
441}
442
Douglas Gregorb1373d02010-01-20 20:59:29 +0000443/// \brief Visit the children of the given cursor.
444///
445/// \returns true if the visitation should be aborted, false if it
446/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000447bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000448 if (clang_isReference(Cursor.kind)) {
449 // By definition, references have no children.
450 return false;
451 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000452
453 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000455 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457 if (clang_isDeclaration(Cursor.kind)) {
458 Decl *D = getCursorDecl(Cursor);
459 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000460 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000461 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000462
Douglas Gregora59e3902010-01-21 23:27:09 +0000463 if (clang_isStatement(Cursor.kind))
464 return Visit(getCursorStmt(Cursor));
465 if (clang_isExpression(Cursor.kind))
466 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000467
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000469 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000470 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
471 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000472 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
473 TLEnd = CXXUnit->top_level_end();
474 TL != TLEnd; ++TL) {
475 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000476 return true;
477 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000478 } else if (VisitDeclContext(
479 CXXUnit->getASTContext().getTranslationUnitDecl()))
480 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000481
Douglas Gregor0396f462010-03-19 05:22:59 +0000482 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000483 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000484 // FIXME: Once we have the ability to deserialize a preprocessing record,
485 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000486 PreprocessingRecord::iterator E, EEnd;
487 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000488 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
489 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
490 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000491
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 continue;
493 }
494
495 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
496 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
497 return true;
498
499 continue;
500 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000501
502 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
503 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
504 return true;
505
506 continue;
507 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 }
509 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000510 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000511 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000512
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 return false;
515}
516
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000517bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000518 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
519 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000520
Ted Kremenek664cffd2010-07-22 11:30:19 +0000521 if (Stmt *Body = B->getBody())
522 return Visit(MakeCXCursor(Body, StmtParent, TU));
523
524 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000525}
526
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000527llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
528 if (RegionOfInterest.isValid()) {
529 SourceRange Range = getRawCursorExtent(Cursor);
530 if (Range.isInvalid())
531 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000532
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000533 switch (CompareRegionOfInterest(Range)) {
534 case RangeBefore:
535 // This declaration comes before the region of interest; skip it.
536 return llvm::Optional<bool>();
537
538 case RangeAfter:
539 // This declaration comes after the region of interest; we're done.
540 return false;
541
542 case RangeOverlap:
543 // This declaration overlaps the region of interest; visit it.
544 break;
545 }
546 }
547 return true;
548}
549
550bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
551 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
552
553 // FIXME: Eventually remove. This part of a hack to support proper
554 // iteration over all Decls contained lexically within an ObjC container.
555 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
556 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
557
558 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000559 Decl *D = *I;
560 if (D->getLexicalDeclContext() != DC)
561 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000562 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000563 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
564 if (!V.hasValue())
565 continue;
566 if (!V.getValue())
567 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000568 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000569 return true;
570 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000572}
573
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000574bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
575 llvm_unreachable("Translation units are visited directly by Visit()");
576 return false;
577}
578
579bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
580 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
581 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000583 return false;
584}
585
586bool CursorVisitor::VisitTagDecl(TagDecl *D) {
587 return VisitDeclContext(D);
588}
589
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000590bool CursorVisitor::VisitClassTemplateSpecializationDecl(
591 ClassTemplateSpecializationDecl *D) {
592 bool ShouldVisitBody = false;
593 switch (D->getSpecializationKind()) {
594 case TSK_Undeclared:
595 case TSK_ImplicitInstantiation:
596 // Nothing to visit
597 return false;
598
599 case TSK_ExplicitInstantiationDeclaration:
600 case TSK_ExplicitInstantiationDefinition:
601 break;
602
603 case TSK_ExplicitSpecialization:
604 ShouldVisitBody = true;
605 break;
606 }
607
608 // Visit the template arguments used in the specialization.
609 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
610 TypeLoc TL = SpecType->getTypeLoc();
611 if (TemplateSpecializationTypeLoc *TSTLoc
612 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
613 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
614 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
615 return true;
616 }
617 }
618
619 if (ShouldVisitBody && VisitCXXRecordDecl(D))
620 return true;
621
622 return false;
623}
624
Douglas Gregor74dbe642010-08-31 19:31:58 +0000625bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
626 ClassTemplatePartialSpecializationDecl *D) {
627 // FIXME: Visit the "outer" template parameter lists on the TagDecl
628 // before visiting these template parameters.
629 if (VisitTemplateParameters(D->getTemplateParameters()))
630 return true;
631
632 // Visit the partial specialization arguments.
633 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
634 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
635 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
636 return true;
637
638 return VisitCXXRecordDecl(D);
639}
640
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000641bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000642 // Visit the default argument.
643 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
644 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
645 if (Visit(DefArg->getTypeLoc()))
646 return true;
647
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000648 return false;
649}
650
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000651bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
652 if (Expr *Init = D->getInitExpr())
653 return Visit(MakeCXCursor(Init, StmtParent, TU));
654 return false;
655}
656
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000657bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
658 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
659 if (Visit(TSInfo->getTypeLoc()))
660 return true;
661
662 return false;
663}
664
Douglas Gregora67e03f2010-09-09 21:42:20 +0000665/// \brief Compare two base or member initializers based on their source order.
666static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
667 CXXBaseOrMemberInitializer const * const *X
668 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
669 CXXBaseOrMemberInitializer const * const *Y
670 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
671
672 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
673 return -1;
674 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
675 return 1;
676 else
677 return 0;
678}
679
Douglas Gregorb1373d02010-01-20 20:59:29 +0000680bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000681 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
682 // Visit the function declaration's syntactic components in the order
683 // written. This requires a bit of work.
684 TypeLoc TL = TSInfo->getTypeLoc();
685 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
686
687 // If we have a function declared directly (without the use of a typedef),
688 // visit just the return type. Otherwise, just visit the function's type
689 // now.
690 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
691 (!FTL && Visit(TL)))
692 return true;
693
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000694 // Visit the nested-name-specifier, if present.
695 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
696 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
697 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000698
699 // Visit the declaration name.
700 if (VisitDeclarationNameInfo(ND->getNameInfo()))
701 return true;
702
703 // FIXME: Visit explicitly-specified template arguments!
704
705 // Visit the function parameters, if we have a function type.
706 if (FTL && VisitFunctionTypeLoc(*FTL, true))
707 return true;
708
709 // FIXME: Attributes?
710 }
711
Douglas Gregora67e03f2010-09-09 21:42:20 +0000712 if (ND->isThisDeclarationADefinition()) {
713 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
714 // Find the initializers that were written in the source.
715 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
716 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
717 IEnd = Constructor->init_end();
718 I != IEnd; ++I) {
719 if (!(*I)->isWritten())
720 continue;
721
722 WrittenInits.push_back(*I);
723 }
724
725 // Sort the initializers in source order
726 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
727 &CompareCXXBaseOrMemberInitializers);
728
729 // Visit the initializers in source order
730 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
731 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
732 if (Init->isMemberInitializer()) {
733 if (Visit(MakeCursorMemberRef(Init->getMember(),
734 Init->getMemberLocation(), TU)))
735 return true;
736 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
737 if (Visit(BaseInfo->getTypeLoc()))
738 return true;
739 }
740
741 // Visit the initializer value.
742 if (Expr *Initializer = Init->getInit())
743 if (Visit(MakeCXCursor(Initializer, ND, TU)))
744 return true;
745 }
746 }
747
748 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
749 return true;
750 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000751
Douglas Gregorb1373d02010-01-20 20:59:29 +0000752 return false;
753}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000754
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000755bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
756 if (VisitDeclaratorDecl(D))
757 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000758
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000759 if (Expr *BitWidth = D->getBitWidth())
760 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000762 return false;
763}
764
765bool CursorVisitor::VisitVarDecl(VarDecl *D) {
766 if (VisitDeclaratorDecl(D))
767 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000768
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000769 if (Expr *Init = D->getInit())
770 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772 return false;
773}
774
Douglas Gregor84b51d72010-09-01 20:16:53 +0000775bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
776 if (VisitDeclaratorDecl(D))
777 return true;
778
779 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
780 if (Expr *DefArg = D->getDefaultArgument())
781 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
782
783 return false;
784}
785
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000786bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
787 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
788 // before visiting these template parameters.
789 if (VisitTemplateParameters(D->getTemplateParameters()))
790 return true;
791
792 return VisitFunctionDecl(D->getTemplatedDecl());
793}
794
Douglas Gregor39d6f072010-08-31 19:02:00 +0000795bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
796 // FIXME: Visit the "outer" template parameter lists on the TagDecl
797 // before visiting these template parameters.
798 if (VisitTemplateParameters(D->getTemplateParameters()))
799 return true;
800
801 return VisitCXXRecordDecl(D->getTemplatedDecl());
802}
803
Douglas Gregor84b51d72010-09-01 20:16:53 +0000804bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
805 if (VisitTemplateParameters(D->getTemplateParameters()))
806 return true;
807
808 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
809 VisitTemplateArgumentLoc(D->getDefaultArgument()))
810 return true;
811
812 return false;
813}
814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000816 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
817 if (Visit(TSInfo->getTypeLoc()))
818 return true;
819
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000820 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000821 PEnd = ND->param_end();
822 P != PEnd; ++P) {
823 if (Visit(MakeCXCursor(*P, TU)))
824 return true;
825 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000826
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000827 if (ND->isThisDeclarationADefinition() &&
828 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
829 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000830
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000831 return false;
832}
833
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000834namespace {
835 struct ContainerDeclsSort {
836 SourceManager &SM;
837 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
838 bool operator()(Decl *A, Decl *B) {
839 SourceLocation L_A = A->getLocStart();
840 SourceLocation L_B = B->getLocStart();
841 assert(L_A.isValid() && L_B.isValid());
842 return SM.isBeforeInTranslationUnit(L_A, L_B);
843 }
844 };
845}
846
Douglas Gregora59e3902010-01-21 23:27:09 +0000847bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000848 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
849 // an @implementation can lexically contain Decls that are not properly
850 // nested in the AST. When we identify such cases, we need to retrofit
851 // this nesting here.
852 if (!DI_current)
853 return VisitDeclContext(D);
854
855 // Scan the Decls that immediately come after the container
856 // in the current DeclContext. If any fall within the
857 // container's lexical region, stash them into a vector
858 // for later processing.
859 llvm::SmallVector<Decl *, 24> DeclsInContainer;
860 SourceLocation EndLoc = D->getSourceRange().getEnd();
861 SourceManager &SM = TU->getSourceManager();
862 if (EndLoc.isValid()) {
863 DeclContext::decl_iterator next = *DI_current;
864 while (++next != DE_current) {
865 Decl *D_next = *next;
866 if (!D_next)
867 break;
868 SourceLocation L = D_next->getLocStart();
869 if (!L.isValid())
870 break;
871 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
872 *DI_current = next;
873 DeclsInContainer.push_back(D_next);
874 continue;
875 }
876 break;
877 }
878 }
879
880 // The common case.
881 if (DeclsInContainer.empty())
882 return VisitDeclContext(D);
883
884 // Get all the Decls in the DeclContext, and sort them with the
885 // additional ones we've collected. Then visit them.
886 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
887 I!=E; ++I) {
888 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000889 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
890 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000891 continue;
892 DeclsInContainer.push_back(subDecl);
893 }
894
895 // Now sort the Decls so that they appear in lexical order.
896 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
897 ContainerDeclsSort(SM));
898
899 // Now visit the decls.
900 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
901 E = DeclsInContainer.end(); I != E; ++I) {
902 CXCursor Cursor = MakeCXCursor(*I, TU);
903 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
904 if (!V.hasValue())
905 continue;
906 if (!V.getValue())
907 return false;
908 if (Visit(Cursor, true))
909 return true;
910 }
911 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000912}
913
Douglas Gregorb1373d02010-01-20 20:59:29 +0000914bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000915 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
916 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000917 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000918
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000919 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
920 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
921 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000922 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000923 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000924
Douglas Gregora59e3902010-01-21 23:27:09 +0000925 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000926}
927
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000928bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
929 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
930 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
931 E = PID->protocol_end(); I != E; ++I, ++PL)
932 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000935 return VisitObjCContainerDecl(PID);
936}
937
Ted Kremenek23173d72010-05-18 21:09:07 +0000938bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000939 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000940 return true;
941
Ted Kremenek23173d72010-05-18 21:09:07 +0000942 // FIXME: This implements a workaround with @property declarations also being
943 // installed in the DeclContext for the @interface. Eventually this code
944 // should be removed.
945 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
946 if (!CDecl || !CDecl->IsClassExtension())
947 return false;
948
949 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
950 if (!ID)
951 return false;
952
953 IdentifierInfo *PropertyId = PD->getIdentifier();
954 ObjCPropertyDecl *prevDecl =
955 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
956
957 if (!prevDecl)
958 return false;
959
960 // Visit synthesized methods since they will be skipped when visiting
961 // the @interface.
962 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000963 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000964 if (Visit(MakeCXCursor(MD, TU)))
965 return true;
966
967 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000968 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000969 if (Visit(MakeCXCursor(MD, TU)))
970 return true;
971
972 return false;
973}
974
Douglas Gregorb1373d02010-01-20 20:59:29 +0000975bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000976 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000977 if (D->getSuperClass() &&
978 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000979 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000980 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000981 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000982
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000983 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
984 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
985 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000986 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000987 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000988
Douglas Gregora59e3902010-01-21 23:27:09 +0000989 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000990}
991
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000992bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
993 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000994}
995
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000996bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000997 // 'ID' could be null when dealing with invalid code.
998 if (ObjCInterfaceDecl *ID = D->getClassInterface())
999 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1000 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001001
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001002 return VisitObjCImplDecl(D);
1003}
1004
1005bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1006#if 0
1007 // Issue callbacks for super class.
1008 // FIXME: No source location information!
1009 if (D->getSuperClass() &&
1010 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001011 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001012 TU)))
1013 return true;
1014#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001016 return VisitObjCImplDecl(D);
1017}
1018
1019bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1020 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1021 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1022 E = D->protocol_end();
1023 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001024 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001025 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026
1027 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001028}
1029
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001030bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1031 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1032 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001035 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001036}
1037
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001038bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1039 return VisitDeclContext(D);
1040}
1041
Douglas Gregor69319002010-08-31 23:48:11 +00001042bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001043 // Visit nested-name-specifier.
1044 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1045 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1046 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001047
1048 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1049 D->getTargetNameLoc(), TU));
1050}
1051
Douglas Gregor7e242562010-09-01 19:52:22 +00001052bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001053 // Visit nested-name-specifier.
1054 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1055 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1056 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001057
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001058 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1059 return true;
1060
Douglas Gregor7e242562010-09-01 19:52:22 +00001061 return VisitDeclarationNameInfo(D->getNameInfo());
1062}
1063
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001064bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001065 // Visit nested-name-specifier.
1066 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1067 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1068 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001069
1070 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1071 D->getIdentLocation(), TU));
1072}
1073
Douglas Gregor7e242562010-09-01 19:52:22 +00001074bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001075 // Visit nested-name-specifier.
1076 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1077 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1078 return true;
1079
Douglas Gregor7e242562010-09-01 19:52:22 +00001080 return VisitDeclarationNameInfo(D->getNameInfo());
1081}
1082
1083bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1084 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001085 // Visit nested-name-specifier.
1086 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1087 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1088 return true;
1089
Douglas Gregor7e242562010-09-01 19:52:22 +00001090 return false;
1091}
1092
Douglas Gregor01829d32010-08-31 14:41:23 +00001093bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1094 switch (Name.getName().getNameKind()) {
1095 case clang::DeclarationName::Identifier:
1096 case clang::DeclarationName::CXXLiteralOperatorName:
1097 case clang::DeclarationName::CXXOperatorName:
1098 case clang::DeclarationName::CXXUsingDirective:
1099 return false;
1100
1101 case clang::DeclarationName::CXXConstructorName:
1102 case clang::DeclarationName::CXXDestructorName:
1103 case clang::DeclarationName::CXXConversionFunctionName:
1104 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1105 return Visit(TSInfo->getTypeLoc());
1106 return false;
1107
1108 case clang::DeclarationName::ObjCZeroArgSelector:
1109 case clang::DeclarationName::ObjCOneArgSelector:
1110 case clang::DeclarationName::ObjCMultiArgSelector:
1111 // FIXME: Per-identifier location info?
1112 return false;
1113 }
1114
1115 return false;
1116}
1117
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1119 SourceRange Range) {
1120 // FIXME: This whole routine is a hack to work around the lack of proper
1121 // source information in nested-name-specifiers (PR5791). Since we do have
1122 // a beginning source location, we can visit the first component of the
1123 // nested-name-specifier, if it's a single-token component.
1124 if (!NNS)
1125 return false;
1126
1127 // Get the first component in the nested-name-specifier.
1128 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1129 NNS = Prefix;
1130
1131 switch (NNS->getKind()) {
1132 case NestedNameSpecifier::Namespace:
1133 // FIXME: The token at this source location might actually have been a
1134 // namespace alias, but we don't model that. Lame!
1135 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1136 TU));
1137
1138 case NestedNameSpecifier::TypeSpec: {
1139 // If the type has a form where we know that the beginning of the source
1140 // range matches up with a reference cursor. Visit the appropriate reference
1141 // cursor.
1142 Type *T = NNS->getAsType();
1143 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1144 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1145 if (const TagType *Tag = dyn_cast<TagType>(T))
1146 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1147 if (const TemplateSpecializationType *TST
1148 = dyn_cast<TemplateSpecializationType>(T))
1149 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1150 break;
1151 }
1152
1153 case NestedNameSpecifier::TypeSpecWithTemplate:
1154 case NestedNameSpecifier::Global:
1155 case NestedNameSpecifier::Identifier:
1156 break;
1157 }
1158
1159 return false;
1160}
1161
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001162bool CursorVisitor::VisitTemplateParameters(
1163 const TemplateParameterList *Params) {
1164 if (!Params)
1165 return false;
1166
1167 for (TemplateParameterList::const_iterator P = Params->begin(),
1168 PEnd = Params->end();
1169 P != PEnd; ++P) {
1170 if (Visit(MakeCXCursor(*P, TU)))
1171 return true;
1172 }
1173
1174 return false;
1175}
1176
Douglas Gregor0b36e612010-08-31 20:37:03 +00001177bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1178 switch (Name.getKind()) {
1179 case TemplateName::Template:
1180 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1181
1182 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001183 // Visit the overloaded template set.
1184 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1185 return true;
1186
Douglas Gregor0b36e612010-08-31 20:37:03 +00001187 return false;
1188
1189 case TemplateName::DependentTemplate:
1190 // FIXME: Visit nested-name-specifier.
1191 return false;
1192
1193 case TemplateName::QualifiedTemplate:
1194 // FIXME: Visit nested-name-specifier.
1195 return Visit(MakeCursorTemplateRef(
1196 Name.getAsQualifiedTemplateName()->getDecl(),
1197 Loc, TU));
1198 }
1199
1200 return false;
1201}
1202
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001203bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1204 switch (TAL.getArgument().getKind()) {
1205 case TemplateArgument::Null:
1206 case TemplateArgument::Integral:
1207 return false;
1208
1209 case TemplateArgument::Pack:
1210 // FIXME: Implement when variadic templates come along.
1211 return false;
1212
1213 case TemplateArgument::Type:
1214 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1215 return Visit(TSInfo->getTypeLoc());
1216 return false;
1217
1218 case TemplateArgument::Declaration:
1219 if (Expr *E = TAL.getSourceDeclExpression())
1220 return Visit(MakeCXCursor(E, StmtParent, TU));
1221 return false;
1222
1223 case TemplateArgument::Expression:
1224 if (Expr *E = TAL.getSourceExpression())
1225 return Visit(MakeCXCursor(E, StmtParent, TU));
1226 return false;
1227
1228 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001229 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1230 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001231 }
1232
1233 return false;
1234}
1235
Ted Kremeneka0536d82010-05-07 01:04:29 +00001236bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1237 return VisitDeclContext(D);
1238}
1239
Douglas Gregor01829d32010-08-31 14:41:23 +00001240bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1241 return Visit(TL.getUnqualifiedLoc());
1242}
1243
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001244bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1245 ASTContext &Context = TU->getASTContext();
1246
1247 // Some builtin types (such as Objective-C's "id", "sel", and
1248 // "Class") have associated declarations. Create cursors for those.
1249 QualType VisitType;
1250 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001251 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001252 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001253 case BuiltinType::Char_U:
1254 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001255 case BuiltinType::Char16:
1256 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001257 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001258 case BuiltinType::UInt:
1259 case BuiltinType::ULong:
1260 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001261 case BuiltinType::UInt128:
1262 case BuiltinType::Char_S:
1263 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001264 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001265 case BuiltinType::Short:
1266 case BuiltinType::Int:
1267 case BuiltinType::Long:
1268 case BuiltinType::LongLong:
1269 case BuiltinType::Int128:
1270 case BuiltinType::Float:
1271 case BuiltinType::Double:
1272 case BuiltinType::LongDouble:
1273 case BuiltinType::NullPtr:
1274 case BuiltinType::Overload:
1275 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277
1278 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001279 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001280
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001281 case BuiltinType::ObjCId:
1282 VisitType = Context.getObjCIdType();
1283 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001284
1285 case BuiltinType::ObjCClass:
1286 VisitType = Context.getObjCClassType();
1287 break;
1288
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001289 case BuiltinType::ObjCSel:
1290 VisitType = Context.getObjCSelType();
1291 break;
1292 }
1293
1294 if (!VisitType.isNull()) {
1295 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001296 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001297 TU));
1298 }
1299
1300 return false;
1301}
1302
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001303bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1304 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1305}
1306
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001307bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1308 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1309}
1310
1311bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1312 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1313}
1314
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001315bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001316 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001317 // no context information with which we can match up the depth/index in the
1318 // type to the appropriate
1319 return false;
1320}
1321
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001322bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1323 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1324 return true;
1325
John McCallc12c5bb2010-05-15 11:32:37 +00001326 return false;
1327}
1328
1329bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1330 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1331 return true;
1332
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1334 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1335 TU)))
1336 return true;
1337 }
1338
1339 return false;
1340}
1341
1342bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001343 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001344}
1345
1346bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1347 return Visit(TL.getPointeeLoc());
1348}
1349
1350bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1351 return Visit(TL.getPointeeLoc());
1352}
1353
1354bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1355 return Visit(TL.getPointeeLoc());
1356}
1357
1358bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001359 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001360}
1361
1362bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001363 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001364}
1365
Douglas Gregor01829d32010-08-31 14:41:23 +00001366bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1367 bool SkipResultType) {
1368 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001369 return true;
1370
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001371 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001372 if (Decl *D = TL.getArg(I))
1373 if (Visit(MakeCXCursor(D, TU)))
1374 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001375
1376 return false;
1377}
1378
1379bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1380 if (Visit(TL.getElementLoc()))
1381 return true;
1382
1383 if (Expr *Size = TL.getSizeExpr())
1384 return Visit(MakeCXCursor(Size, StmtParent, TU));
1385
1386 return false;
1387}
1388
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001389bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1390 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001391 // Visit the template name.
1392 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1393 TL.getTemplateNameLoc()))
1394 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001395
1396 // Visit the template arguments.
1397 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1398 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1399 return true;
1400
1401 return false;
1402}
1403
Douglas Gregor2332c112010-01-21 20:48:56 +00001404bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1405 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1406}
1407
1408bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1409 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1410 return Visit(TSInfo->getTypeLoc());
1411
1412 return false;
1413}
1414
Douglas Gregora59e3902010-01-21 23:27:09 +00001415bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001416 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001417}
1418
Ted Kremenek3064ef92010-08-27 21:34:58 +00001419bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1420 if (D->isDefinition()) {
1421 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1422 E = D->bases_end(); I != E; ++I) {
1423 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1424 return true;
1425 }
1426 }
1427
1428 return VisitTagDecl(D);
1429}
1430
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001431bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001432 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001433 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1434 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001435
1436 // Visit the components of the offsetof expression.
1437 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1438 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1439 const OffsetOfNode &Node = E->getComponent(I);
1440 switch (Node.getKind()) {
1441 case OffsetOfNode::Array:
1442 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1443 StmtParent, TU)))
1444 return true;
1445 break;
1446
1447 case OffsetOfNode::Field:
1448 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1449 TU)))
1450 return true;
1451 break;
1452
1453 case OffsetOfNode::Identifier:
1454 case OffsetOfNode::Base:
1455 continue;
1456 }
1457 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001458
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001459 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001460}
1461
Douglas Gregor336fd812010-01-23 00:40:08 +00001462bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1463 if (E->isArgumentType()) {
1464 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1465 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001466
Douglas Gregor336fd812010-01-23 00:40:08 +00001467 return false;
1468 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001469
Douglas Gregor336fd812010-01-23 00:40:08 +00001470 return VisitExpr(E);
1471}
1472
Douglas Gregor36897b02010-09-10 00:22:18 +00001473bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1474 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1475}
1476
Douglas Gregor648220e2010-08-10 15:02:34 +00001477bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1478 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1479 Visit(E->getArgTInfo2()->getTypeLoc());
1480}
1481
1482bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1483 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1484 return true;
1485
1486 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1487}
1488
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001489bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1490 // Visit the designators.
1491 typedef DesignatedInitExpr::Designator Designator;
1492 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1493 DEnd = E->designators_end();
1494 D != DEnd; ++D) {
1495 if (D->isFieldDesignator()) {
1496 if (FieldDecl *Field = D->getField())
1497 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1498 return true;
1499
1500 continue;
1501 }
1502
1503 if (D->isArrayDesignator()) {
1504 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1505 return true;
1506
1507 continue;
1508 }
1509
1510 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1511 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1512 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1513 return true;
1514 }
1515
1516 // Visit the initializer value itself.
1517 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1518}
1519
Douglas Gregor94802292010-09-02 21:20:16 +00001520bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1521 if (E->isTypeOperand()) {
1522 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1523 return Visit(TSInfo->getTypeLoc());
1524
1525 return false;
1526 }
1527
1528 return VisitExpr(E);
1529}
1530
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001531bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1532 if (E->isTypeOperand()) {
1533 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1534 return Visit(TSInfo->getTypeLoc());
1535
1536 return false;
1537 }
1538
1539 return VisitExpr(E);
1540}
1541
Douglas Gregorab6677e2010-09-08 00:15:04 +00001542bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1543 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1544 return Visit(TSInfo->getTypeLoc());
1545
1546 return false;
1547}
1548
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001549bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1550 // Visit base expression.
1551 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1552 return true;
1553
1554 // Visit the nested-name-specifier.
1555 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1556 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1557 return true;
1558
1559 // Visit the scope type that looks disturbingly like the nested-name-specifier
1560 // but isn't.
1561 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1562 if (Visit(TSInfo->getTypeLoc()))
1563 return true;
1564
1565 // Visit the name of the type being destroyed.
1566 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1567 if (Visit(TSInfo->getTypeLoc()))
1568 return true;
1569
1570 return false;
1571}
1572
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001573bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1574 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1575}
1576
Douglas Gregorbfebed22010-09-03 17:24:10 +00001577bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1578 DependentScopeDeclRefExpr *E) {
1579 // Visit the nested-name-specifier.
1580 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1581 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1582 return true;
1583
1584 // Visit the declaration name.
1585 if (VisitDeclarationNameInfo(E->getNameInfo()))
1586 return true;
1587
1588 // Visit the explicitly-specified template arguments.
1589 if (const ExplicitTemplateArgumentList *ArgList
1590 = E->getOptionalExplicitTemplateArgs()) {
1591 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1592 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1593 Arg != ArgEnd; ++Arg) {
1594 if (VisitTemplateArgumentLoc(*Arg))
1595 return true;
1596 }
1597 }
1598
1599 return false;
1600}
1601
Douglas Gregorab6677e2010-09-08 00:15:04 +00001602bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1603 CXXUnresolvedConstructExpr *E) {
1604 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1605 if (Visit(TSInfo->getTypeLoc()))
1606 return true;
1607
1608 return VisitExpr(E);
1609}
1610
Douglas Gregor25d63622010-09-03 17:35:34 +00001611bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1612 CXXDependentScopeMemberExpr *E) {
1613 // Visit the base expression, if there is one.
1614 if (!E->isImplicitAccess() &&
1615 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1616 return true;
1617
1618 // Visit the nested-name-specifier.
1619 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1620 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1621 return true;
1622
1623 // Visit the declaration name.
1624 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1625 return true;
1626
1627 // Visit the explicitly-specified template arguments.
1628 if (const ExplicitTemplateArgumentList *ArgList
1629 = E->getOptionalExplicitTemplateArgs()) {
1630 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1631 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1632 Arg != ArgEnd; ++Arg) {
1633 if (VisitTemplateArgumentLoc(*Arg))
1634 return true;
1635 }
1636 }
1637
1638 return false;
1639}
1640
Ted Kremenek09dfa372010-02-18 05:46:33 +00001641bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001642 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1643 i != e; ++i)
1644 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001645 return true;
1646
1647 return false;
1648}
1649
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001650//===----------------------------------------------------------------------===//
1651// Data-recursive visitor methods.
1652//===----------------------------------------------------------------------===//
1653
Ted Kremenek28a71942010-11-13 00:36:47 +00001654namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001655#define DEF_JOB(NAME, DATA, KIND)\
1656class NAME : public VisitorJob {\
1657public:\
1658 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1659 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1660 DATA *get() const { return static_cast<DATA*>(dataA); }\
1661};
1662
1663DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1664DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001665DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001666DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1667#undef DEF_JOB
1668
1669class DeclVisit : public VisitorJob {
1670public:
1671 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1672 VisitorJob(parent, VisitorJob::DeclVisitKind,
1673 d, isFirst ? (void*) 1 : (void*) 0) {}
1674 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001675 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001676 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001677 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001678 bool isFirst() const { return dataB ? true : false; }
1679};
1680
1681class TypeLocVisit : public VisitorJob {
1682public:
1683 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1684 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1685 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1686
1687 static bool classof(const VisitorJob *VJ) {
1688 return VJ->getKind() == TypeLocVisitKind;
1689 }
1690
Ted Kremenek82f3c502010-11-15 22:23:26 +00001691 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001692 QualType T = QualType::getFromOpaquePtr(dataA);
1693 return TypeLoc(T, dataB);
1694 }
1695};
1696
Ted Kremenek28a71942010-11-13 00:36:47 +00001697class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1698 VisitorWorkList &WL;
1699 CXCursor Parent;
1700public:
1701 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1702 : WL(wl), Parent(parent) {}
1703
Ted Kremenek73d15c42010-11-13 01:09:29 +00001704 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001705 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001706 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001707 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1708 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001709 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001710 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001711 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001712 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001713 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1714 void VisitForStmt(ForStmt *FS);
1715 void VisitIfStmt(IfStmt *If);
1716 void VisitInitListExpr(InitListExpr *IE);
1717 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001718 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001719 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1720 void VisitOverloadExpr(OverloadExpr *E);
1721 void VisitStmt(Stmt *S);
1722 void VisitSwitchStmt(SwitchStmt *S);
1723 void VisitWhileStmt(WhileStmt *W);
1724 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1725
1726private:
1727 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001728 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001729 void AddTypeLoc(TypeSourceInfo *TI);
1730 void EnqueueChildren(Stmt *S);
1731};
1732} // end anonyous namespace
1733
1734void EnqueueVisitor::AddStmt(Stmt *S) {
1735 if (S)
1736 WL.push_back(StmtVisit(S, Parent));
1737}
Ted Kremenek035dc412010-11-13 00:36:50 +00001738void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001739 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001740 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001741}
1742void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1743 if (TI)
1744 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1745 }
1746void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001747 unsigned size = WL.size();
1748 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1749 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001750 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001751 }
1752 if (size == WL.size())
1753 return;
1754 // Now reverse the entries we just added. This will match the DFS
1755 // ordering performed by the worklist.
1756 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1757 std::reverse(I, E);
1758}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001759void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1760 AddDecl(B->getBlockDecl());
1761}
Ted Kremenek28a71942010-11-13 00:36:47 +00001762void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1763 EnqueueChildren(E);
1764 AddTypeLoc(E->getTypeSourceInfo());
1765}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001766void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1767 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1768 E = S->body_rend(); I != E; ++I) {
1769 AddStmt(*I);
1770 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001771}
1772void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1773 // Enqueue the initializer or constructor arguments.
1774 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1775 AddStmt(E->getConstructorArg(I-1));
1776 // Enqueue the array size, if any.
1777 AddStmt(E->getArraySize());
1778 // Enqueue the allocated type.
1779 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1780 // Enqueue the placement arguments.
1781 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1782 AddStmt(E->getPlacementArg(I-1));
1783}
Ted Kremenek28a71942010-11-13 00:36:47 +00001784void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001785 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1786 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001787 AddStmt(CE->getCallee());
1788 AddStmt(CE->getArg(0));
1789}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001790void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1791 EnqueueChildren(E);
1792 AddTypeLoc(E->getTypeSourceInfo());
1793}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001794void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1795 WL.push_back(DeclRefExprParts(DR, Parent));
1796}
Ted Kremenek035dc412010-11-13 00:36:50 +00001797void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1798 unsigned size = WL.size();
1799 bool isFirst = true;
1800 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1801 D != DEnd; ++D) {
1802 AddDecl(*D, isFirst);
1803 isFirst = false;
1804 }
1805 if (size == WL.size())
1806 return;
1807 // Now reverse the entries we just added. This will match the DFS
1808 // ordering performed by the worklist.
1809 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1810 std::reverse(I, E);
1811}
Ted Kremenek28a71942010-11-13 00:36:47 +00001812void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1813 EnqueueChildren(E);
1814 AddTypeLoc(E->getTypeInfoAsWritten());
1815}
1816void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1817 AddStmt(FS->getBody());
1818 AddStmt(FS->getInc());
1819 AddStmt(FS->getCond());
1820 AddDecl(FS->getConditionVariable());
1821 AddStmt(FS->getInit());
1822}
1823void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1824 AddStmt(If->getElse());
1825 AddStmt(If->getThen());
1826 AddStmt(If->getCond());
1827 AddDecl(If->getConditionVariable());
1828}
1829void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1830 // We care about the syntactic form of the initializer list, only.
1831 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1832 IE = Syntactic;
1833 EnqueueChildren(IE);
1834}
1835void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1836 WL.push_back(MemberExprParts(M, Parent));
1837 AddStmt(M->getBase());
1838}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001839void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1840 AddTypeLoc(E->getEncodedTypeSourceInfo());
1841}
Ted Kremenek28a71942010-11-13 00:36:47 +00001842void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1843 EnqueueChildren(M);
1844 AddTypeLoc(M->getClassReceiverTypeInfo());
1845}
1846void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001847 WL.push_back(OverloadExprParts(E, Parent));
1848}
Ted Kremenek28a71942010-11-13 00:36:47 +00001849void EnqueueVisitor::VisitStmt(Stmt *S) {
1850 EnqueueChildren(S);
1851}
1852void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1853 AddStmt(S->getBody());
1854 AddStmt(S->getCond());
1855 AddDecl(S->getConditionVariable());
1856}
1857void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1858 AddStmt(W->getBody());
1859 AddStmt(W->getCond());
1860 AddDecl(W->getConditionVariable());
1861}
1862void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1863 VisitOverloadExpr(U);
1864 if (!U->isImplicitAccess())
1865 AddStmt(U->getBase());
1866}
Ted Kremenek60458782010-11-12 21:34:16 +00001867
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001868void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001869 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001870}
1871
1872bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1873 if (RegionOfInterest.isValid()) {
1874 SourceRange Range = getRawCursorExtent(C);
1875 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1876 return false;
1877 }
1878 return true;
1879}
1880
1881bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1882 while (!WL.empty()) {
1883 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001884 VisitorJob LI = WL.back();
1885 WL.pop_back();
1886
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001887 // Set the Parent field, then back to its old value once we're done.
1888 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1889
1890 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001891 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001892 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001893 if (!D)
1894 continue;
1895
1896 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001897 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001898 return true;
1899
1900 continue;
1901 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001902 case VisitorJob::TypeLocVisitKind: {
1903 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001904 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001905 return true;
1906 continue;
1907 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001908 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001909 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001910 if (!S)
1911 continue;
1912
Ted Kremenekf1107452010-11-12 18:26:56 +00001913 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001914 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1915
1916 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001917 case Stmt::GotoStmtClass: {
1918 GotoStmt *GS = cast<GotoStmt>(S);
1919 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1920 GS->getLabelLoc(), TU))) {
1921 return true;
1922 }
1923 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001924 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001925 // Cases not yet handled by the data-recursion
1926 // algorithm.
1927 case Stmt::OffsetOfExprClass:
1928 case Stmt::SizeOfAlignOfExprClass:
1929 case Stmt::AddrLabelExprClass:
1930 case Stmt::TypesCompatibleExprClass:
1931 case Stmt::VAArgExprClass:
1932 case Stmt::DesignatedInitExprClass:
1933 case Stmt::CXXTypeidExprClass:
1934 case Stmt::CXXUuidofExprClass:
1935 case Stmt::CXXScalarValueInitExprClass:
1936 case Stmt::CXXPseudoDestructorExprClass:
1937 case Stmt::UnaryTypeTraitExprClass:
1938 case Stmt::DependentScopeDeclRefExprClass:
1939 case Stmt::CXXUnresolvedConstructExprClass:
1940 case Stmt::CXXDependentScopeMemberExprClass:
1941 if (Visit(Cursor))
1942 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001943 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001944 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001945 if (!IsInRegionOfInterest(Cursor))
1946 continue;
1947 switch (Visitor(Cursor, Parent, ClientData)) {
1948 case CXChildVisit_Break:
1949 return true;
1950 case CXChildVisit_Continue:
1951 break;
1952 case CXChildVisit_Recurse:
1953 EnqueueWorkList(WL, S);
1954 break;
1955 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001956 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001957 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001958 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001959 }
1960 case VisitorJob::MemberExprPartsKind: {
1961 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001962 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001963
1964 // Visit the nested-name-specifier
1965 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1966 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1967 return true;
1968
1969 // Visit the declaration name.
1970 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1971 return true;
1972
1973 // Visit the explicitly-specified template arguments, if any.
1974 if (M->hasExplicitTemplateArgs()) {
1975 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1976 *ArgEnd = Arg + M->getNumTemplateArgs();
1977 Arg != ArgEnd; ++Arg) {
1978 if (VisitTemplateArgumentLoc(*Arg))
1979 return true;
1980 }
1981 }
1982 continue;
1983 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001984 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001985 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001986 // Visit nested-name-specifier, if present.
1987 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
1988 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
1989 return true;
1990 // Visit declaration name.
1991 if (VisitDeclarationNameInfo(DR->getNameInfo()))
1992 return true;
1993 // Visit explicitly-specified template arguments.
1994 if (DR->hasExplicitTemplateArgs()) {
1995 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
1996 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1997 *ArgEnd = Arg + Args.NumTemplateArgs;
1998 Arg != ArgEnd; ++Arg)
1999 if (VisitTemplateArgumentLoc(*Arg))
2000 return true;
2001 }
2002 continue;
2003 }
Ted Kremenek60458782010-11-12 21:34:16 +00002004 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002005 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002006 // Visit the nested-name-specifier.
2007 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2008 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2009 return true;
2010 // Visit the declaration name.
2011 if (VisitDeclarationNameInfo(O->getNameInfo()))
2012 return true;
2013 // Visit the overloaded declaration reference.
2014 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2015 return true;
2016 // Visit the explicitly-specified template arguments.
2017 if (const ExplicitTemplateArgumentList *ArgList
2018 = O->getOptionalExplicitTemplateArgs()) {
2019 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2020 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2021 Arg != ArgEnd; ++Arg) {
2022 if (VisitTemplateArgumentLoc(*Arg))
2023 return true;
2024 }
2025 }
2026 continue;
2027 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002028 }
2029 }
2030 return false;
2031}
2032
2033bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002034 VisitorWorkList *WL = 0;
2035 if (!WorkListFreeList.empty()) {
2036 WL = WorkListFreeList.back();
2037 WL->clear();
2038 WorkListFreeList.pop_back();
2039 }
2040 else {
2041 WL = new VisitorWorkList();
2042 WorkListCache.push_back(WL);
2043 }
2044 EnqueueWorkList(*WL, S);
2045 bool result = RunVisitorWorkList(*WL);
2046 WorkListFreeList.push_back(WL);
2047 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002048}
2049
2050//===----------------------------------------------------------------------===//
2051// Misc. API hooks.
2052//===----------------------------------------------------------------------===//
2053
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002054static llvm::sys::Mutex EnableMultithreadingMutex;
2055static bool EnabledMultithreading;
2056
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002057extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002058CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2059 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002060 // Disable pretty stack trace functionality, which will otherwise be a very
2061 // poor citizen of the world and set up all sorts of signal handlers.
2062 llvm::DisablePrettyStackTrace = true;
2063
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002064 // We use crash recovery to make some of our APIs more reliable, implicitly
2065 // enable it.
2066 llvm::CrashRecoveryContext::Enable();
2067
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002068 // Enable support for multithreading in LLVM.
2069 {
2070 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2071 if (!EnabledMultithreading) {
2072 llvm::llvm_start_multithreaded();
2073 EnabledMultithreading = true;
2074 }
2075 }
2076
Douglas Gregora030b7c2010-01-22 20:35:53 +00002077 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002078 if (excludeDeclarationsFromPCH)
2079 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002080 if (displayDiagnostics)
2081 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002082 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002083}
2084
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002085void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002086 if (CIdx)
2087 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002088}
2089
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002090CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002091 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002092 if (!CIdx)
2093 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002094
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002095 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002096 FileSystemOptions FileSystemOpts;
2097 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002098
Douglas Gregor28019772010-04-05 23:52:57 +00002099 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002100 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002101 CXXIdx->getOnlyLocalDecls(),
2102 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002103}
2104
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002105unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002106 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002107 CXTranslationUnit_CacheCompletionResults |
2108 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002109}
2110
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002111CXTranslationUnit
2112clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2113 const char *source_filename,
2114 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002115 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002116 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002117 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002118 return clang_parseTranslationUnit(CIdx, source_filename,
2119 command_line_args, num_command_line_args,
2120 unsaved_files, num_unsaved_files,
2121 CXTranslationUnit_DetailedPreprocessingRecord);
2122}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002123
2124struct ParseTranslationUnitInfo {
2125 CXIndex CIdx;
2126 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002127 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002128 int num_command_line_args;
2129 struct CXUnsavedFile *unsaved_files;
2130 unsigned num_unsaved_files;
2131 unsigned options;
2132 CXTranslationUnit result;
2133};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002134static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002135 ParseTranslationUnitInfo *PTUI =
2136 static_cast<ParseTranslationUnitInfo*>(UserData);
2137 CXIndex CIdx = PTUI->CIdx;
2138 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002139 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002140 int num_command_line_args = PTUI->num_command_line_args;
2141 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2142 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2143 unsigned options = PTUI->options;
2144 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002145
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002146 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002147 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002149 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2150
Douglas Gregor44c181a2010-07-23 00:33:23 +00002151 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002152 bool CompleteTranslationUnit
2153 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002154 bool CacheCodeCompetionResults
2155 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002156 bool CXXPrecompilePreamble
2157 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2158 bool CXXChainedPCH
2159 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002160
Douglas Gregor5352ac02010-01-28 00:27:43 +00002161 // Configure the diagnostics.
2162 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002163 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2164 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002165
Douglas Gregor4db64a42010-01-23 00:14:00 +00002166 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2167 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002168 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002169 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002170 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002171 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2172 Buffer));
2173 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002174
Douglas Gregorb10daed2010-10-11 16:52:23 +00002175 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002176
Ted Kremenek139ba862009-10-22 00:03:57 +00002177 // The 'source_filename' argument is optional. If the caller does not
2178 // specify it then it is assumed that the source file is specified
2179 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002180 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002181 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002182
2183 // Since the Clang C library is primarily used by batch tools dealing with
2184 // (often very broken) source code, where spell-checking can have a
2185 // significant negative impact on performance (particularly when
2186 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002187 // Only do this if we haven't found a spell-checking-related argument.
2188 bool FoundSpellCheckingArgument = false;
2189 for (int I = 0; I != num_command_line_args; ++I) {
2190 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2191 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2192 FoundSpellCheckingArgument = true;
2193 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002194 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002195 }
2196 if (!FoundSpellCheckingArgument)
2197 Args.push_back("-fno-spell-checking");
2198
2199 Args.insert(Args.end(), command_line_args,
2200 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002201
Douglas Gregor44c181a2010-07-23 00:33:23 +00002202 // Do we need the detailed preprocessing record?
2203 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002204 Args.push_back("-Xclang");
2205 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002206 }
2207
Douglas Gregorb10daed2010-10-11 16:52:23 +00002208 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002209 llvm::OwningPtr<ASTUnit> Unit(
2210 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2211 Diags,
2212 CXXIdx->getClangResourcesPath(),
2213 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002214 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002215 RemappedFiles.data(),
2216 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002217 PrecompilePreamble,
2218 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002219 CacheCodeCompetionResults,
2220 CXXPrecompilePreamble,
2221 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002222
Douglas Gregorb10daed2010-10-11 16:52:23 +00002223 if (NumErrors != Diags->getNumErrors()) {
2224 // Make sure to check that 'Unit' is non-NULL.
2225 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2226 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2227 DEnd = Unit->stored_diag_end();
2228 D != DEnd; ++D) {
2229 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2230 CXString Msg = clang_formatDiagnostic(&Diag,
2231 clang_defaultDiagnosticDisplayOptions());
2232 fprintf(stderr, "%s\n", clang_getCString(Msg));
2233 clang_disposeString(Msg);
2234 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002235#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002236 // On Windows, force a flush, since there may be multiple copies of
2237 // stderr and stdout in the file system, all with different buffers
2238 // but writing to the same device.
2239 fflush(stderr);
2240#endif
2241 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002242 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002243
Douglas Gregorb10daed2010-10-11 16:52:23 +00002244 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002245}
2246CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2247 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002248 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002249 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002250 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002251 unsigned num_unsaved_files,
2252 unsigned options) {
2253 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002254 num_command_line_args, unsaved_files,
2255 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002256 llvm::CrashRecoveryContext CRC;
2257
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002258 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002259 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2260 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2261 fprintf(stderr, " 'command_line_args' : [");
2262 for (int i = 0; i != num_command_line_args; ++i) {
2263 if (i)
2264 fprintf(stderr, ", ");
2265 fprintf(stderr, "'%s'", command_line_args[i]);
2266 }
2267 fprintf(stderr, "],\n");
2268 fprintf(stderr, " 'unsaved_files' : [");
2269 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2270 if (i)
2271 fprintf(stderr, ", ");
2272 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2273 unsaved_files[i].Length);
2274 }
2275 fprintf(stderr, "],\n");
2276 fprintf(stderr, " 'options' : %d,\n", options);
2277 fprintf(stderr, "}\n");
2278
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002279 return 0;
2280 }
2281
2282 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002283}
2284
Douglas Gregor19998442010-08-13 15:35:05 +00002285unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2286 return CXSaveTranslationUnit_None;
2287}
2288
2289int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2290 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002291 if (!TU)
2292 return 1;
2293
2294 return static_cast<ASTUnit *>(TU)->Save(FileName);
2295}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002296
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002297void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002298 if (CTUnit) {
2299 // If the translation unit has been marked as unsafe to free, just discard
2300 // it.
2301 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2302 return;
2303
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002304 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002305 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002306}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002307
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002308unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2309 return CXReparse_None;
2310}
2311
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002312struct ReparseTranslationUnitInfo {
2313 CXTranslationUnit TU;
2314 unsigned num_unsaved_files;
2315 struct CXUnsavedFile *unsaved_files;
2316 unsigned options;
2317 int result;
2318};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002319
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002320static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002321 ReparseTranslationUnitInfo *RTUI =
2322 static_cast<ReparseTranslationUnitInfo*>(UserData);
2323 CXTranslationUnit TU = RTUI->TU;
2324 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2325 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2326 unsigned options = RTUI->options;
2327 (void) options;
2328 RTUI->result = 1;
2329
Douglas Gregorabc563f2010-07-19 21:46:24 +00002330 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002331 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002332
2333 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2334 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002335
2336 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2337 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2338 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2339 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002340 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002341 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2342 Buffer));
2343 }
2344
Douglas Gregor593b0c12010-09-23 18:47:53 +00002345 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2346 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002347}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002348
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002349int clang_reparseTranslationUnit(CXTranslationUnit TU,
2350 unsigned num_unsaved_files,
2351 struct CXUnsavedFile *unsaved_files,
2352 unsigned options) {
2353 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2354 options, 0 };
2355 llvm::CrashRecoveryContext CRC;
2356
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002357 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002358 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002359 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2360 return 1;
2361 }
2362
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002363
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002364 return RTUI.result;
2365}
2366
Douglas Gregordf95a132010-08-09 20:45:32 +00002367
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002368CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002369 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002370 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002371
Steve Naroff77accc12009-09-03 18:19:54 +00002372 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002373 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002374}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002375
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002376CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002377 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002378 return Result;
2379}
2380
Ted Kremenekfb480492010-01-13 21:46:36 +00002381} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002382
Ted Kremenekfb480492010-01-13 21:46:36 +00002383//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002384// CXSourceLocation and CXSourceRange Operations.
2385//===----------------------------------------------------------------------===//
2386
Douglas Gregorb9790342010-01-22 21:44:22 +00002387extern "C" {
2388CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002389 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002390 return Result;
2391}
2392
2393unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002394 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2395 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2396 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002397}
2398
2399CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2400 CXFile file,
2401 unsigned line,
2402 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002403 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002404 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002405
Douglas Gregorb9790342010-01-22 21:44:22 +00002406 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2407 SourceLocation SLoc
2408 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002409 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002410 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002411 if (SLoc.isInvalid()) return clang_getNullLocation();
2412
2413 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2414}
2415
2416CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2417 CXFile file,
2418 unsigned offset) {
2419 if (!tu || !file)
2420 return clang_getNullLocation();
2421
2422 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2423 SourceLocation Start
2424 = CXXUnit->getSourceManager().getLocation(
2425 static_cast<const FileEntry *>(file),
2426 1, 1);
2427 if (Start.isInvalid()) return clang_getNullLocation();
2428
2429 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2430
2431 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002432
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002433 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002434}
2435
Douglas Gregor5352ac02010-01-28 00:27:43 +00002436CXSourceRange clang_getNullRange() {
2437 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2438 return Result;
2439}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002440
Douglas Gregor5352ac02010-01-28 00:27:43 +00002441CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2442 if (begin.ptr_data[0] != end.ptr_data[0] ||
2443 begin.ptr_data[1] != end.ptr_data[1])
2444 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002445
2446 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002447 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002448 return Result;
2449}
2450
Douglas Gregor46766dc2010-01-26 19:19:08 +00002451void clang_getInstantiationLocation(CXSourceLocation location,
2452 CXFile *file,
2453 unsigned *line,
2454 unsigned *column,
2455 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002456 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2457
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002458 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002459 if (file)
2460 *file = 0;
2461 if (line)
2462 *line = 0;
2463 if (column)
2464 *column = 0;
2465 if (offset)
2466 *offset = 0;
2467 return;
2468 }
2469
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002470 const SourceManager &SM =
2471 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002472 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002473
2474 if (file)
2475 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2476 if (line)
2477 *line = SM.getInstantiationLineNumber(InstLoc);
2478 if (column)
2479 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002480 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002481 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002482}
2483
Douglas Gregora9b06d42010-11-09 06:24:54 +00002484void clang_getSpellingLocation(CXSourceLocation location,
2485 CXFile *file,
2486 unsigned *line,
2487 unsigned *column,
2488 unsigned *offset) {
2489 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2490
2491 if (!location.ptr_data[0] || Loc.isInvalid()) {
2492 if (file)
2493 *file = 0;
2494 if (line)
2495 *line = 0;
2496 if (column)
2497 *column = 0;
2498 if (offset)
2499 *offset = 0;
2500 return;
2501 }
2502
2503 const SourceManager &SM =
2504 *static_cast<const SourceManager*>(location.ptr_data[0]);
2505 SourceLocation SpellLoc = Loc;
2506 if (SpellLoc.isMacroID()) {
2507 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2508 if (SimpleSpellingLoc.isFileID() &&
2509 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2510 SpellLoc = SimpleSpellingLoc;
2511 else
2512 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2513 }
2514
2515 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2516 FileID FID = LocInfo.first;
2517 unsigned FileOffset = LocInfo.second;
2518
2519 if (file)
2520 *file = (void *)SM.getFileEntryForID(FID);
2521 if (line)
2522 *line = SM.getLineNumber(FID, FileOffset);
2523 if (column)
2524 *column = SM.getColumnNumber(FID, FileOffset);
2525 if (offset)
2526 *offset = FileOffset;
2527}
2528
Douglas Gregor1db19de2010-01-19 21:36:55 +00002529CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002530 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002531 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002532 return Result;
2533}
2534
2535CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002536 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002537 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002538 return Result;
2539}
2540
Douglas Gregorb9790342010-01-22 21:44:22 +00002541} // end: extern "C"
2542
Douglas Gregor1db19de2010-01-19 21:36:55 +00002543//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002544// CXFile Operations.
2545//===----------------------------------------------------------------------===//
2546
2547extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002548CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002549 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002550 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002551
Steve Naroff88145032009-10-27 14:35:18 +00002552 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002553 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002554}
2555
2556time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002557 if (!SFile)
2558 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002559
Steve Naroff88145032009-10-27 14:35:18 +00002560 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2561 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002562}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563
Douglas Gregorb9790342010-01-22 21:44:22 +00002564CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2565 if (!tu)
2566 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002567
Douglas Gregorb9790342010-01-22 21:44:22 +00002568 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Douglas Gregorb9790342010-01-22 21:44:22 +00002570 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002571 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2572 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002573 return const_cast<FileEntry *>(File);
2574}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002575
Ted Kremenekfb480492010-01-13 21:46:36 +00002576} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002577
Ted Kremenekfb480492010-01-13 21:46:36 +00002578//===----------------------------------------------------------------------===//
2579// CXCursor Operations.
2580//===----------------------------------------------------------------------===//
2581
Ted Kremenekfb480492010-01-13 21:46:36 +00002582static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002583 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2584 return getDeclFromExpr(CE->getSubExpr());
2585
Ted Kremenekfb480492010-01-13 21:46:36 +00002586 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2587 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002588 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2589 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002590 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2591 return ME->getMemberDecl();
2592 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2593 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002594 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2595 return PRE->getProperty();
2596
Ted Kremenekfb480492010-01-13 21:46:36 +00002597 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2598 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002599 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2600 if (!CE->isElidable())
2601 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002602 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2603 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002604
Douglas Gregordb1314e2010-10-01 21:11:22 +00002605 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2606 return PE->getProtocol();
2607
Ted Kremenekfb480492010-01-13 21:46:36 +00002608 return 0;
2609}
2610
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002611static SourceLocation getLocationFromExpr(Expr *E) {
2612 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2613 return /*FIXME:*/Msg->getLeftLoc();
2614 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2615 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002616 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2617 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002618 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2619 return Member->getMemberLoc();
2620 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2621 return Ivar->getLocation();
2622 return E->getLocStart();
2623}
2624
Ted Kremenekfb480492010-01-13 21:46:36 +00002625extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002626
2627unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002628 CXCursorVisitor visitor,
2629 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002630 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002631
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002632 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2633 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002634 return CursorVis.VisitChildren(parent);
2635}
2636
David Chisnall3387c652010-11-03 14:12:26 +00002637#ifndef __has_feature
2638#define __has_feature(x) 0
2639#endif
2640#if __has_feature(blocks)
2641typedef enum CXChildVisitResult
2642 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2643
2644static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2645 CXClientData client_data) {
2646 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2647 return block(cursor, parent);
2648}
2649#else
2650// If we are compiled with a compiler that doesn't have native blocks support,
2651// define and call the block manually, so the
2652typedef struct _CXChildVisitResult
2653{
2654 void *isa;
2655 int flags;
2656 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002657 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2658 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002659} *CXCursorVisitorBlock;
2660
2661static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2662 CXClientData client_data) {
2663 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2664 return block->invoke(block, cursor, parent);
2665}
2666#endif
2667
2668
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002669unsigned clang_visitChildrenWithBlock(CXCursor parent,
2670 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002671 return clang_visitChildren(parent, visitWithBlock, block);
2672}
2673
Douglas Gregor78205d42010-01-20 21:45:58 +00002674static CXString getDeclSpelling(Decl *D) {
2675 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2676 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002677 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002678
Douglas Gregor78205d42010-01-20 21:45:58 +00002679 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002680 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002681
Douglas Gregor78205d42010-01-20 21:45:58 +00002682 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2683 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2684 // and returns different names. NamedDecl returns the class name and
2685 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002686 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002687
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002688 if (isa<UsingDirectiveDecl>(D))
2689 return createCXString("");
2690
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002691 llvm::SmallString<1024> S;
2692 llvm::raw_svector_ostream os(S);
2693 ND->printName(os);
2694
2695 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002696}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002697
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002698CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002699 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002700 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002701
Steve Narofff334b4e2009-09-02 18:26:48 +00002702 if (clang_isReference(C.kind)) {
2703 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002704 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002705 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002706 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002707 }
2708 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002709 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002710 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002711 }
2712 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002713 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002714 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002715 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002716 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002717 case CXCursor_CXXBaseSpecifier: {
2718 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2719 return createCXString(B->getType().getAsString());
2720 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002721 case CXCursor_TypeRef: {
2722 TypeDecl *Type = getCursorTypeRef(C).first;
2723 assert(Type && "Missing type decl");
2724
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002725 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2726 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002727 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002728 case CXCursor_TemplateRef: {
2729 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002730 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002731
2732 return createCXString(Template->getNameAsString());
2733 }
Douglas Gregor69319002010-08-31 23:48:11 +00002734
2735 case CXCursor_NamespaceRef: {
2736 NamedDecl *NS = getCursorNamespaceRef(C).first;
2737 assert(NS && "Missing namespace decl");
2738
2739 return createCXString(NS->getNameAsString());
2740 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002741
Douglas Gregora67e03f2010-09-09 21:42:20 +00002742 case CXCursor_MemberRef: {
2743 FieldDecl *Field = getCursorMemberRef(C).first;
2744 assert(Field && "Missing member decl");
2745
2746 return createCXString(Field->getNameAsString());
2747 }
2748
Douglas Gregor36897b02010-09-10 00:22:18 +00002749 case CXCursor_LabelRef: {
2750 LabelStmt *Label = getCursorLabelRef(C).first;
2751 assert(Label && "Missing label");
2752
2753 return createCXString(Label->getID()->getName());
2754 }
2755
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002756 case CXCursor_OverloadedDeclRef: {
2757 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2758 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2759 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2760 return createCXString(ND->getNameAsString());
2761 return createCXString("");
2762 }
2763 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2764 return createCXString(E->getName().getAsString());
2765 OverloadedTemplateStorage *Ovl
2766 = Storage.get<OverloadedTemplateStorage*>();
2767 if (Ovl->size() == 0)
2768 return createCXString("");
2769 return createCXString((*Ovl->begin())->getNameAsString());
2770 }
2771
Daniel Dunbaracca7252009-11-30 20:42:49 +00002772 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002773 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002774 }
2775 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002776
2777 if (clang_isExpression(C.kind)) {
2778 Decl *D = getDeclFromExpr(getCursorExpr(C));
2779 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002780 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002781 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002782 }
2783
Douglas Gregor36897b02010-09-10 00:22:18 +00002784 if (clang_isStatement(C.kind)) {
2785 Stmt *S = getCursorStmt(C);
2786 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2787 return createCXString(Label->getID()->getName());
2788
2789 return createCXString("");
2790 }
2791
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002792 if (C.kind == CXCursor_MacroInstantiation)
2793 return createCXString(getCursorMacroInstantiation(C)->getName()
2794 ->getNameStart());
2795
Douglas Gregor572feb22010-03-18 18:04:21 +00002796 if (C.kind == CXCursor_MacroDefinition)
2797 return createCXString(getCursorMacroDefinition(C)->getName()
2798 ->getNameStart());
2799
Douglas Gregorecdcb882010-10-20 22:00:55 +00002800 if (C.kind == CXCursor_InclusionDirective)
2801 return createCXString(getCursorInclusionDirective(C)->getFileName());
2802
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002803 if (clang_isDeclaration(C.kind))
2804 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002805
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002806 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002807}
2808
Douglas Gregor358559d2010-10-02 22:49:11 +00002809CXString clang_getCursorDisplayName(CXCursor C) {
2810 if (!clang_isDeclaration(C.kind))
2811 return clang_getCursorSpelling(C);
2812
2813 Decl *D = getCursorDecl(C);
2814 if (!D)
2815 return createCXString("");
2816
2817 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2818 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2819 D = FunTmpl->getTemplatedDecl();
2820
2821 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2822 llvm::SmallString<64> Str;
2823 llvm::raw_svector_ostream OS(Str);
2824 OS << Function->getNameAsString();
2825 if (Function->getPrimaryTemplate())
2826 OS << "<>";
2827 OS << "(";
2828 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2829 if (I)
2830 OS << ", ";
2831 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2832 }
2833
2834 if (Function->isVariadic()) {
2835 if (Function->getNumParams())
2836 OS << ", ";
2837 OS << "...";
2838 }
2839 OS << ")";
2840 return createCXString(OS.str());
2841 }
2842
2843 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2844 llvm::SmallString<64> Str;
2845 llvm::raw_svector_ostream OS(Str);
2846 OS << ClassTemplate->getNameAsString();
2847 OS << "<";
2848 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2849 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2850 if (I)
2851 OS << ", ";
2852
2853 NamedDecl *Param = Params->getParam(I);
2854 if (Param->getIdentifier()) {
2855 OS << Param->getIdentifier()->getName();
2856 continue;
2857 }
2858
2859 // There is no parameter name, which makes this tricky. Try to come up
2860 // with something useful that isn't too long.
2861 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2862 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2863 else if (NonTypeTemplateParmDecl *NTTP
2864 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2865 OS << NTTP->getType().getAsString(Policy);
2866 else
2867 OS << "template<...> class";
2868 }
2869
2870 OS << ">";
2871 return createCXString(OS.str());
2872 }
2873
2874 if (ClassTemplateSpecializationDecl *ClassSpec
2875 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2876 // If the type was explicitly written, use that.
2877 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2878 return createCXString(TSInfo->getType().getAsString(Policy));
2879
2880 llvm::SmallString<64> Str;
2881 llvm::raw_svector_ostream OS(Str);
2882 OS << ClassSpec->getNameAsString();
2883 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002884 ClassSpec->getTemplateArgs().data(),
2885 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002886 Policy);
2887 return createCXString(OS.str());
2888 }
2889
2890 return clang_getCursorSpelling(C);
2891}
2892
Ted Kremeneke68fff62010-02-17 00:41:32 +00002893CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002894 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002895 case CXCursor_FunctionDecl:
2896 return createCXString("FunctionDecl");
2897 case CXCursor_TypedefDecl:
2898 return createCXString("TypedefDecl");
2899 case CXCursor_EnumDecl:
2900 return createCXString("EnumDecl");
2901 case CXCursor_EnumConstantDecl:
2902 return createCXString("EnumConstantDecl");
2903 case CXCursor_StructDecl:
2904 return createCXString("StructDecl");
2905 case CXCursor_UnionDecl:
2906 return createCXString("UnionDecl");
2907 case CXCursor_ClassDecl:
2908 return createCXString("ClassDecl");
2909 case CXCursor_FieldDecl:
2910 return createCXString("FieldDecl");
2911 case CXCursor_VarDecl:
2912 return createCXString("VarDecl");
2913 case CXCursor_ParmDecl:
2914 return createCXString("ParmDecl");
2915 case CXCursor_ObjCInterfaceDecl:
2916 return createCXString("ObjCInterfaceDecl");
2917 case CXCursor_ObjCCategoryDecl:
2918 return createCXString("ObjCCategoryDecl");
2919 case CXCursor_ObjCProtocolDecl:
2920 return createCXString("ObjCProtocolDecl");
2921 case CXCursor_ObjCPropertyDecl:
2922 return createCXString("ObjCPropertyDecl");
2923 case CXCursor_ObjCIvarDecl:
2924 return createCXString("ObjCIvarDecl");
2925 case CXCursor_ObjCInstanceMethodDecl:
2926 return createCXString("ObjCInstanceMethodDecl");
2927 case CXCursor_ObjCClassMethodDecl:
2928 return createCXString("ObjCClassMethodDecl");
2929 case CXCursor_ObjCImplementationDecl:
2930 return createCXString("ObjCImplementationDecl");
2931 case CXCursor_ObjCCategoryImplDecl:
2932 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002933 case CXCursor_CXXMethod:
2934 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002935 case CXCursor_UnexposedDecl:
2936 return createCXString("UnexposedDecl");
2937 case CXCursor_ObjCSuperClassRef:
2938 return createCXString("ObjCSuperClassRef");
2939 case CXCursor_ObjCProtocolRef:
2940 return createCXString("ObjCProtocolRef");
2941 case CXCursor_ObjCClassRef:
2942 return createCXString("ObjCClassRef");
2943 case CXCursor_TypeRef:
2944 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002945 case CXCursor_TemplateRef:
2946 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002947 case CXCursor_NamespaceRef:
2948 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002949 case CXCursor_MemberRef:
2950 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002951 case CXCursor_LabelRef:
2952 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002953 case CXCursor_OverloadedDeclRef:
2954 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002955 case CXCursor_UnexposedExpr:
2956 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002957 case CXCursor_BlockExpr:
2958 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002959 case CXCursor_DeclRefExpr:
2960 return createCXString("DeclRefExpr");
2961 case CXCursor_MemberRefExpr:
2962 return createCXString("MemberRefExpr");
2963 case CXCursor_CallExpr:
2964 return createCXString("CallExpr");
2965 case CXCursor_ObjCMessageExpr:
2966 return createCXString("ObjCMessageExpr");
2967 case CXCursor_UnexposedStmt:
2968 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002969 case CXCursor_LabelStmt:
2970 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002971 case CXCursor_InvalidFile:
2972 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002973 case CXCursor_InvalidCode:
2974 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002975 case CXCursor_NoDeclFound:
2976 return createCXString("NoDeclFound");
2977 case CXCursor_NotImplemented:
2978 return createCXString("NotImplemented");
2979 case CXCursor_TranslationUnit:
2980 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002981 case CXCursor_UnexposedAttr:
2982 return createCXString("UnexposedAttr");
2983 case CXCursor_IBActionAttr:
2984 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002985 case CXCursor_IBOutletAttr:
2986 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002987 case CXCursor_IBOutletCollectionAttr:
2988 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002989 case CXCursor_PreprocessingDirective:
2990 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002991 case CXCursor_MacroDefinition:
2992 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002993 case CXCursor_MacroInstantiation:
2994 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002995 case CXCursor_InclusionDirective:
2996 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002997 case CXCursor_Namespace:
2998 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002999 case CXCursor_LinkageSpec:
3000 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003001 case CXCursor_CXXBaseSpecifier:
3002 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003003 case CXCursor_Constructor:
3004 return createCXString("CXXConstructor");
3005 case CXCursor_Destructor:
3006 return createCXString("CXXDestructor");
3007 case CXCursor_ConversionFunction:
3008 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003009 case CXCursor_TemplateTypeParameter:
3010 return createCXString("TemplateTypeParameter");
3011 case CXCursor_NonTypeTemplateParameter:
3012 return createCXString("NonTypeTemplateParameter");
3013 case CXCursor_TemplateTemplateParameter:
3014 return createCXString("TemplateTemplateParameter");
3015 case CXCursor_FunctionTemplate:
3016 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003017 case CXCursor_ClassTemplate:
3018 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003019 case CXCursor_ClassTemplatePartialSpecialization:
3020 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003021 case CXCursor_NamespaceAlias:
3022 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003023 case CXCursor_UsingDirective:
3024 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003025 case CXCursor_UsingDeclaration:
3026 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003027 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003028
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003029 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003030 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003031}
Steve Naroff89922f82009-08-31 00:59:03 +00003032
Ted Kremeneke68fff62010-02-17 00:41:32 +00003033enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3034 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003035 CXClientData client_data) {
3036 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003037
3038 // If our current best cursor is the construction of a temporary object,
3039 // don't replace that cursor with a type reference, because we want
3040 // clang_getCursor() to point at the constructor.
3041 if (clang_isExpression(BestCursor->kind) &&
3042 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3043 cursor.kind == CXCursor_TypeRef)
3044 return CXChildVisit_Recurse;
3045
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003046 *BestCursor = cursor;
3047 return CXChildVisit_Recurse;
3048}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003049
Douglas Gregorb9790342010-01-22 21:44:22 +00003050CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3051 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003052 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003053
Douglas Gregorb9790342010-01-22 21:44:22 +00003054 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003055 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3056
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003057 // Translate the given source location to make it point at the beginning of
3058 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003059 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003060
3061 // Guard against an invalid SourceLocation, or we may assert in one
3062 // of the following calls.
3063 if (SLoc.isInvalid())
3064 return clang_getNullCursor();
3065
Douglas Gregor40749ee2010-11-03 00:35:38 +00003066 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003067 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3068 CXXUnit->getASTContext().getLangOptions());
3069
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003070 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3071 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003072 // FIXME: Would be great to have a "hint" cursor, then walk from that
3073 // hint cursor upward until we find a cursor whose source range encloses
3074 // the region of interest, rather than starting from the translation unit.
3075 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003076 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003077 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003078 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003079 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003080
3081 if (Logging) {
3082 CXFile SearchFile;
3083 unsigned SearchLine, SearchColumn;
3084 CXFile ResultFile;
3085 unsigned ResultLine, ResultColumn;
3086 CXString SearchFileName, ResultFileName, KindSpelling;
3087 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3088
3089 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3090 0);
3091 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3092 &ResultColumn, 0);
3093 SearchFileName = clang_getFileName(SearchFile);
3094 ResultFileName = clang_getFileName(ResultFile);
3095 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3096 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3097 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3098 clang_getCString(KindSpelling),
3099 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3100 clang_disposeString(SearchFileName);
3101 clang_disposeString(ResultFileName);
3102 clang_disposeString(KindSpelling);
3103 }
3104
Ted Kremeneke68fff62010-02-17 00:41:32 +00003105 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003106}
3107
Ted Kremenek73885552009-11-17 19:28:59 +00003108CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003109 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003110}
3111
3112unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003113 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003114}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003115
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003116unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003117 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3118}
3119
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003120unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003121 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3122}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003123
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003124unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003125 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3126}
3127
Douglas Gregor97b98722010-01-19 23:20:36 +00003128unsigned clang_isExpression(enum CXCursorKind K) {
3129 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3130}
3131
3132unsigned clang_isStatement(enum CXCursorKind K) {
3133 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3134}
3135
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003136unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3137 return K == CXCursor_TranslationUnit;
3138}
3139
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003140unsigned clang_isPreprocessing(enum CXCursorKind K) {
3141 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3142}
3143
Ted Kremenekad6eff62010-03-08 21:17:29 +00003144unsigned clang_isUnexposed(enum CXCursorKind K) {
3145 switch (K) {
3146 case CXCursor_UnexposedDecl:
3147 case CXCursor_UnexposedExpr:
3148 case CXCursor_UnexposedStmt:
3149 case CXCursor_UnexposedAttr:
3150 return true;
3151 default:
3152 return false;
3153 }
3154}
3155
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003156CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003157 return C.kind;
3158}
3159
Douglas Gregor98258af2010-01-18 22:46:11 +00003160CXSourceLocation clang_getCursorLocation(CXCursor C) {
3161 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003162 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003163 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003164 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3165 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003166 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003167 }
3168
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003169 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003170 std::pair<ObjCProtocolDecl *, SourceLocation> P
3171 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003172 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003173 }
3174
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003175 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003176 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3177 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003178 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003179 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003180
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003181 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003182 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003183 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003184 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003185
3186 case CXCursor_TemplateRef: {
3187 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3188 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3189 }
3190
Douglas Gregor69319002010-08-31 23:48:11 +00003191 case CXCursor_NamespaceRef: {
3192 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3193 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3194 }
3195
Douglas Gregora67e03f2010-09-09 21:42:20 +00003196 case CXCursor_MemberRef: {
3197 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3198 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3199 }
3200
Ted Kremenek3064ef92010-08-27 21:34:58 +00003201 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003202 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3203 if (!BaseSpec)
3204 return clang_getNullLocation();
3205
3206 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3207 return cxloc::translateSourceLocation(getCursorContext(C),
3208 TSInfo->getTypeLoc().getBeginLoc());
3209
3210 return cxloc::translateSourceLocation(getCursorContext(C),
3211 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003212 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003213
Douglas Gregor36897b02010-09-10 00:22:18 +00003214 case CXCursor_LabelRef: {
3215 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3216 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3217 }
3218
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003219 case CXCursor_OverloadedDeclRef:
3220 return cxloc::translateSourceLocation(getCursorContext(C),
3221 getCursorOverloadedDeclRef(C).second);
3222
Douglas Gregorf46034a2010-01-18 23:41:10 +00003223 default:
3224 // FIXME: Need a way to enumerate all non-reference cases.
3225 llvm_unreachable("Missed a reference kind");
3226 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003227 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003228
3229 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003230 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003231 getLocationFromExpr(getCursorExpr(C)));
3232
Douglas Gregor36897b02010-09-10 00:22:18 +00003233 if (clang_isStatement(C.kind))
3234 return cxloc::translateSourceLocation(getCursorContext(C),
3235 getCursorStmt(C)->getLocStart());
3236
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003237 if (C.kind == CXCursor_PreprocessingDirective) {
3238 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3239 return cxloc::translateSourceLocation(getCursorContext(C), L);
3240 }
Douglas Gregor48072312010-03-18 15:23:44 +00003241
3242 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003243 SourceLocation L
3244 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003245 return cxloc::translateSourceLocation(getCursorContext(C), L);
3246 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003247
3248 if (C.kind == CXCursor_MacroDefinition) {
3249 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3250 return cxloc::translateSourceLocation(getCursorContext(C), L);
3251 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003252
3253 if (C.kind == CXCursor_InclusionDirective) {
3254 SourceLocation L
3255 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3256 return cxloc::translateSourceLocation(getCursorContext(C), L);
3257 }
3258
Ted Kremenek9a700d22010-05-12 06:16:13 +00003259 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003260 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003261
Douglas Gregorf46034a2010-01-18 23:41:10 +00003262 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003263 SourceLocation Loc = D->getLocation();
3264 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3265 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003266 // FIXME: Multiple variables declared in a single declaration
3267 // currently lack the information needed to correctly determine their
3268 // ranges when accounting for the type-specifier. We use context
3269 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3270 // and if so, whether it is the first decl.
3271 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3272 if (!cxcursor::isFirstInDeclGroup(C))
3273 Loc = VD->getLocation();
3274 }
3275
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003276 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003277}
Douglas Gregora7bde202010-01-19 00:34:46 +00003278
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003279} // end extern "C"
3280
3281static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003282 if (clang_isReference(C.kind)) {
3283 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003284 case CXCursor_ObjCSuperClassRef:
3285 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003286
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003287 case CXCursor_ObjCProtocolRef:
3288 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003289
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003290 case CXCursor_ObjCClassRef:
3291 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003292
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003293 case CXCursor_TypeRef:
3294 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003295
3296 case CXCursor_TemplateRef:
3297 return getCursorTemplateRef(C).second;
3298
Douglas Gregor69319002010-08-31 23:48:11 +00003299 case CXCursor_NamespaceRef:
3300 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003301
3302 case CXCursor_MemberRef:
3303 return getCursorMemberRef(C).second;
3304
Ted Kremenek3064ef92010-08-27 21:34:58 +00003305 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003306 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003307
Douglas Gregor36897b02010-09-10 00:22:18 +00003308 case CXCursor_LabelRef:
3309 return getCursorLabelRef(C).second;
3310
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003311 case CXCursor_OverloadedDeclRef:
3312 return getCursorOverloadedDeclRef(C).second;
3313
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003314 default:
3315 // FIXME: Need a way to enumerate all non-reference cases.
3316 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003317 }
3318 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003319
3320 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003321 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003322
3323 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003324 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003325
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003326 if (C.kind == CXCursor_PreprocessingDirective)
3327 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003328
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003329 if (C.kind == CXCursor_MacroInstantiation)
3330 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003331
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003332 if (C.kind == CXCursor_MacroDefinition)
3333 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003334
3335 if (C.kind == CXCursor_InclusionDirective)
3336 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3337
Ted Kremenek007a7c92010-11-01 23:26:51 +00003338 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3339 Decl *D = cxcursor::getCursorDecl(C);
3340 SourceRange R = D->getSourceRange();
3341 // FIXME: Multiple variables declared in a single declaration
3342 // currently lack the information needed to correctly determine their
3343 // ranges when accounting for the type-specifier. We use context
3344 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3345 // and if so, whether it is the first decl.
3346 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3347 if (!cxcursor::isFirstInDeclGroup(C))
3348 R.setBegin(VD->getLocation());
3349 }
3350 return R;
3351 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003352 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003353
3354extern "C" {
3355
3356CXSourceRange clang_getCursorExtent(CXCursor C) {
3357 SourceRange R = getRawCursorExtent(C);
3358 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003359 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003360
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003361 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003362}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003363
3364CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003365 if (clang_isInvalid(C.kind))
3366 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003367
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003368 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003369 if (clang_isDeclaration(C.kind)) {
3370 Decl *D = getCursorDecl(C);
3371 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3372 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3373 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3374 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3375 if (ObjCForwardProtocolDecl *Protocols
3376 = dyn_cast<ObjCForwardProtocolDecl>(D))
3377 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3378
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003379 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003380 }
3381
Douglas Gregor97b98722010-01-19 23:20:36 +00003382 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003383 Expr *E = getCursorExpr(C);
3384 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003385 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003386 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003387
3388 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3389 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3390
Douglas Gregor97b98722010-01-19 23:20:36 +00003391 return clang_getNullCursor();
3392 }
3393
Douglas Gregor36897b02010-09-10 00:22:18 +00003394 if (clang_isStatement(C.kind)) {
3395 Stmt *S = getCursorStmt(C);
3396 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3397 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3398 getCursorASTUnit(C));
3399
3400 return clang_getNullCursor();
3401 }
3402
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003403 if (C.kind == CXCursor_MacroInstantiation) {
3404 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3405 return MakeMacroDefinitionCursor(Def, CXXUnit);
3406 }
3407
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003408 if (!clang_isReference(C.kind))
3409 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003410
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003411 switch (C.kind) {
3412 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003413 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003414
3415 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003416 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003417
3418 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003419 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003420
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003421 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003422 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003423
3424 case CXCursor_TemplateRef:
3425 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3426
Douglas Gregor69319002010-08-31 23:48:11 +00003427 case CXCursor_NamespaceRef:
3428 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3429
Douglas Gregora67e03f2010-09-09 21:42:20 +00003430 case CXCursor_MemberRef:
3431 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3432
Ted Kremenek3064ef92010-08-27 21:34:58 +00003433 case CXCursor_CXXBaseSpecifier: {
3434 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3435 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3436 CXXUnit));
3437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438
Douglas Gregor36897b02010-09-10 00:22:18 +00003439 case CXCursor_LabelRef:
3440 // FIXME: We end up faking the "parent" declaration here because we
3441 // don't want to make CXCursor larger.
3442 return MakeCXCursor(getCursorLabelRef(C).first,
3443 CXXUnit->getASTContext().getTranslationUnitDecl(),
3444 CXXUnit);
3445
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003446 case CXCursor_OverloadedDeclRef:
3447 return C;
3448
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003449 default:
3450 // We would prefer to enumerate all non-reference cursor kinds here.
3451 llvm_unreachable("Unhandled reference cursor kind");
3452 break;
3453 }
3454 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003455
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003456 return clang_getNullCursor();
3457}
3458
Douglas Gregorb6998662010-01-19 19:34:47 +00003459CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003460 if (clang_isInvalid(C.kind))
3461 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003462
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003463 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003464
Douglas Gregorb6998662010-01-19 19:34:47 +00003465 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003466 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003467 C = clang_getCursorReferenced(C);
3468 WasReference = true;
3469 }
3470
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003471 if (C.kind == CXCursor_MacroInstantiation)
3472 return clang_getCursorReferenced(C);
3473
Douglas Gregorb6998662010-01-19 19:34:47 +00003474 if (!clang_isDeclaration(C.kind))
3475 return clang_getNullCursor();
3476
3477 Decl *D = getCursorDecl(C);
3478 if (!D)
3479 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003480
Douglas Gregorb6998662010-01-19 19:34:47 +00003481 switch (D->getKind()) {
3482 // Declaration kinds that don't really separate the notions of
3483 // declaration and definition.
3484 case Decl::Namespace:
3485 case Decl::Typedef:
3486 case Decl::TemplateTypeParm:
3487 case Decl::EnumConstant:
3488 case Decl::Field:
3489 case Decl::ObjCIvar:
3490 case Decl::ObjCAtDefsField:
3491 case Decl::ImplicitParam:
3492 case Decl::ParmVar:
3493 case Decl::NonTypeTemplateParm:
3494 case Decl::TemplateTemplateParm:
3495 case Decl::ObjCCategoryImpl:
3496 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003497 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003498 case Decl::LinkageSpec:
3499 case Decl::ObjCPropertyImpl:
3500 case Decl::FileScopeAsm:
3501 case Decl::StaticAssert:
3502 case Decl::Block:
3503 return C;
3504
3505 // Declaration kinds that don't make any sense here, but are
3506 // nonetheless harmless.
3507 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003508 break;
3509
3510 // Declaration kinds for which the definition is not resolvable.
3511 case Decl::UnresolvedUsingTypename:
3512 case Decl::UnresolvedUsingValue:
3513 break;
3514
3515 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003516 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3517 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003518
3519 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003520 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003521
3522 case Decl::Enum:
3523 case Decl::Record:
3524 case Decl::CXXRecord:
3525 case Decl::ClassTemplateSpecialization:
3526 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003527 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003528 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003529 return clang_getNullCursor();
3530
3531 case Decl::Function:
3532 case Decl::CXXMethod:
3533 case Decl::CXXConstructor:
3534 case Decl::CXXDestructor:
3535 case Decl::CXXConversion: {
3536 const FunctionDecl *Def = 0;
3537 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003538 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003539 return clang_getNullCursor();
3540 }
3541
3542 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003543 // Ask the variable if it has a definition.
3544 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3545 return MakeCXCursor(Def, CXXUnit);
3546 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003547 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003548
Douglas Gregorb6998662010-01-19 19:34:47 +00003549 case Decl::FunctionTemplate: {
3550 const FunctionDecl *Def = 0;
3551 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003552 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003553 return clang_getNullCursor();
3554 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003555
Douglas Gregorb6998662010-01-19 19:34:47 +00003556 case Decl::ClassTemplate: {
3557 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003558 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003559 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003560 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003561 return clang_getNullCursor();
3562 }
3563
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003564 case Decl::Using:
3565 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3566 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003567
3568 case Decl::UsingShadow:
3569 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003570 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003571 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003572
3573 case Decl::ObjCMethod: {
3574 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3575 if (Method->isThisDeclarationADefinition())
3576 return C;
3577
3578 // Dig out the method definition in the associated
3579 // @implementation, if we have it.
3580 // FIXME: The ASTs should make finding the definition easier.
3581 if (ObjCInterfaceDecl *Class
3582 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3583 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3584 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3585 Method->isInstanceMethod()))
3586 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003587 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003588
3589 return clang_getNullCursor();
3590 }
3591
3592 case Decl::ObjCCategory:
3593 if (ObjCCategoryImplDecl *Impl
3594 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003595 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003596 return clang_getNullCursor();
3597
3598 case Decl::ObjCProtocol:
3599 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3600 return C;
3601 return clang_getNullCursor();
3602
3603 case Decl::ObjCInterface:
3604 // There are two notions of a "definition" for an Objective-C
3605 // class: the interface and its implementation. When we resolved a
3606 // reference to an Objective-C class, produce the @interface as
3607 // the definition; when we were provided with the interface,
3608 // produce the @implementation as the definition.
3609 if (WasReference) {
3610 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3611 return C;
3612 } else if (ObjCImplementationDecl *Impl
3613 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003614 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003615 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003616
Douglas Gregorb6998662010-01-19 19:34:47 +00003617 case Decl::ObjCProperty:
3618 // FIXME: We don't really know where to find the
3619 // ObjCPropertyImplDecls that implement this property.
3620 return clang_getNullCursor();
3621
3622 case Decl::ObjCCompatibleAlias:
3623 if (ObjCInterfaceDecl *Class
3624 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3625 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003626 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003627
Douglas Gregorb6998662010-01-19 19:34:47 +00003628 return clang_getNullCursor();
3629
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003630 case Decl::ObjCForwardProtocol:
3631 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3632 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003633
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003634 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003635 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003636 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003637
3638 case Decl::Friend:
3639 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003640 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003641 return clang_getNullCursor();
3642
3643 case Decl::FriendTemplate:
3644 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003645 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003646 return clang_getNullCursor();
3647 }
3648
3649 return clang_getNullCursor();
3650}
3651
3652unsigned clang_isCursorDefinition(CXCursor C) {
3653 if (!clang_isDeclaration(C.kind))
3654 return 0;
3655
3656 return clang_getCursorDefinition(C) == C;
3657}
3658
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003659unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003660 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003661 return 0;
3662
3663 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3664 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3665 return E->getNumDecls();
3666
3667 if (OverloadedTemplateStorage *S
3668 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3669 return S->size();
3670
3671 Decl *D = Storage.get<Decl*>();
3672 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003673 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003674 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3675 return Classes->size();
3676 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3677 return Protocols->protocol_size();
3678
3679 return 0;
3680}
3681
3682CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003683 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003684 return clang_getNullCursor();
3685
3686 if (index >= clang_getNumOverloadedDecls(cursor))
3687 return clang_getNullCursor();
3688
3689 ASTUnit *Unit = getCursorASTUnit(cursor);
3690 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3691 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3692 return MakeCXCursor(E->decls_begin()[index], Unit);
3693
3694 if (OverloadedTemplateStorage *S
3695 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3696 return MakeCXCursor(S->begin()[index], Unit);
3697
3698 Decl *D = Storage.get<Decl*>();
3699 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3700 // FIXME: This is, unfortunately, linear time.
3701 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3702 std::advance(Pos, index);
3703 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3704 }
3705
3706 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3707 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3708
3709 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3710 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3711
3712 return clang_getNullCursor();
3713}
3714
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003715void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003716 const char **startBuf,
3717 const char **endBuf,
3718 unsigned *startLine,
3719 unsigned *startColumn,
3720 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003721 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003722 assert(getCursorDecl(C) && "CXCursor has null decl");
3723 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003724 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3725 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003726
Steve Naroff4ade6d62009-09-23 17:52:52 +00003727 SourceManager &SM = FD->getASTContext().getSourceManager();
3728 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3729 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3730 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3731 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3732 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3733 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3734}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003735
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003736void clang_enableStackTraces(void) {
3737 llvm::sys::PrintStackTraceOnErrorSignal();
3738}
3739
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003740void clang_executeOnThread(void (*fn)(void*), void *user_data,
3741 unsigned stack_size) {
3742 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3743}
3744
Ted Kremenekfb480492010-01-13 21:46:36 +00003745} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003746
Ted Kremenekfb480492010-01-13 21:46:36 +00003747//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003748// Token-based Operations.
3749//===----------------------------------------------------------------------===//
3750
3751/* CXToken layout:
3752 * int_data[0]: a CXTokenKind
3753 * int_data[1]: starting token location
3754 * int_data[2]: token length
3755 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003756 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003757 * otherwise unused.
3758 */
3759extern "C" {
3760
3761CXTokenKind clang_getTokenKind(CXToken CXTok) {
3762 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3763}
3764
3765CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3766 switch (clang_getTokenKind(CXTok)) {
3767 case CXToken_Identifier:
3768 case CXToken_Keyword:
3769 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003770 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3771 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003772
3773 case CXToken_Literal: {
3774 // We have stashed the starting pointer in the ptr_data field. Use it.
3775 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003776 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003777 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003778
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003779 case CXToken_Punctuation:
3780 case CXToken_Comment:
3781 break;
3782 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003783
3784 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003785 // deconstructing the source location.
3786 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3787 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003788 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003789
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003790 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3791 std::pair<FileID, unsigned> LocInfo
3792 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003793 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003794 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003795 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3796 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003797 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003798
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003799 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003800}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003801
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3803 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3804 if (!CXXUnit)
3805 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3808 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3809}
3810
3811CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3812 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003813 if (!CXXUnit)
3814 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003815
3816 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003817 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3818}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003819
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3821 CXToken **Tokens, unsigned *NumTokens) {
3822 if (Tokens)
3823 *Tokens = 0;
3824 if (NumTokens)
3825 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003826
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003827 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3828 if (!CXXUnit || !Tokens || !NumTokens)
3829 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003830
Douglas Gregorbdf60622010-03-05 21:16:25 +00003831 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3832
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003833 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834 if (R.isInvalid())
3835 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3838 std::pair<FileID, unsigned> BeginLocInfo
3839 = SourceMgr.getDecomposedLoc(R.getBegin());
3840 std::pair<FileID, unsigned> EndLocInfo
3841 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003842
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003843 // Cannot tokenize across files.
3844 if (BeginLocInfo.first != EndLocInfo.first)
3845 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
3847 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003848 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003849 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003850 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003851 if (Invalid)
3852 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003853
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003854 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3855 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003856 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003857 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003860 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003861 llvm::SmallVector<CXToken, 32> CXTokens;
3862 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003863 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 do {
3865 // Lex the next token
3866 Lex.LexFromRawLexer(Tok);
3867 if (Tok.is(tok::eof))
3868 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870 // Initialize the CXToken.
3871 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003872
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003873 // - Common fields
3874 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3875 CXTok.int_data[2] = Tok.getLength();
3876 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003877
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 // - Kind-specific fields
3879 if (Tok.isLiteral()) {
3880 CXTok.int_data[0] = CXToken_Literal;
3881 CXTok.ptr_data = (void *)Tok.getLiteralData();
3882 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003883 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003884 std::pair<FileID, unsigned> LocInfo
3885 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003886 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003887 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003888 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3889 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003890 return;
3891
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003892 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003893 IdentifierInfo *II
3894 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003895
David Chisnall096428b2010-10-13 21:44:48 +00003896 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003897 CXTok.int_data[0] = CXToken_Keyword;
3898 }
3899 else {
3900 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3901 CXToken_Identifier
3902 : CXToken_Keyword;
3903 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003904 CXTok.ptr_data = II;
3905 } else if (Tok.is(tok::comment)) {
3906 CXTok.int_data[0] = CXToken_Comment;
3907 CXTok.ptr_data = 0;
3908 } else {
3909 CXTok.int_data[0] = CXToken_Punctuation;
3910 CXTok.ptr_data = 0;
3911 }
3912 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003913 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003914 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003915
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003916 if (CXTokens.empty())
3917 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003918
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003919 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3920 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3921 *NumTokens = CXTokens.size();
3922}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003923
Ted Kremenek6db61092010-05-05 00:55:15 +00003924void clang_disposeTokens(CXTranslationUnit TU,
3925 CXToken *Tokens, unsigned NumTokens) {
3926 free(Tokens);
3927}
3928
3929} // end: extern "C"
3930
3931//===----------------------------------------------------------------------===//
3932// Token annotation APIs.
3933//===----------------------------------------------------------------------===//
3934
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003935typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003936static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3937 CXCursor parent,
3938 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003939namespace {
3940class AnnotateTokensWorker {
3941 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003942 CXToken *Tokens;
3943 CXCursor *Cursors;
3944 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003945 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003946 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003947 CursorVisitor AnnotateVis;
3948 SourceManager &SrcMgr;
3949
3950 bool MoreTokens() const { return TokIdx < NumTokens; }
3951 unsigned NextToken() const { return TokIdx; }
3952 void AdvanceToken() { ++TokIdx; }
3953 SourceLocation GetTokenLoc(unsigned tokI) {
3954 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3955 }
3956
Ted Kremenek6db61092010-05-05 00:55:15 +00003957public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003958 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003959 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3960 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003961 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003962 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003963 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3964 Decl::MaxPCHLevel, RegionOfInterest),
3965 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003966
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003967 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003968 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003969 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003970 void AnnotateTokens() {
3971 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3972 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003973};
3974}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003975
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003976void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3977 // Walk the AST within the region of interest, annotating tokens
3978 // along the way.
3979 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003980
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003981 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3982 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003983 if (Pos != Annotated.end() &&
3984 (clang_isInvalid(Cursors[I].kind) ||
3985 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003986 Cursors[I] = Pos->second;
3987 }
3988
3989 // Finish up annotating any tokens left.
3990 if (!MoreTokens())
3991 return;
3992
3993 const CXCursor &C = clang_getNullCursor();
3994 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3995 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3996 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003997 }
3998}
3999
Ted Kremenek6db61092010-05-05 00:55:15 +00004000enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004001AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004002 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004003 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004004 if (cursorRange.isInvalid())
4005 return CXChildVisit_Recurse;
4006
Douglas Gregor4419b672010-10-21 06:10:04 +00004007 if (clang_isPreprocessing(cursor.kind)) {
4008 // For macro instantiations, just note where the beginning of the macro
4009 // instantiation occurs.
4010 if (cursor.kind == CXCursor_MacroInstantiation) {
4011 Annotated[Loc.int_data] = cursor;
4012 return CXChildVisit_Recurse;
4013 }
4014
Douglas Gregor4419b672010-10-21 06:10:04 +00004015 // Items in the preprocessing record are kept separate from items in
4016 // declarations, so we keep a separate token index.
4017 unsigned SavedTokIdx = TokIdx;
4018 TokIdx = PreprocessingTokIdx;
4019
4020 // Skip tokens up until we catch up to the beginning of the preprocessing
4021 // entry.
4022 while (MoreTokens()) {
4023 const unsigned I = NextToken();
4024 SourceLocation TokLoc = GetTokenLoc(I);
4025 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4026 case RangeBefore:
4027 AdvanceToken();
4028 continue;
4029 case RangeAfter:
4030 case RangeOverlap:
4031 break;
4032 }
4033 break;
4034 }
4035
4036 // Look at all of the tokens within this range.
4037 while (MoreTokens()) {
4038 const unsigned I = NextToken();
4039 SourceLocation TokLoc = GetTokenLoc(I);
4040 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4041 case RangeBefore:
4042 assert(0 && "Infeasible");
4043 case RangeAfter:
4044 break;
4045 case RangeOverlap:
4046 Cursors[I] = cursor;
4047 AdvanceToken();
4048 continue;
4049 }
4050 break;
4051 }
4052
4053 // Save the preprocessing token index; restore the non-preprocessing
4054 // token index.
4055 PreprocessingTokIdx = TokIdx;
4056 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004057 return CXChildVisit_Recurse;
4058 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004059
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004060 if (cursorRange.isInvalid())
4061 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004062
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004063 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4064
Ted Kremeneka333c662010-05-12 05:29:33 +00004065 // Adjust the annotated range based specific declarations.
4066 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4067 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004068 Decl *D = cxcursor::getCursorDecl(cursor);
4069 // Don't visit synthesized ObjC methods, since they have no syntatic
4070 // representation in the source.
4071 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4072 if (MD->isSynthesized())
4073 return CXChildVisit_Continue;
4074 }
4075 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004076 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4077 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004078 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004079 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004080 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004081 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004082 }
4083 }
4084 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004085
Ted Kremenek3f404602010-08-14 01:14:06 +00004086 // If the location of the cursor occurs within a macro instantiation, record
4087 // the spelling location of the cursor in our annotation map. We can then
4088 // paper over the token labelings during a post-processing step to try and
4089 // get cursor mappings for tokens that are the *arguments* of a macro
4090 // instantiation.
4091 if (L.isMacroID()) {
4092 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4093 // Only invalidate the old annotation if it isn't part of a preprocessing
4094 // directive. Here we assume that the default construction of CXCursor
4095 // results in CXCursor.kind being an initialized value (i.e., 0). If
4096 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004097
Ted Kremenek3f404602010-08-14 01:14:06 +00004098 CXCursor &oldC = Annotated[rawEncoding];
4099 if (!clang_isPreprocessing(oldC.kind))
4100 oldC = cursor;
4101 }
4102
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004103 const enum CXCursorKind K = clang_getCursorKind(parent);
4104 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004105 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4106 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004107
4108 while (MoreTokens()) {
4109 const unsigned I = NextToken();
4110 SourceLocation TokLoc = GetTokenLoc(I);
4111 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4112 case RangeBefore:
4113 Cursors[I] = updateC;
4114 AdvanceToken();
4115 continue;
4116 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004117 case RangeOverlap:
4118 break;
4119 }
4120 break;
4121 }
4122
4123 // Visit children to get their cursor information.
4124 const unsigned BeforeChildren = NextToken();
4125 VisitChildren(cursor);
4126 const unsigned AfterChildren = NextToken();
4127
4128 // Adjust 'Last' to the last token within the extent of the cursor.
4129 while (MoreTokens()) {
4130 const unsigned I = NextToken();
4131 SourceLocation TokLoc = GetTokenLoc(I);
4132 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4133 case RangeBefore:
4134 assert(0 && "Infeasible");
4135 case RangeAfter:
4136 break;
4137 case RangeOverlap:
4138 Cursors[I] = updateC;
4139 AdvanceToken();
4140 continue;
4141 }
4142 break;
4143 }
4144 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004145
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004146 // Scan the tokens that are at the beginning of the cursor, but are not
4147 // capture by the child cursors.
4148
4149 // For AST elements within macros, rely on a post-annotate pass to
4150 // to correctly annotate the tokens with cursors. Otherwise we can
4151 // get confusing results of having tokens that map to cursors that really
4152 // are expanded by an instantiation.
4153 if (L.isMacroID())
4154 cursor = clang_getNullCursor();
4155
4156 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4157 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4158 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004159
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004160 Cursors[I] = cursor;
4161 }
4162 // Scan the tokens that are at the end of the cursor, but are not captured
4163 // but the child cursors.
4164 for (unsigned I = AfterChildren; I != Last; ++I)
4165 Cursors[I] = cursor;
4166
4167 TokIdx = Last;
4168 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004169}
4170
Ted Kremenek6db61092010-05-05 00:55:15 +00004171static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4172 CXCursor parent,
4173 CXClientData client_data) {
4174 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4175}
4176
Ted Kremenekab979612010-11-11 08:05:23 +00004177// This gets run a separate thread to avoid stack blowout.
4178static void runAnnotateTokensWorker(void *UserData) {
4179 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4180}
4181
Ted Kremenek6db61092010-05-05 00:55:15 +00004182extern "C" {
4183
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004184void clang_annotateTokens(CXTranslationUnit TU,
4185 CXToken *Tokens, unsigned NumTokens,
4186 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004187
4188 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004189 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004190
Douglas Gregor4419b672010-10-21 06:10:04 +00004191 // Any token we don't specifically annotate will have a NULL cursor.
4192 CXCursor C = clang_getNullCursor();
4193 for (unsigned I = 0; I != NumTokens; ++I)
4194 Cursors[I] = C;
4195
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004196 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004197 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004198 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004199
Douglas Gregorbdf60622010-03-05 21:16:25 +00004200 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004201
Douglas Gregor0396f462010-03-19 05:22:59 +00004202 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004203 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004204 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4205 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004206 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4207 clang_getTokenLocation(TU,
4208 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004209
Douglas Gregor0396f462010-03-19 05:22:59 +00004210 // A mapping from the source locations found when re-lexing or traversing the
4211 // region of interest to the corresponding cursors.
4212 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004213
4214 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004215 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004216 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4217 std::pair<FileID, unsigned> BeginLocInfo
4218 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4219 std::pair<FileID, unsigned> EndLocInfo
4220 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004221
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004222 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004223 bool Invalid = false;
4224 if (BeginLocInfo.first == EndLocInfo.first &&
4225 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4226 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004227 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4228 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004230 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004231 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232
4233 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004234 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004235 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004236 Token Tok;
4237 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004239 reprocess:
4240 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4241 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004242 // don't see it while preprocessing these tokens later, but keep track
4243 // of all of the token locations inside this preprocessing directive so
4244 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 //
4246 // FIXME: Some simple tests here could identify macro definitions and
4247 // #undefs, to provide specific cursor kinds for those.
4248 std::vector<SourceLocation> Locations;
4249 do {
4250 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004251 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004252 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004253
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004254 using namespace cxcursor;
4255 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004256 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4257 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004258 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004259 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4260 Annotated[Locations[I].getRawEncoding()] = Cursor;
4261 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004262
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004263 if (Tok.isAtStartOfLine())
4264 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004265
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004266 continue;
4267 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004268
Douglas Gregor48072312010-03-18 15:23:44 +00004269 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004270 break;
4271 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004272 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004273
Douglas Gregor0396f462010-03-19 05:22:59 +00004274 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004275 // a specific cursor.
4276 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4277 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004278
4279 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004280 // FIXME: We use a ridiculous stack size here because the data-recursion
4281 // algorithm uses a large stack frame than the non-data recursive version,
4282 // and AnnotationTokensWorker currently transforms the data-recursion
4283 // algorithm back into a traditional recursion by explicitly calling
4284 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004285 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004286 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4287 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004288 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4289 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004290}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004291} // end: extern "C"
4292
4293//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004294// Operations for querying linkage of a cursor.
4295//===----------------------------------------------------------------------===//
4296
4297extern "C" {
4298CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004299 if (!clang_isDeclaration(cursor.kind))
4300 return CXLinkage_Invalid;
4301
Ted Kremenek16b42592010-03-03 06:36:57 +00004302 Decl *D = cxcursor::getCursorDecl(cursor);
4303 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4304 switch (ND->getLinkage()) {
4305 case NoLinkage: return CXLinkage_NoLinkage;
4306 case InternalLinkage: return CXLinkage_Internal;
4307 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4308 case ExternalLinkage: return CXLinkage_External;
4309 };
4310
4311 return CXLinkage_Invalid;
4312}
4313} // end: extern "C"
4314
4315//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004316// Operations for querying language of a cursor.
4317//===----------------------------------------------------------------------===//
4318
4319static CXLanguageKind getDeclLanguage(const Decl *D) {
4320 switch (D->getKind()) {
4321 default:
4322 break;
4323 case Decl::ImplicitParam:
4324 case Decl::ObjCAtDefsField:
4325 case Decl::ObjCCategory:
4326 case Decl::ObjCCategoryImpl:
4327 case Decl::ObjCClass:
4328 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004329 case Decl::ObjCForwardProtocol:
4330 case Decl::ObjCImplementation:
4331 case Decl::ObjCInterface:
4332 case Decl::ObjCIvar:
4333 case Decl::ObjCMethod:
4334 case Decl::ObjCProperty:
4335 case Decl::ObjCPropertyImpl:
4336 case Decl::ObjCProtocol:
4337 return CXLanguage_ObjC;
4338 case Decl::CXXConstructor:
4339 case Decl::CXXConversion:
4340 case Decl::CXXDestructor:
4341 case Decl::CXXMethod:
4342 case Decl::CXXRecord:
4343 case Decl::ClassTemplate:
4344 case Decl::ClassTemplatePartialSpecialization:
4345 case Decl::ClassTemplateSpecialization:
4346 case Decl::Friend:
4347 case Decl::FriendTemplate:
4348 case Decl::FunctionTemplate:
4349 case Decl::LinkageSpec:
4350 case Decl::Namespace:
4351 case Decl::NamespaceAlias:
4352 case Decl::NonTypeTemplateParm:
4353 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004354 case Decl::TemplateTemplateParm:
4355 case Decl::TemplateTypeParm:
4356 case Decl::UnresolvedUsingTypename:
4357 case Decl::UnresolvedUsingValue:
4358 case Decl::Using:
4359 case Decl::UsingDirective:
4360 case Decl::UsingShadow:
4361 return CXLanguage_CPlusPlus;
4362 }
4363
4364 return CXLanguage_C;
4365}
4366
4367extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004368
4369enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4370 if (clang_isDeclaration(cursor.kind))
4371 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4372 if (D->hasAttr<UnavailableAttr>() ||
4373 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4374 return CXAvailability_Available;
4375
4376 if (D->hasAttr<DeprecatedAttr>())
4377 return CXAvailability_Deprecated;
4378 }
4379
4380 return CXAvailability_Available;
4381}
4382
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004383CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4384 if (clang_isDeclaration(cursor.kind))
4385 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4386
4387 return CXLanguage_Invalid;
4388}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004389
4390CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4391 if (clang_isDeclaration(cursor.kind)) {
4392 if (Decl *D = getCursorDecl(cursor)) {
4393 DeclContext *DC = D->getDeclContext();
4394 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4395 }
4396 }
4397
4398 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4399 if (Decl *D = getCursorDecl(cursor))
4400 return MakeCXCursor(D, getCursorASTUnit(cursor));
4401 }
4402
4403 return clang_getNullCursor();
4404}
4405
4406CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4407 if (clang_isDeclaration(cursor.kind)) {
4408 if (Decl *D = getCursorDecl(cursor)) {
4409 DeclContext *DC = D->getLexicalDeclContext();
4410 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4411 }
4412 }
4413
4414 // FIXME: Note that we can't easily compute the lexical context of a
4415 // statement or expression, so we return nothing.
4416 return clang_getNullCursor();
4417}
4418
Douglas Gregor9f592342010-10-01 20:25:15 +00004419static void CollectOverriddenMethods(DeclContext *Ctx,
4420 ObjCMethodDecl *Method,
4421 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4422 if (!Ctx)
4423 return;
4424
4425 // If we have a class or category implementation, jump straight to the
4426 // interface.
4427 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4428 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4429
4430 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4431 if (!Container)
4432 return;
4433
4434 // Check whether we have a matching method at this level.
4435 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4436 Method->isInstanceMethod()))
4437 if (Method != Overridden) {
4438 // We found an override at this level; there is no need to look
4439 // into other protocols or categories.
4440 Methods.push_back(Overridden);
4441 return;
4442 }
4443
4444 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4445 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4446 PEnd = Protocol->protocol_end();
4447 P != PEnd; ++P)
4448 CollectOverriddenMethods(*P, Method, Methods);
4449 }
4450
4451 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4452 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4453 PEnd = Category->protocol_end();
4454 P != PEnd; ++P)
4455 CollectOverriddenMethods(*P, Method, Methods);
4456 }
4457
4458 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4459 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4460 PEnd = Interface->protocol_end();
4461 P != PEnd; ++P)
4462 CollectOverriddenMethods(*P, Method, Methods);
4463
4464 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4465 Category; Category = Category->getNextClassCategory())
4466 CollectOverriddenMethods(Category, Method, Methods);
4467
4468 // We only look into the superclass if we haven't found anything yet.
4469 if (Methods.empty())
4470 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4471 return CollectOverriddenMethods(Super, Method, Methods);
4472 }
4473}
4474
4475void clang_getOverriddenCursors(CXCursor cursor,
4476 CXCursor **overridden,
4477 unsigned *num_overridden) {
4478 if (overridden)
4479 *overridden = 0;
4480 if (num_overridden)
4481 *num_overridden = 0;
4482 if (!overridden || !num_overridden)
4483 return;
4484
4485 if (!clang_isDeclaration(cursor.kind))
4486 return;
4487
4488 Decl *D = getCursorDecl(cursor);
4489 if (!D)
4490 return;
4491
4492 // Handle C++ member functions.
4493 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4494 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4495 *num_overridden = CXXMethod->size_overridden_methods();
4496 if (!*num_overridden)
4497 return;
4498
4499 *overridden = new CXCursor [*num_overridden];
4500 unsigned I = 0;
4501 for (CXXMethodDecl::method_iterator
4502 M = CXXMethod->begin_overridden_methods(),
4503 MEnd = CXXMethod->end_overridden_methods();
4504 M != MEnd; (void)++M, ++I)
4505 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4506 return;
4507 }
4508
4509 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4510 if (!Method)
4511 return;
4512
4513 // Handle Objective-C methods.
4514 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4515 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4516
4517 if (Methods.empty())
4518 return;
4519
4520 *num_overridden = Methods.size();
4521 *overridden = new CXCursor [Methods.size()];
4522 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4523 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4524}
4525
4526void clang_disposeOverriddenCursors(CXCursor *overridden) {
4527 delete [] overridden;
4528}
4529
Douglas Gregorecdcb882010-10-20 22:00:55 +00004530CXFile clang_getIncludedFile(CXCursor cursor) {
4531 if (cursor.kind != CXCursor_InclusionDirective)
4532 return 0;
4533
4534 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4535 return (void *)ID->getFile();
4536}
4537
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004538} // end: extern "C"
4539
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004540
4541//===----------------------------------------------------------------------===//
4542// C++ AST instrospection.
4543//===----------------------------------------------------------------------===//
4544
4545extern "C" {
4546unsigned clang_CXXMethod_isStatic(CXCursor C) {
4547 if (!clang_isDeclaration(C.kind))
4548 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004549
4550 CXXMethodDecl *Method = 0;
4551 Decl *D = cxcursor::getCursorDecl(C);
4552 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4553 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4554 else
4555 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4556 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004557}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004558
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004559} // end: extern "C"
4560
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004561//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004562// Attribute introspection.
4563//===----------------------------------------------------------------------===//
4564
4565extern "C" {
4566CXType clang_getIBOutletCollectionType(CXCursor C) {
4567 if (C.kind != CXCursor_IBOutletCollectionAttr)
4568 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4569
4570 IBOutletCollectionAttr *A =
4571 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4572
4573 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4574}
4575} // end: extern "C"
4576
4577//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004578// CXString Operations.
4579//===----------------------------------------------------------------------===//
4580
4581extern "C" {
4582const char *clang_getCString(CXString string) {
4583 return string.Spelling;
4584}
4585
4586void clang_disposeString(CXString string) {
4587 if (string.MustFreeString && string.Spelling)
4588 free((void*)string.Spelling);
4589}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004590
Ted Kremenekfb480492010-01-13 21:46:36 +00004591} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004592
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004593namespace clang { namespace cxstring {
4594CXString createCXString(const char *String, bool DupString){
4595 CXString Str;
4596 if (DupString) {
4597 Str.Spelling = strdup(String);
4598 Str.MustFreeString = 1;
4599 } else {
4600 Str.Spelling = String;
4601 Str.MustFreeString = 0;
4602 }
4603 return Str;
4604}
4605
4606CXString createCXString(llvm::StringRef String, bool DupString) {
4607 CXString Result;
4608 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4609 char *Spelling = (char *)malloc(String.size() + 1);
4610 memmove(Spelling, String.data(), String.size());
4611 Spelling[String.size()] = 0;
4612 Result.Spelling = Spelling;
4613 Result.MustFreeString = 1;
4614 } else {
4615 Result.Spelling = String.data();
4616 Result.MustFreeString = 0;
4617 }
4618 return Result;
4619}
4620}}
4621
Ted Kremenek04bb7162010-01-22 22:44:15 +00004622//===----------------------------------------------------------------------===//
4623// Misc. utility functions.
4624//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004625
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004626/// Default to using an 8 MB stack size on "safety" threads.
4627static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004628
4629namespace clang {
4630
4631bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004632 void (*Fn)(void*), void *UserData,
4633 unsigned Size) {
4634 if (!Size)
4635 Size = GetSafetyThreadStackSize();
4636 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004637 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4638 return CRC.RunSafely(Fn, UserData);
4639}
4640
4641unsigned GetSafetyThreadStackSize() {
4642 return SafetyStackThreadSize;
4643}
4644
4645void SetSafetyThreadStackSize(unsigned Value) {
4646 SafetyStackThreadSize = Value;
4647}
4648
4649}
4650
Ted Kremenek04bb7162010-01-22 22:44:15 +00004651extern "C" {
4652
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004653CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004654 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004655}
4656
4657} // end: extern "C"