blob: a25570e0c1440a83451ef409290494cc22705e0a [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 Kremeneked122732010-11-16 01:56:27 +000017#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000018#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000019#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000020#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000021
Ted Kremenek04bb7162010-01-22 22:44:15 +000022#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000023
Steve Naroff50398192009-08-28 15:28:48 +000024#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000026#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000027#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000030#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000031#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000032#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000033#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000034#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000035#include "llvm/ADT/Optional.h"
36#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000037#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000038#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000039#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000041#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000042#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000043#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000044#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000045#include "llvm/System/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000046#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000047
Steve Naroff50398192009-08-28 15:28:48 +000048using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000049using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000050using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000051
Douglas Gregor33e9abd2010-01-22 19:49:59 +000052/// \brief The result of comparing two source ranges.
53enum RangeComparisonResult {
54 /// \brief Either the ranges overlap or one of the ranges is invalid.
55 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000056
Douglas Gregor33e9abd2010-01-22 19:49:59 +000057 /// \brief The first range ends before the second range starts.
58 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000059
Douglas Gregor33e9abd2010-01-22 19:49:59 +000060 /// \brief The first range starts after the second range ends.
61 RangeAfter
62};
63
Ted Kremenekf0e23e82010-02-17 00:41:40 +000064/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000065/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000066static RangeComparisonResult RangeCompare(SourceManager &SM,
67 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000068 SourceRange R2) {
69 assert(R1.isValid() && "First range is invalid?");
70 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000071 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000072 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000073 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000074 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000075 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000076 return RangeAfter;
77 return RangeOverlap;
78}
79
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000080/// \brief Determine if a source location falls within, before, or after a
81/// a given source range.
82static RangeComparisonResult LocationCompare(SourceManager &SM,
83 SourceLocation L, SourceRange R) {
84 assert(R.isValid() && "First range is invalid?");
85 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000086 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000087 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
89 return RangeBefore;
90 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
91 return RangeAfter;
92 return RangeOverlap;
93}
94
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000095/// \brief Translate a Clang source range into a CIndex source range.
96///
97/// Clang internally represents ranges where the end location points to the
98/// start of the token at the end. However, for external clients it is more
99/// useful to have a CXSourceRange be a proper half-open interval. This routine
100/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000101CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000102 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000103 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000104 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000105 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000106 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000107 if (EndLoc.isValid() && EndLoc.isMacroID())
108 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000109 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000110 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111 EndLoc = EndLoc.getFileLocWithOffset(Length);
112 }
113
114 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
115 R.getBegin().getRawEncoding(),
116 EndLoc.getRawEncoding() };
117 return Result;
118}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000119
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000120//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000121// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000122//===----------------------------------------------------------------------===//
123
Steve Naroff89922f82009-08-31 00:59:03 +0000124namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000125
126class VisitorJob {
127public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000128 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000129 TypeLocVisitKind, OverloadExprPartsKind,
130 DeclRefExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000131protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000132 void *dataA;
133 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000134 CXCursor parent;
135 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000136 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
137 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000138public:
139 Kind getKind() const { return K; }
140 const CXCursor &getParent() const { return parent; }
141 static bool classof(VisitorJob *VJ) { return true; }
142};
143
144typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
145
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000147class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000148 public TypeLocVisitor<CursorVisitor, bool>,
149 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000150{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000152 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000153
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000154 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000155 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000156
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000157 /// \brief The declaration that serves at the parent of any statement or
158 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000159 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000160
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000163
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000164 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000166
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000167 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
168 // to the visitor. Declarations with a PCH level greater than this value will
169 // be suppressed.
170 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171
172 /// \brief When valid, a source range to which the cursor should restrict
173 /// its search.
174 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000176 // FIXME: Eventually remove. This part of a hack to support proper
177 // iteration over all Decls contained lexically within an ObjC container.
178 DeclContext::decl_iterator *DI_current;
179 DeclContext::decl_iterator DE_current;
180
Ted Kremenekd1ded662010-11-15 23:31:32 +0000181 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
182 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
183 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
184
Douglas Gregorb1373d02010-01-20 20:59:29 +0000185 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000186 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000187 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000188
189 /// \brief Determine whether this particular source range comes before, comes
190 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000191 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000192 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
194
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000195 class SetParentRAII {
196 CXCursor &Parent;
197 Decl *&StmtParent;
198 CXCursor OldParent;
199
200 public:
201 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
202 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
203 {
204 Parent = NewParent;
205 if (clang_isDeclaration(Parent.kind))
206 StmtParent = getCursorDecl(Parent);
207 }
208
209 ~SetParentRAII() {
210 Parent = OldParent;
211 if (clang_isDeclaration(Parent.kind))
212 StmtParent = getCursorDecl(Parent);
213 }
214 };
215
Steve Naroff89922f82009-08-31 00:59:03 +0000216public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
218 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000219 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000221 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
222 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000223 {
224 Parent.kind = CXCursor_NoDeclFound;
225 Parent.data[0] = 0;
226 Parent.data[1] = 0;
227 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000228 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000229 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000230
Ted Kremenekd1ded662010-11-15 23:31:32 +0000231 ~CursorVisitor() {
232 // Free the pre-allocated worklists for data-recursion.
233 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
234 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
235 delete *I;
236 }
237 }
238
Ted Kremenekab979612010-11-11 08:05:23 +0000239 ASTUnit *getASTUnit() const { return TU; }
240
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000241 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000242
243 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
244 getPreprocessedEntities();
245
Douglas Gregorb1373d02010-01-20 20:59:29 +0000246 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000247
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000248 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000249 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000250 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000251 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000252 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000253 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000254 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
255 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000256 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000257 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000258 bool VisitClassTemplatePartialSpecializationDecl(
259 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000260 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000261 bool VisitEnumConstantDecl(EnumConstantDecl *D);
262 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
263 bool VisitFunctionDecl(FunctionDecl *ND);
264 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000265 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000266 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000267 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000268 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000269 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000270 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
271 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
272 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
273 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000274 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000275 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
276 bool VisitObjCImplDecl(ObjCImplDecl *D);
277 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
278 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000279 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
280 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
281 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000282 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000283 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000284 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000285 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000286 bool VisitUsingDecl(UsingDecl *D);
287 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
288 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000289
Douglas Gregor01829d32010-08-31 14:41:23 +0000290 // Name visitor
291 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000292 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000293
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000294 // Template visitors
295 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000296 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000297 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
298
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000299 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000300 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000301 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000302 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000303 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
304 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000305 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000306 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000307 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000308 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
309 bool VisitPointerTypeLoc(PointerTypeLoc TL);
310 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
311 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
312 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
313 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000314 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000315 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000316 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000317 // FIXME: Implement visitors here when the unimplemented TypeLocs get
318 // implemented
319 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
320 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000321
Douglas Gregora59e3902010-01-21 23:27:09 +0000322 // Statement visitors
323 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000324
Douglas Gregor336fd812010-01-23 00:40:08 +0000325 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000326 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000327 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000328 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000329 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
330 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000331 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000332 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000333 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000334 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000335 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000336 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000337 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000338 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000339 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000340
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000341 // Data-recursive visitor functions.
342 bool IsInRegionOfInterest(CXCursor C);
343 bool RunVisitorWorkList(VisitorWorkList &WL);
344 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenek37f1ea02010-11-15 23:11:54 +0000345 bool VisitDataRecursive(Stmt *S) LLVM_ATTRIBUTE_NOINLINE;
Steve Naroff89922f82009-08-31 00:59:03 +0000346};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000347
Ted Kremenekab188932010-01-05 19:32:54 +0000348} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000349
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000350static SourceRange getRawCursorExtent(CXCursor C);
351
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000352RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000353 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
354}
355
Douglas Gregorb1373d02010-01-20 20:59:29 +0000356/// \brief Visit the given cursor and, if requested by the visitor,
357/// its children.
358///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359/// \param Cursor the cursor to visit.
360///
361/// \param CheckRegionOfInterest if true, then the caller already checked that
362/// this cursor is within the region of interest.
363///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000364/// \returns true if the visitation should be aborted, false if it
365/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000367 if (clang_isInvalid(Cursor.kind))
368 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000369
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370 if (clang_isDeclaration(Cursor.kind)) {
371 Decl *D = getCursorDecl(Cursor);
372 assert(D && "Invalid declaration cursor");
373 if (D->getPCHLevel() > MaxPCHLevel)
374 return false;
375
376 if (D->isImplicit())
377 return false;
378 }
379
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000380 // If we have a range of interest, and this cursor doesn't intersect with it,
381 // we're done.
382 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000383 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000384 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385 return false;
386 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 switch (Visitor(Cursor, Parent, ClientData)) {
389 case CXChildVisit_Break:
390 return true;
391
392 case CXChildVisit_Continue:
393 return false;
394
395 case CXChildVisit_Recurse:
396 return VisitChildren(Cursor);
397 }
398
Douglas Gregorfd643772010-01-25 16:45:46 +0000399 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400}
401
Douglas Gregor788f5a12010-03-20 00:41:21 +0000402std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
403CursorVisitor::getPreprocessedEntities() {
404 PreprocessingRecord &PPRec
405 = *TU->getPreprocessor().getPreprocessingRecord();
406
407 bool OnlyLocalDecls
408 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
409
410 // There is no region of interest; we have to walk everything.
411 if (RegionOfInterest.isInvalid())
412 return std::make_pair(PPRec.begin(OnlyLocalDecls),
413 PPRec.end(OnlyLocalDecls));
414
415 // Find the file in which the region of interest lands.
416 SourceManager &SM = TU->getSourceManager();
417 std::pair<FileID, unsigned> Begin
418 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
419 std::pair<FileID, unsigned> End
420 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
421
422 // The region of interest spans files; we have to walk everything.
423 if (Begin.first != End.first)
424 return std::make_pair(PPRec.begin(OnlyLocalDecls),
425 PPRec.end(OnlyLocalDecls));
426
427 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
428 = TU->getPreprocessedEntitiesByFile();
429 if (ByFileMap.empty()) {
430 // Build the mapping from files to sets of preprocessed entities.
431 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
432 EEnd = PPRec.end(OnlyLocalDecls);
433 E != EEnd; ++E) {
434 std::pair<FileID, unsigned> P
435 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
436 ByFileMap[P.first].push_back(*E);
437 }
438 }
439
440 return std::make_pair(ByFileMap[Begin.first].begin(),
441 ByFileMap[Begin.first].end());
442}
443
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444/// \brief Visit the children of the given cursor.
445///
446/// \returns true if the visitation should be aborted, false if it
447/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000448bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000449 if (clang_isReference(Cursor.kind)) {
450 // By definition, references have no children.
451 return false;
452 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000453
454 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000456 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458 if (clang_isDeclaration(Cursor.kind)) {
459 Decl *D = getCursorDecl(Cursor);
460 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000461 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000462 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463
Douglas Gregora59e3902010-01-21 23:27:09 +0000464 if (clang_isStatement(Cursor.kind))
465 return Visit(getCursorStmt(Cursor));
466 if (clang_isExpression(Cursor.kind))
467 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000470 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000471 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
472 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000473 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
474 TLEnd = CXXUnit->top_level_end();
475 TL != TLEnd; ++TL) {
476 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000477 return true;
478 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000479 } else if (VisitDeclContext(
480 CXXUnit->getASTContext().getTranslationUnitDecl()))
481 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000482
Douglas Gregor0396f462010-03-19 05:22:59 +0000483 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000484 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000485 // FIXME: Once we have the ability to deserialize a preprocessing record,
486 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000487 PreprocessingRecord::iterator E, EEnd;
488 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000489 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
490 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
491 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000492
Douglas Gregor0396f462010-03-19 05:22:59 +0000493 continue;
494 }
495
496 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
497 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
498 return true;
499
500 continue;
501 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000502
503 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
504 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
505 return true;
506
507 continue;
508 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000509 }
510 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000511 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000513
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 return false;
516}
517
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000518bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000519 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
520 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000521
Ted Kremenek664cffd2010-07-22 11:30:19 +0000522 if (Stmt *Body = B->getBody())
523 return Visit(MakeCXCursor(Body, StmtParent, TU));
524
525 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000526}
527
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000528llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
529 if (RegionOfInterest.isValid()) {
530 SourceRange Range = getRawCursorExtent(Cursor);
531 if (Range.isInvalid())
532 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000533
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000534 switch (CompareRegionOfInterest(Range)) {
535 case RangeBefore:
536 // This declaration comes before the region of interest; skip it.
537 return llvm::Optional<bool>();
538
539 case RangeAfter:
540 // This declaration comes after the region of interest; we're done.
541 return false;
542
543 case RangeOverlap:
544 // This declaration overlaps the region of interest; visit it.
545 break;
546 }
547 }
548 return true;
549}
550
551bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
552 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
553
554 // FIXME: Eventually remove. This part of a hack to support proper
555 // iteration over all Decls contained lexically within an ObjC container.
556 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
557 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
558
559 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000560 Decl *D = *I;
561 if (D->getLexicalDeclContext() != DC)
562 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000563 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000564 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
565 if (!V.hasValue())
566 continue;
567 if (!V.getValue())
568 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000569 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570 return true;
571 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000573}
574
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000575bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
576 llvm_unreachable("Translation units are visited directly by Visit()");
577 return false;
578}
579
580bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
581 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
582 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000583
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000584 return false;
585}
586
587bool CursorVisitor::VisitTagDecl(TagDecl *D) {
588 return VisitDeclContext(D);
589}
590
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000591bool CursorVisitor::VisitClassTemplateSpecializationDecl(
592 ClassTemplateSpecializationDecl *D) {
593 bool ShouldVisitBody = false;
594 switch (D->getSpecializationKind()) {
595 case TSK_Undeclared:
596 case TSK_ImplicitInstantiation:
597 // Nothing to visit
598 return false;
599
600 case TSK_ExplicitInstantiationDeclaration:
601 case TSK_ExplicitInstantiationDefinition:
602 break;
603
604 case TSK_ExplicitSpecialization:
605 ShouldVisitBody = true;
606 break;
607 }
608
609 // Visit the template arguments used in the specialization.
610 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
611 TypeLoc TL = SpecType->getTypeLoc();
612 if (TemplateSpecializationTypeLoc *TSTLoc
613 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
614 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
615 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
616 return true;
617 }
618 }
619
620 if (ShouldVisitBody && VisitCXXRecordDecl(D))
621 return true;
622
623 return false;
624}
625
Douglas Gregor74dbe642010-08-31 19:31:58 +0000626bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
627 ClassTemplatePartialSpecializationDecl *D) {
628 // FIXME: Visit the "outer" template parameter lists on the TagDecl
629 // before visiting these template parameters.
630 if (VisitTemplateParameters(D->getTemplateParameters()))
631 return true;
632
633 // Visit the partial specialization arguments.
634 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
635 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
636 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
637 return true;
638
639 return VisitCXXRecordDecl(D);
640}
641
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000642bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000643 // Visit the default argument.
644 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
645 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
646 if (Visit(DefArg->getTypeLoc()))
647 return true;
648
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000649 return false;
650}
651
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000652bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
653 if (Expr *Init = D->getInitExpr())
654 return Visit(MakeCXCursor(Init, StmtParent, TU));
655 return false;
656}
657
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000658bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
659 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
660 if (Visit(TSInfo->getTypeLoc()))
661 return true;
662
663 return false;
664}
665
Douglas Gregora67e03f2010-09-09 21:42:20 +0000666/// \brief Compare two base or member initializers based on their source order.
667static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
668 CXXBaseOrMemberInitializer const * const *X
669 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
670 CXXBaseOrMemberInitializer const * const *Y
671 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
672
673 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
674 return -1;
675 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
676 return 1;
677 else
678 return 0;
679}
680
Douglas Gregorb1373d02010-01-20 20:59:29 +0000681bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000682 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
683 // Visit the function declaration's syntactic components in the order
684 // written. This requires a bit of work.
685 TypeLoc TL = TSInfo->getTypeLoc();
686 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
687
688 // If we have a function declared directly (without the use of a typedef),
689 // visit just the return type. Otherwise, just visit the function's type
690 // now.
691 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
692 (!FTL && Visit(TL)))
693 return true;
694
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000695 // Visit the nested-name-specifier, if present.
696 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
697 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
698 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000699
700 // Visit the declaration name.
701 if (VisitDeclarationNameInfo(ND->getNameInfo()))
702 return true;
703
704 // FIXME: Visit explicitly-specified template arguments!
705
706 // Visit the function parameters, if we have a function type.
707 if (FTL && VisitFunctionTypeLoc(*FTL, true))
708 return true;
709
710 // FIXME: Attributes?
711 }
712
Douglas Gregora67e03f2010-09-09 21:42:20 +0000713 if (ND->isThisDeclarationADefinition()) {
714 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
715 // Find the initializers that were written in the source.
716 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
717 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
718 IEnd = Constructor->init_end();
719 I != IEnd; ++I) {
720 if (!(*I)->isWritten())
721 continue;
722
723 WrittenInits.push_back(*I);
724 }
725
726 // Sort the initializers in source order
727 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
728 &CompareCXXBaseOrMemberInitializers);
729
730 // Visit the initializers in source order
731 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
732 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
733 if (Init->isMemberInitializer()) {
734 if (Visit(MakeCursorMemberRef(Init->getMember(),
735 Init->getMemberLocation(), TU)))
736 return true;
737 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
738 if (Visit(BaseInfo->getTypeLoc()))
739 return true;
740 }
741
742 // Visit the initializer value.
743 if (Expr *Initializer = Init->getInit())
744 if (Visit(MakeCXCursor(Initializer, ND, TU)))
745 return true;
746 }
747 }
748
749 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
750 return true;
751 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000752
Douglas Gregorb1373d02010-01-20 20:59:29 +0000753 return false;
754}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000755
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000756bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
757 if (VisitDeclaratorDecl(D))
758 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000759
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000760 if (Expr *BitWidth = D->getBitWidth())
761 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000762
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000763 return false;
764}
765
766bool CursorVisitor::VisitVarDecl(VarDecl *D) {
767 if (VisitDeclaratorDecl(D))
768 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000769
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000770 if (Expr *Init = D->getInit())
771 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000772
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000773 return false;
774}
775
Douglas Gregor84b51d72010-09-01 20:16:53 +0000776bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
777 if (VisitDeclaratorDecl(D))
778 return true;
779
780 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
781 if (Expr *DefArg = D->getDefaultArgument())
782 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
783
784 return false;
785}
786
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000787bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
788 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
789 // before visiting these template parameters.
790 if (VisitTemplateParameters(D->getTemplateParameters()))
791 return true;
792
793 return VisitFunctionDecl(D->getTemplatedDecl());
794}
795
Douglas Gregor39d6f072010-08-31 19:02:00 +0000796bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
797 // FIXME: Visit the "outer" template parameter lists on the TagDecl
798 // before visiting these template parameters.
799 if (VisitTemplateParameters(D->getTemplateParameters()))
800 return true;
801
802 return VisitCXXRecordDecl(D->getTemplatedDecl());
803}
804
Douglas Gregor84b51d72010-09-01 20:16:53 +0000805bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
806 if (VisitTemplateParameters(D->getTemplateParameters()))
807 return true;
808
809 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
810 VisitTemplateArgumentLoc(D->getDefaultArgument()))
811 return true;
812
813 return false;
814}
815
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000816bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000817 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
818 if (Visit(TSInfo->getTypeLoc()))
819 return true;
820
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000821 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000822 PEnd = ND->param_end();
823 P != PEnd; ++P) {
824 if (Visit(MakeCXCursor(*P, TU)))
825 return true;
826 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000827
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000828 if (ND->isThisDeclarationADefinition() &&
829 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
830 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832 return false;
833}
834
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000835namespace {
836 struct ContainerDeclsSort {
837 SourceManager &SM;
838 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
839 bool operator()(Decl *A, Decl *B) {
840 SourceLocation L_A = A->getLocStart();
841 SourceLocation L_B = B->getLocStart();
842 assert(L_A.isValid() && L_B.isValid());
843 return SM.isBeforeInTranslationUnit(L_A, L_B);
844 }
845 };
846}
847
Douglas Gregora59e3902010-01-21 23:27:09 +0000848bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000849 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
850 // an @implementation can lexically contain Decls that are not properly
851 // nested in the AST. When we identify such cases, we need to retrofit
852 // this nesting here.
853 if (!DI_current)
854 return VisitDeclContext(D);
855
856 // Scan the Decls that immediately come after the container
857 // in the current DeclContext. If any fall within the
858 // container's lexical region, stash them into a vector
859 // for later processing.
860 llvm::SmallVector<Decl *, 24> DeclsInContainer;
861 SourceLocation EndLoc = D->getSourceRange().getEnd();
862 SourceManager &SM = TU->getSourceManager();
863 if (EndLoc.isValid()) {
864 DeclContext::decl_iterator next = *DI_current;
865 while (++next != DE_current) {
866 Decl *D_next = *next;
867 if (!D_next)
868 break;
869 SourceLocation L = D_next->getLocStart();
870 if (!L.isValid())
871 break;
872 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
873 *DI_current = next;
874 DeclsInContainer.push_back(D_next);
875 continue;
876 }
877 break;
878 }
879 }
880
881 // The common case.
882 if (DeclsInContainer.empty())
883 return VisitDeclContext(D);
884
885 // Get all the Decls in the DeclContext, and sort them with the
886 // additional ones we've collected. Then visit them.
887 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
888 I!=E; ++I) {
889 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000890 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
891 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000892 continue;
893 DeclsInContainer.push_back(subDecl);
894 }
895
896 // Now sort the Decls so that they appear in lexical order.
897 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
898 ContainerDeclsSort(SM));
899
900 // Now visit the decls.
901 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
902 E = DeclsInContainer.end(); I != E; ++I) {
903 CXCursor Cursor = MakeCXCursor(*I, TU);
904 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
905 if (!V.hasValue())
906 continue;
907 if (!V.getValue())
908 return false;
909 if (Visit(Cursor, true))
910 return true;
911 }
912 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000913}
914
Douglas Gregorb1373d02010-01-20 20:59:29 +0000915bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000916 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
917 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000918 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000919
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000920 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
921 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
922 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000923 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000924 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000925
Douglas Gregora59e3902010-01-21 23:27:09 +0000926 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000927}
928
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000929bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
930 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
931 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
932 E = PID->protocol_end(); I != E; ++I, ++PL)
933 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
934 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000935
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000936 return VisitObjCContainerDecl(PID);
937}
938
Ted Kremenek23173d72010-05-18 21:09:07 +0000939bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000940 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000941 return true;
942
Ted Kremenek23173d72010-05-18 21:09:07 +0000943 // FIXME: This implements a workaround with @property declarations also being
944 // installed in the DeclContext for the @interface. Eventually this code
945 // should be removed.
946 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
947 if (!CDecl || !CDecl->IsClassExtension())
948 return false;
949
950 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
951 if (!ID)
952 return false;
953
954 IdentifierInfo *PropertyId = PD->getIdentifier();
955 ObjCPropertyDecl *prevDecl =
956 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
957
958 if (!prevDecl)
959 return false;
960
961 // Visit synthesized methods since they will be skipped when visiting
962 // the @interface.
963 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000964 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000965 if (Visit(MakeCXCursor(MD, TU)))
966 return true;
967
968 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000969 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000970 if (Visit(MakeCXCursor(MD, TU)))
971 return true;
972
973 return false;
974}
975
Douglas Gregorb1373d02010-01-20 20:59:29 +0000976bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000977 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000978 if (D->getSuperClass() &&
979 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000980 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000981 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000982 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000983
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000984 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
985 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
986 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000987 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989
Douglas Gregora59e3902010-01-21 23:27:09 +0000990 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000991}
992
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000993bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
994 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000995}
996
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000997bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000998 // 'ID' could be null when dealing with invalid code.
999 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1000 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1001 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001002
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001003 return VisitObjCImplDecl(D);
1004}
1005
1006bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1007#if 0
1008 // Issue callbacks for super class.
1009 // FIXME: No source location information!
1010 if (D->getSuperClass() &&
1011 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001013 TU)))
1014 return true;
1015#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001017 return VisitObjCImplDecl(D);
1018}
1019
1020bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1021 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1022 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1023 E = D->protocol_end();
1024 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001025 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001026 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027
1028 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001029}
1030
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001031bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1032 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1033 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1034 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001035
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001036 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001037}
1038
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001039bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1040 return VisitDeclContext(D);
1041}
1042
Douglas Gregor69319002010-08-31 23:48:11 +00001043bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001044 // Visit nested-name-specifier.
1045 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1046 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1047 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001048
1049 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1050 D->getTargetNameLoc(), TU));
1051}
1052
Douglas Gregor7e242562010-09-01 19:52:22 +00001053bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001054 // Visit nested-name-specifier.
1055 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1056 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1057 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001058
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001059 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1060 return true;
1061
Douglas Gregor7e242562010-09-01 19:52:22 +00001062 return VisitDeclarationNameInfo(D->getNameInfo());
1063}
1064
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001065bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001066 // Visit nested-name-specifier.
1067 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1068 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1069 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001070
1071 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1072 D->getIdentLocation(), TU));
1073}
1074
Douglas Gregor7e242562010-09-01 19:52:22 +00001075bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001076 // Visit nested-name-specifier.
1077 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1078 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1079 return true;
1080
Douglas Gregor7e242562010-09-01 19:52:22 +00001081 return VisitDeclarationNameInfo(D->getNameInfo());
1082}
1083
1084bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1085 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 // Visit nested-name-specifier.
1087 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1088 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1089 return true;
1090
Douglas Gregor7e242562010-09-01 19:52:22 +00001091 return false;
1092}
1093
Douglas Gregor01829d32010-08-31 14:41:23 +00001094bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1095 switch (Name.getName().getNameKind()) {
1096 case clang::DeclarationName::Identifier:
1097 case clang::DeclarationName::CXXLiteralOperatorName:
1098 case clang::DeclarationName::CXXOperatorName:
1099 case clang::DeclarationName::CXXUsingDirective:
1100 return false;
1101
1102 case clang::DeclarationName::CXXConstructorName:
1103 case clang::DeclarationName::CXXDestructorName:
1104 case clang::DeclarationName::CXXConversionFunctionName:
1105 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1106 return Visit(TSInfo->getTypeLoc());
1107 return false;
1108
1109 case clang::DeclarationName::ObjCZeroArgSelector:
1110 case clang::DeclarationName::ObjCOneArgSelector:
1111 case clang::DeclarationName::ObjCMultiArgSelector:
1112 // FIXME: Per-identifier location info?
1113 return false;
1114 }
1115
1116 return false;
1117}
1118
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1120 SourceRange Range) {
1121 // FIXME: This whole routine is a hack to work around the lack of proper
1122 // source information in nested-name-specifiers (PR5791). Since we do have
1123 // a beginning source location, we can visit the first component of the
1124 // nested-name-specifier, if it's a single-token component.
1125 if (!NNS)
1126 return false;
1127
1128 // Get the first component in the nested-name-specifier.
1129 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1130 NNS = Prefix;
1131
1132 switch (NNS->getKind()) {
1133 case NestedNameSpecifier::Namespace:
1134 // FIXME: The token at this source location might actually have been a
1135 // namespace alias, but we don't model that. Lame!
1136 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1137 TU));
1138
1139 case NestedNameSpecifier::TypeSpec: {
1140 // If the type has a form where we know that the beginning of the source
1141 // range matches up with a reference cursor. Visit the appropriate reference
1142 // cursor.
1143 Type *T = NNS->getAsType();
1144 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1145 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1146 if (const TagType *Tag = dyn_cast<TagType>(T))
1147 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1148 if (const TemplateSpecializationType *TST
1149 = dyn_cast<TemplateSpecializationType>(T))
1150 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1151 break;
1152 }
1153
1154 case NestedNameSpecifier::TypeSpecWithTemplate:
1155 case NestedNameSpecifier::Global:
1156 case NestedNameSpecifier::Identifier:
1157 break;
1158 }
1159
1160 return false;
1161}
1162
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001163bool CursorVisitor::VisitTemplateParameters(
1164 const TemplateParameterList *Params) {
1165 if (!Params)
1166 return false;
1167
1168 for (TemplateParameterList::const_iterator P = Params->begin(),
1169 PEnd = Params->end();
1170 P != PEnd; ++P) {
1171 if (Visit(MakeCXCursor(*P, TU)))
1172 return true;
1173 }
1174
1175 return false;
1176}
1177
Douglas Gregor0b36e612010-08-31 20:37:03 +00001178bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1179 switch (Name.getKind()) {
1180 case TemplateName::Template:
1181 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1182
1183 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001184 // Visit the overloaded template set.
1185 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1186 return true;
1187
Douglas Gregor0b36e612010-08-31 20:37:03 +00001188 return false;
1189
1190 case TemplateName::DependentTemplate:
1191 // FIXME: Visit nested-name-specifier.
1192 return false;
1193
1194 case TemplateName::QualifiedTemplate:
1195 // FIXME: Visit nested-name-specifier.
1196 return Visit(MakeCursorTemplateRef(
1197 Name.getAsQualifiedTemplateName()->getDecl(),
1198 Loc, TU));
1199 }
1200
1201 return false;
1202}
1203
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001204bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1205 switch (TAL.getArgument().getKind()) {
1206 case TemplateArgument::Null:
1207 case TemplateArgument::Integral:
1208 return false;
1209
1210 case TemplateArgument::Pack:
1211 // FIXME: Implement when variadic templates come along.
1212 return false;
1213
1214 case TemplateArgument::Type:
1215 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1216 return Visit(TSInfo->getTypeLoc());
1217 return false;
1218
1219 case TemplateArgument::Declaration:
1220 if (Expr *E = TAL.getSourceDeclExpression())
1221 return Visit(MakeCXCursor(E, StmtParent, TU));
1222 return false;
1223
1224 case TemplateArgument::Expression:
1225 if (Expr *E = TAL.getSourceExpression())
1226 return Visit(MakeCXCursor(E, StmtParent, TU));
1227 return false;
1228
1229 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001230 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1231 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001232 }
1233
1234 return false;
1235}
1236
Ted Kremeneka0536d82010-05-07 01:04:29 +00001237bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1238 return VisitDeclContext(D);
1239}
1240
Douglas Gregor01829d32010-08-31 14:41:23 +00001241bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1242 return Visit(TL.getUnqualifiedLoc());
1243}
1244
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001245bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1246 ASTContext &Context = TU->getASTContext();
1247
1248 // Some builtin types (such as Objective-C's "id", "sel", and
1249 // "Class") have associated declarations. Create cursors for those.
1250 QualType VisitType;
1251 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001252 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001253 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001254 case BuiltinType::Char_U:
1255 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001256 case BuiltinType::Char16:
1257 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001258 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001259 case BuiltinType::UInt:
1260 case BuiltinType::ULong:
1261 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001262 case BuiltinType::UInt128:
1263 case BuiltinType::Char_S:
1264 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001265 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001266 case BuiltinType::Short:
1267 case BuiltinType::Int:
1268 case BuiltinType::Long:
1269 case BuiltinType::LongLong:
1270 case BuiltinType::Int128:
1271 case BuiltinType::Float:
1272 case BuiltinType::Double:
1273 case BuiltinType::LongDouble:
1274 case BuiltinType::NullPtr:
1275 case BuiltinType::Overload:
1276 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001277 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001278
1279 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001280 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001281
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001282 case BuiltinType::ObjCId:
1283 VisitType = Context.getObjCIdType();
1284 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001285
1286 case BuiltinType::ObjCClass:
1287 VisitType = Context.getObjCClassType();
1288 break;
1289
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001290 case BuiltinType::ObjCSel:
1291 VisitType = Context.getObjCSelType();
1292 break;
1293 }
1294
1295 if (!VisitType.isNull()) {
1296 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001297 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001298 TU));
1299 }
1300
1301 return false;
1302}
1303
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001304bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1305 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1306}
1307
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001308bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1309 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1310}
1311
1312bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1313 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1314}
1315
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001316bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001317 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001318 // no context information with which we can match up the depth/index in the
1319 // type to the appropriate
1320 return false;
1321}
1322
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1324 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1325 return true;
1326
John McCallc12c5bb2010-05-15 11:32:37 +00001327 return false;
1328}
1329
1330bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1331 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1332 return true;
1333
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1335 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1336 TU)))
1337 return true;
1338 }
1339
1340 return false;
1341}
1342
1343bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001344 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001345}
1346
1347bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1348 return Visit(TL.getPointeeLoc());
1349}
1350
1351bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1352 return Visit(TL.getPointeeLoc());
1353}
1354
1355bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1356 return Visit(TL.getPointeeLoc());
1357}
1358
1359bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001360 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001361}
1362
1363bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001364 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001365}
1366
Douglas Gregor01829d32010-08-31 14:41:23 +00001367bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1368 bool SkipResultType) {
1369 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370 return true;
1371
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001372 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001373 if (Decl *D = TL.getArg(I))
1374 if (Visit(MakeCXCursor(D, TU)))
1375 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376
1377 return false;
1378}
1379
1380bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1381 if (Visit(TL.getElementLoc()))
1382 return true;
1383
1384 if (Expr *Size = TL.getSizeExpr())
1385 return Visit(MakeCXCursor(Size, StmtParent, TU));
1386
1387 return false;
1388}
1389
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001390bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1391 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001392 // Visit the template name.
1393 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1394 TL.getTemplateNameLoc()))
1395 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001396
1397 // Visit the template arguments.
1398 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1399 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1400 return true;
1401
1402 return false;
1403}
1404
Douglas Gregor2332c112010-01-21 20:48:56 +00001405bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1406 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1407}
1408
1409bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1410 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1411 return Visit(TSInfo->getTypeLoc());
1412
1413 return false;
1414}
1415
Douglas Gregora59e3902010-01-21 23:27:09 +00001416bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001417 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001418}
1419
Ted Kremenek3064ef92010-08-27 21:34:58 +00001420bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1421 if (D->isDefinition()) {
1422 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1423 E = D->bases_end(); I != E; ++I) {
1424 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1425 return true;
1426 }
1427 }
1428
1429 return VisitTagDecl(D);
1430}
1431
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001432bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001433 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001434 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1435 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001436
1437 // Visit the components of the offsetof expression.
1438 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1439 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1440 const OffsetOfNode &Node = E->getComponent(I);
1441 switch (Node.getKind()) {
1442 case OffsetOfNode::Array:
1443 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1444 StmtParent, TU)))
1445 return true;
1446 break;
1447
1448 case OffsetOfNode::Field:
1449 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1450 TU)))
1451 return true;
1452 break;
1453
1454 case OffsetOfNode::Identifier:
1455 case OffsetOfNode::Base:
1456 continue;
1457 }
1458 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001459
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001460 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001461}
1462
Douglas Gregor336fd812010-01-23 00:40:08 +00001463bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1464 if (E->isArgumentType()) {
1465 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1466 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001467
Douglas Gregor336fd812010-01-23 00:40:08 +00001468 return false;
1469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001470
Douglas Gregor336fd812010-01-23 00:40:08 +00001471 return VisitExpr(E);
1472}
1473
Douglas Gregor36897b02010-09-10 00:22:18 +00001474bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1475 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1476}
1477
Douglas Gregor648220e2010-08-10 15:02:34 +00001478bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1479 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1480 Visit(E->getArgTInfo2()->getTypeLoc());
1481}
1482
1483bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1484 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1485 return true;
1486
1487 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1488}
1489
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001490bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1491 // Visit the designators.
1492 typedef DesignatedInitExpr::Designator Designator;
1493 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1494 DEnd = E->designators_end();
1495 D != DEnd; ++D) {
1496 if (D->isFieldDesignator()) {
1497 if (FieldDecl *Field = D->getField())
1498 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1499 return true;
1500
1501 continue;
1502 }
1503
1504 if (D->isArrayDesignator()) {
1505 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1506 return true;
1507
1508 continue;
1509 }
1510
1511 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1512 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1513 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1514 return true;
1515 }
1516
1517 // Visit the initializer value itself.
1518 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1519}
1520
Douglas Gregor94802292010-09-02 21:20:16 +00001521bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1522 if (E->isTypeOperand()) {
1523 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1524 return Visit(TSInfo->getTypeLoc());
1525
1526 return false;
1527 }
1528
1529 return VisitExpr(E);
1530}
1531
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001532bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1533 if (E->isTypeOperand()) {
1534 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1535 return Visit(TSInfo->getTypeLoc());
1536
1537 return false;
1538 }
1539
1540 return VisitExpr(E);
1541}
1542
Douglas Gregorab6677e2010-09-08 00:15:04 +00001543bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1544 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1545 return Visit(TSInfo->getTypeLoc());
1546
1547 return false;
1548}
1549
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001550bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1551 // Visit base expression.
1552 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1553 return true;
1554
1555 // Visit the nested-name-specifier.
1556 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1557 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1558 return true;
1559
1560 // Visit the scope type that looks disturbingly like the nested-name-specifier
1561 // but isn't.
1562 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1563 if (Visit(TSInfo->getTypeLoc()))
1564 return true;
1565
1566 // Visit the name of the type being destroyed.
1567 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1568 if (Visit(TSInfo->getTypeLoc()))
1569 return true;
1570
1571 return false;
1572}
1573
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001574bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1575 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1576}
1577
Douglas Gregorbfebed22010-09-03 17:24:10 +00001578bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1579 DependentScopeDeclRefExpr *E) {
1580 // Visit the nested-name-specifier.
1581 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1582 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1583 return true;
1584
1585 // Visit the declaration name.
1586 if (VisitDeclarationNameInfo(E->getNameInfo()))
1587 return true;
1588
1589 // Visit the explicitly-specified template arguments.
1590 if (const ExplicitTemplateArgumentList *ArgList
1591 = E->getOptionalExplicitTemplateArgs()) {
1592 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1593 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1594 Arg != ArgEnd; ++Arg) {
1595 if (VisitTemplateArgumentLoc(*Arg))
1596 return true;
1597 }
1598 }
1599
1600 return false;
1601}
1602
Douglas Gregorab6677e2010-09-08 00:15:04 +00001603bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1604 CXXUnresolvedConstructExpr *E) {
1605 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1606 if (Visit(TSInfo->getTypeLoc()))
1607 return true;
1608
1609 return VisitExpr(E);
1610}
1611
Douglas Gregor25d63622010-09-03 17:35:34 +00001612bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1613 CXXDependentScopeMemberExpr *E) {
1614 // Visit the base expression, if there is one.
1615 if (!E->isImplicitAccess() &&
1616 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1617 return true;
1618
1619 // Visit the nested-name-specifier.
1620 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1621 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1622 return true;
1623
1624 // Visit the declaration name.
1625 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1626 return true;
1627
1628 // Visit the explicitly-specified template arguments.
1629 if (const ExplicitTemplateArgumentList *ArgList
1630 = E->getOptionalExplicitTemplateArgs()) {
1631 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1632 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1633 Arg != ArgEnd; ++Arg) {
1634 if (VisitTemplateArgumentLoc(*Arg))
1635 return true;
1636 }
1637 }
1638
1639 return false;
1640}
1641
Ted Kremenek09dfa372010-02-18 05:46:33 +00001642bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001643 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1644 i != e; ++i)
1645 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001646 return true;
1647
1648 return false;
1649}
1650
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001651//===----------------------------------------------------------------------===//
1652// Data-recursive visitor methods.
1653//===----------------------------------------------------------------------===//
1654
Ted Kremenek28a71942010-11-13 00:36:47 +00001655namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001656#define DEF_JOB(NAME, DATA, KIND)\
1657class NAME : public VisitorJob {\
1658public:\
1659 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1660 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1661 DATA *get() const { return static_cast<DATA*>(dataA); }\
1662};
1663
1664DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1665DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001666DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001667DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1668#undef DEF_JOB
1669
1670class DeclVisit : public VisitorJob {
1671public:
1672 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1673 VisitorJob(parent, VisitorJob::DeclVisitKind,
1674 d, isFirst ? (void*) 1 : (void*) 0) {}
1675 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001676 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001677 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001678 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001679 bool isFirst() const { return dataB ? true : false; }
1680};
1681
1682class TypeLocVisit : public VisitorJob {
1683public:
1684 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1685 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1686 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1687
1688 static bool classof(const VisitorJob *VJ) {
1689 return VJ->getKind() == TypeLocVisitKind;
1690 }
1691
Ted Kremenek82f3c502010-11-15 22:23:26 +00001692 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001693 QualType T = QualType::getFromOpaquePtr(dataA);
1694 return TypeLoc(T, dataB);
1695 }
1696};
1697
Ted Kremenek28a71942010-11-13 00:36:47 +00001698class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1699 VisitorWorkList &WL;
1700 CXCursor Parent;
1701public:
1702 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1703 : WL(wl), Parent(parent) {}
1704
Ted Kremenek73d15c42010-11-13 01:09:29 +00001705 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001706 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001707 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001708 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1709 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001710 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001711 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001712 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001713 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001714 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1715 void VisitForStmt(ForStmt *FS);
1716 void VisitIfStmt(IfStmt *If);
1717 void VisitInitListExpr(InitListExpr *IE);
1718 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001719 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001720 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1721 void VisitOverloadExpr(OverloadExpr *E);
1722 void VisitStmt(Stmt *S);
1723 void VisitSwitchStmt(SwitchStmt *S);
1724 void VisitWhileStmt(WhileStmt *W);
1725 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1726
1727private:
1728 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001729 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001730 void AddTypeLoc(TypeSourceInfo *TI);
1731 void EnqueueChildren(Stmt *S);
1732};
1733} // end anonyous namespace
1734
1735void EnqueueVisitor::AddStmt(Stmt *S) {
1736 if (S)
1737 WL.push_back(StmtVisit(S, Parent));
1738}
Ted Kremenek035dc412010-11-13 00:36:50 +00001739void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001740 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001741 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001742}
1743void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1744 if (TI)
1745 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1746 }
1747void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001748 unsigned size = WL.size();
1749 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1750 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001752 }
1753 if (size == WL.size())
1754 return;
1755 // Now reverse the entries we just added. This will match the DFS
1756 // ordering performed by the worklist.
1757 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1758 std::reverse(I, E);
1759}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001760void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1761 AddDecl(B->getBlockDecl());
1762}
Ted Kremenek28a71942010-11-13 00:36:47 +00001763void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1764 EnqueueChildren(E);
1765 AddTypeLoc(E->getTypeSourceInfo());
1766}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001767void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1768 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1769 E = S->body_rend(); I != E; ++I) {
1770 AddStmt(*I);
1771 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001772}
1773void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1774 // Enqueue the initializer or constructor arguments.
1775 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1776 AddStmt(E->getConstructorArg(I-1));
1777 // Enqueue the array size, if any.
1778 AddStmt(E->getArraySize());
1779 // Enqueue the allocated type.
1780 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1781 // Enqueue the placement arguments.
1782 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1783 AddStmt(E->getPlacementArg(I-1));
1784}
Ted Kremenek28a71942010-11-13 00:36:47 +00001785void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001786 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1787 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001788 AddStmt(CE->getCallee());
1789 AddStmt(CE->getArg(0));
1790}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001791void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1792 EnqueueChildren(E);
1793 AddTypeLoc(E->getTypeSourceInfo());
1794}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001795void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1796 WL.push_back(DeclRefExprParts(DR, Parent));
1797}
Ted Kremenek035dc412010-11-13 00:36:50 +00001798void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1799 unsigned size = WL.size();
1800 bool isFirst = true;
1801 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1802 D != DEnd; ++D) {
1803 AddDecl(*D, isFirst);
1804 isFirst = false;
1805 }
1806 if (size == WL.size())
1807 return;
1808 // Now reverse the entries we just added. This will match the DFS
1809 // ordering performed by the worklist.
1810 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1811 std::reverse(I, E);
1812}
Ted Kremenek28a71942010-11-13 00:36:47 +00001813void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1814 EnqueueChildren(E);
1815 AddTypeLoc(E->getTypeInfoAsWritten());
1816}
1817void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1818 AddStmt(FS->getBody());
1819 AddStmt(FS->getInc());
1820 AddStmt(FS->getCond());
1821 AddDecl(FS->getConditionVariable());
1822 AddStmt(FS->getInit());
1823}
1824void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1825 AddStmt(If->getElse());
1826 AddStmt(If->getThen());
1827 AddStmt(If->getCond());
1828 AddDecl(If->getConditionVariable());
1829}
1830void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1831 // We care about the syntactic form of the initializer list, only.
1832 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1833 IE = Syntactic;
1834 EnqueueChildren(IE);
1835}
1836void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1837 WL.push_back(MemberExprParts(M, Parent));
1838 AddStmt(M->getBase());
1839}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001840void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1841 AddTypeLoc(E->getEncodedTypeSourceInfo());
1842}
Ted Kremenek28a71942010-11-13 00:36:47 +00001843void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1844 EnqueueChildren(M);
1845 AddTypeLoc(M->getClassReceiverTypeInfo());
1846}
1847void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001848 WL.push_back(OverloadExprParts(E, Parent));
1849}
Ted Kremenek28a71942010-11-13 00:36:47 +00001850void EnqueueVisitor::VisitStmt(Stmt *S) {
1851 EnqueueChildren(S);
1852}
1853void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1854 AddStmt(S->getBody());
1855 AddStmt(S->getCond());
1856 AddDecl(S->getConditionVariable());
1857}
1858void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1859 AddStmt(W->getBody());
1860 AddStmt(W->getCond());
1861 AddDecl(W->getConditionVariable());
1862}
1863void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1864 VisitOverloadExpr(U);
1865 if (!U->isImplicitAccess())
1866 AddStmt(U->getBase());
1867}
Ted Kremenek60458782010-11-12 21:34:16 +00001868
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001869void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001870 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001871}
1872
1873bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1874 if (RegionOfInterest.isValid()) {
1875 SourceRange Range = getRawCursorExtent(C);
1876 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1877 return false;
1878 }
1879 return true;
1880}
1881
1882bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1883 while (!WL.empty()) {
1884 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001885 VisitorJob LI = WL.back();
1886 WL.pop_back();
1887
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001888 // Set the Parent field, then back to its old value once we're done.
1889 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1890
1891 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001892 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001893 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001894 if (!D)
1895 continue;
1896
1897 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001898 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001899 return true;
1900
1901 continue;
1902 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001903 case VisitorJob::TypeLocVisitKind: {
1904 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001905 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001906 return true;
1907 continue;
1908 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001909 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001910 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001911 if (!S)
1912 continue;
1913
Ted Kremenekf1107452010-11-12 18:26:56 +00001914 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001915 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1916
1917 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001918 case Stmt::GotoStmtClass: {
1919 GotoStmt *GS = cast<GotoStmt>(S);
1920 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1921 GS->getLabelLoc(), TU))) {
1922 return true;
1923 }
1924 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001925 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001926 // Cases not yet handled by the data-recursion
1927 // algorithm.
1928 case Stmt::OffsetOfExprClass:
1929 case Stmt::SizeOfAlignOfExprClass:
1930 case Stmt::AddrLabelExprClass:
1931 case Stmt::TypesCompatibleExprClass:
1932 case Stmt::VAArgExprClass:
1933 case Stmt::DesignatedInitExprClass:
1934 case Stmt::CXXTypeidExprClass:
1935 case Stmt::CXXUuidofExprClass:
1936 case Stmt::CXXScalarValueInitExprClass:
1937 case Stmt::CXXPseudoDestructorExprClass:
1938 case Stmt::UnaryTypeTraitExprClass:
1939 case Stmt::DependentScopeDeclRefExprClass:
1940 case Stmt::CXXUnresolvedConstructExprClass:
1941 case Stmt::CXXDependentScopeMemberExprClass:
1942 if (Visit(Cursor))
1943 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001944 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001945 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001946 if (!IsInRegionOfInterest(Cursor))
1947 continue;
1948 switch (Visitor(Cursor, Parent, ClientData)) {
1949 case CXChildVisit_Break:
1950 return true;
1951 case CXChildVisit_Continue:
1952 break;
1953 case CXChildVisit_Recurse:
1954 EnqueueWorkList(WL, S);
1955 break;
1956 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001957 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001958 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001959 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001960 }
1961 case VisitorJob::MemberExprPartsKind: {
1962 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001963 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001964
1965 // Visit the nested-name-specifier
1966 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1967 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1968 return true;
1969
1970 // Visit the declaration name.
1971 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1972 return true;
1973
1974 // Visit the explicitly-specified template arguments, if any.
1975 if (M->hasExplicitTemplateArgs()) {
1976 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1977 *ArgEnd = Arg + M->getNumTemplateArgs();
1978 Arg != ArgEnd; ++Arg) {
1979 if (VisitTemplateArgumentLoc(*Arg))
1980 return true;
1981 }
1982 }
1983 continue;
1984 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001985 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001986 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001987 // Visit nested-name-specifier, if present.
1988 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
1989 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
1990 return true;
1991 // Visit declaration name.
1992 if (VisitDeclarationNameInfo(DR->getNameInfo()))
1993 return true;
1994 // Visit explicitly-specified template arguments.
1995 if (DR->hasExplicitTemplateArgs()) {
1996 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
1997 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1998 *ArgEnd = Arg + Args.NumTemplateArgs;
1999 Arg != ArgEnd; ++Arg)
2000 if (VisitTemplateArgumentLoc(*Arg))
2001 return true;
2002 }
2003 continue;
2004 }
Ted Kremenek60458782010-11-12 21:34:16 +00002005 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002006 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002007 // Visit the nested-name-specifier.
2008 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2009 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2010 return true;
2011 // Visit the declaration name.
2012 if (VisitDeclarationNameInfo(O->getNameInfo()))
2013 return true;
2014 // Visit the overloaded declaration reference.
2015 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2016 return true;
2017 // Visit the explicitly-specified template arguments.
2018 if (const ExplicitTemplateArgumentList *ArgList
2019 = O->getOptionalExplicitTemplateArgs()) {
2020 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2021 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2022 Arg != ArgEnd; ++Arg) {
2023 if (VisitTemplateArgumentLoc(*Arg))
2024 return true;
2025 }
2026 }
2027 continue;
2028 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002029 }
2030 }
2031 return false;
2032}
2033
2034bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002035 VisitorWorkList *WL = 0;
2036 if (!WorkListFreeList.empty()) {
2037 WL = WorkListFreeList.back();
2038 WL->clear();
2039 WorkListFreeList.pop_back();
2040 }
2041 else {
2042 WL = new VisitorWorkList();
2043 WorkListCache.push_back(WL);
2044 }
2045 EnqueueWorkList(*WL, S);
2046 bool result = RunVisitorWorkList(*WL);
2047 WorkListFreeList.push_back(WL);
2048 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002049}
2050
2051//===----------------------------------------------------------------------===//
2052// Misc. API hooks.
2053//===----------------------------------------------------------------------===//
2054
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002055static llvm::sys::Mutex EnableMultithreadingMutex;
2056static bool EnabledMultithreading;
2057
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002058extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002059CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2060 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002061 // Disable pretty stack trace functionality, which will otherwise be a very
2062 // poor citizen of the world and set up all sorts of signal handlers.
2063 llvm::DisablePrettyStackTrace = true;
2064
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002065 // We use crash recovery to make some of our APIs more reliable, implicitly
2066 // enable it.
2067 llvm::CrashRecoveryContext::Enable();
2068
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002069 // Enable support for multithreading in LLVM.
2070 {
2071 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2072 if (!EnabledMultithreading) {
2073 llvm::llvm_start_multithreaded();
2074 EnabledMultithreading = true;
2075 }
2076 }
2077
Douglas Gregora030b7c2010-01-22 20:35:53 +00002078 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002079 if (excludeDeclarationsFromPCH)
2080 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002081 if (displayDiagnostics)
2082 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002083 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002084}
2085
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002086void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002087 if (CIdx)
2088 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002089}
2090
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002091CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002092 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002093 if (!CIdx)
2094 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002095
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002096 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002097 FileSystemOptions FileSystemOpts;
2098 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002099
Douglas Gregor28019772010-04-05 23:52:57 +00002100 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002101 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002102 CXXIdx->getOnlyLocalDecls(),
2103 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002104}
2105
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002106unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002107 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002108 CXTranslationUnit_CacheCompletionResults |
2109 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002110}
2111
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002112CXTranslationUnit
2113clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2114 const char *source_filename,
2115 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002116 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002117 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002118 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002119 return clang_parseTranslationUnit(CIdx, source_filename,
2120 command_line_args, num_command_line_args,
2121 unsaved_files, num_unsaved_files,
2122 CXTranslationUnit_DetailedPreprocessingRecord);
2123}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002124
2125struct ParseTranslationUnitInfo {
2126 CXIndex CIdx;
2127 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002128 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002129 int num_command_line_args;
2130 struct CXUnsavedFile *unsaved_files;
2131 unsigned num_unsaved_files;
2132 unsigned options;
2133 CXTranslationUnit result;
2134};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002135static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002136 ParseTranslationUnitInfo *PTUI =
2137 static_cast<ParseTranslationUnitInfo*>(UserData);
2138 CXIndex CIdx = PTUI->CIdx;
2139 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002140 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002141 int num_command_line_args = PTUI->num_command_line_args;
2142 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2143 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2144 unsigned options = PTUI->options;
2145 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002146
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002147 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002148 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002150 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2151
Douglas Gregor44c181a2010-07-23 00:33:23 +00002152 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002153 bool CompleteTranslationUnit
2154 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002155 bool CacheCodeCompetionResults
2156 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002157 bool CXXPrecompilePreamble
2158 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2159 bool CXXChainedPCH
2160 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002161
Douglas Gregor5352ac02010-01-28 00:27:43 +00002162 // Configure the diagnostics.
2163 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002164 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2165 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002166
Douglas Gregor4db64a42010-01-23 00:14:00 +00002167 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2168 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002169 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002170 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002171 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002172 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2173 Buffer));
2174 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002175
Douglas Gregorb10daed2010-10-11 16:52:23 +00002176 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002177
Ted Kremenek139ba862009-10-22 00:03:57 +00002178 // The 'source_filename' argument is optional. If the caller does not
2179 // specify it then it is assumed that the source file is specified
2180 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002181 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002182 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002183
2184 // Since the Clang C library is primarily used by batch tools dealing with
2185 // (often very broken) source code, where spell-checking can have a
2186 // significant negative impact on performance (particularly when
2187 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002188 // Only do this if we haven't found a spell-checking-related argument.
2189 bool FoundSpellCheckingArgument = false;
2190 for (int I = 0; I != num_command_line_args; ++I) {
2191 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2192 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2193 FoundSpellCheckingArgument = true;
2194 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002195 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002196 }
2197 if (!FoundSpellCheckingArgument)
2198 Args.push_back("-fno-spell-checking");
2199
2200 Args.insert(Args.end(), command_line_args,
2201 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002202
Douglas Gregor44c181a2010-07-23 00:33:23 +00002203 // Do we need the detailed preprocessing record?
2204 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002205 Args.push_back("-Xclang");
2206 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002207 }
2208
Douglas Gregorb10daed2010-10-11 16:52:23 +00002209 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002210 llvm::OwningPtr<ASTUnit> Unit(
2211 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2212 Diags,
2213 CXXIdx->getClangResourcesPath(),
2214 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002215 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 RemappedFiles.data(),
2217 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 PrecompilePreamble,
2219 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002220 CacheCodeCompetionResults,
2221 CXXPrecompilePreamble,
2222 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002223
Douglas Gregorb10daed2010-10-11 16:52:23 +00002224 if (NumErrors != Diags->getNumErrors()) {
2225 // Make sure to check that 'Unit' is non-NULL.
2226 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2227 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2228 DEnd = Unit->stored_diag_end();
2229 D != DEnd; ++D) {
2230 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2231 CXString Msg = clang_formatDiagnostic(&Diag,
2232 clang_defaultDiagnosticDisplayOptions());
2233 fprintf(stderr, "%s\n", clang_getCString(Msg));
2234 clang_disposeString(Msg);
2235 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002236#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002237 // On Windows, force a flush, since there may be multiple copies of
2238 // stderr and stdout in the file system, all with different buffers
2239 // but writing to the same device.
2240 fflush(stderr);
2241#endif
2242 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002243 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002244
Douglas Gregorb10daed2010-10-11 16:52:23 +00002245 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002246}
2247CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2248 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002249 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002250 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002251 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002252 unsigned num_unsaved_files,
2253 unsigned options) {
2254 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002255 num_command_line_args, unsaved_files,
2256 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002257 llvm::CrashRecoveryContext CRC;
2258
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002259 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002260 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2261 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2262 fprintf(stderr, " 'command_line_args' : [");
2263 for (int i = 0; i != num_command_line_args; ++i) {
2264 if (i)
2265 fprintf(stderr, ", ");
2266 fprintf(stderr, "'%s'", command_line_args[i]);
2267 }
2268 fprintf(stderr, "],\n");
2269 fprintf(stderr, " 'unsaved_files' : [");
2270 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2271 if (i)
2272 fprintf(stderr, ", ");
2273 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2274 unsaved_files[i].Length);
2275 }
2276 fprintf(stderr, "],\n");
2277 fprintf(stderr, " 'options' : %d,\n", options);
2278 fprintf(stderr, "}\n");
2279
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002280 return 0;
2281 }
2282
2283 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002284}
2285
Douglas Gregor19998442010-08-13 15:35:05 +00002286unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2287 return CXSaveTranslationUnit_None;
2288}
2289
2290int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2291 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002292 if (!TU)
2293 return 1;
2294
2295 return static_cast<ASTUnit *>(TU)->Save(FileName);
2296}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002297
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002298void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002299 if (CTUnit) {
2300 // If the translation unit has been marked as unsafe to free, just discard
2301 // it.
2302 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2303 return;
2304
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002305 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002306 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002307}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002308
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002309unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2310 return CXReparse_None;
2311}
2312
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002313struct ReparseTranslationUnitInfo {
2314 CXTranslationUnit TU;
2315 unsigned num_unsaved_files;
2316 struct CXUnsavedFile *unsaved_files;
2317 unsigned options;
2318 int result;
2319};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002320
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002321static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002322 ReparseTranslationUnitInfo *RTUI =
2323 static_cast<ReparseTranslationUnitInfo*>(UserData);
2324 CXTranslationUnit TU = RTUI->TU;
2325 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2326 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2327 unsigned options = RTUI->options;
2328 (void) options;
2329 RTUI->result = 1;
2330
Douglas Gregorabc563f2010-07-19 21:46:24 +00002331 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002332 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002333
2334 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2335 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002336
2337 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2338 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2339 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2340 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002341 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002342 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2343 Buffer));
2344 }
2345
Douglas Gregor593b0c12010-09-23 18:47:53 +00002346 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2347 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002348}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002349
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002350int clang_reparseTranslationUnit(CXTranslationUnit TU,
2351 unsigned num_unsaved_files,
2352 struct CXUnsavedFile *unsaved_files,
2353 unsigned options) {
2354 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2355 options, 0 };
2356 llvm::CrashRecoveryContext CRC;
2357
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002358 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002359 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002360 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2361 return 1;
2362 }
2363
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002364
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002365 return RTUI.result;
2366}
2367
Douglas Gregordf95a132010-08-09 20:45:32 +00002368
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002369CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002370 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002371 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002372
Steve Naroff77accc12009-09-03 18:19:54 +00002373 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002374 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002375}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002376
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002377CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002378 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002379 return Result;
2380}
2381
Ted Kremenekfb480492010-01-13 21:46:36 +00002382} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002383
Ted Kremenekfb480492010-01-13 21:46:36 +00002384//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002385// CXSourceLocation and CXSourceRange Operations.
2386//===----------------------------------------------------------------------===//
2387
Douglas Gregorb9790342010-01-22 21:44:22 +00002388extern "C" {
2389CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002390 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002391 return Result;
2392}
2393
2394unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002395 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2396 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2397 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002398}
2399
2400CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2401 CXFile file,
2402 unsigned line,
2403 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002404 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002405 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002406
Douglas Gregorb9790342010-01-22 21:44:22 +00002407 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2408 SourceLocation SLoc
2409 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002410 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002411 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002412 if (SLoc.isInvalid()) return clang_getNullLocation();
2413
2414 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2415}
2416
2417CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2418 CXFile file,
2419 unsigned offset) {
2420 if (!tu || !file)
2421 return clang_getNullLocation();
2422
2423 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2424 SourceLocation Start
2425 = CXXUnit->getSourceManager().getLocation(
2426 static_cast<const FileEntry *>(file),
2427 1, 1);
2428 if (Start.isInvalid()) return clang_getNullLocation();
2429
2430 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2431
2432 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002433
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002434 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002435}
2436
Douglas Gregor5352ac02010-01-28 00:27:43 +00002437CXSourceRange clang_getNullRange() {
2438 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2439 return Result;
2440}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002441
Douglas Gregor5352ac02010-01-28 00:27:43 +00002442CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2443 if (begin.ptr_data[0] != end.ptr_data[0] ||
2444 begin.ptr_data[1] != end.ptr_data[1])
2445 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002446
2447 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002448 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002449 return Result;
2450}
2451
Douglas Gregor46766dc2010-01-26 19:19:08 +00002452void clang_getInstantiationLocation(CXSourceLocation location,
2453 CXFile *file,
2454 unsigned *line,
2455 unsigned *column,
2456 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002457 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2458
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002459 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002460 if (file)
2461 *file = 0;
2462 if (line)
2463 *line = 0;
2464 if (column)
2465 *column = 0;
2466 if (offset)
2467 *offset = 0;
2468 return;
2469 }
2470
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002471 const SourceManager &SM =
2472 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002473 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002474
2475 if (file)
2476 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2477 if (line)
2478 *line = SM.getInstantiationLineNumber(InstLoc);
2479 if (column)
2480 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002481 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002482 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002483}
2484
Douglas Gregora9b06d42010-11-09 06:24:54 +00002485void clang_getSpellingLocation(CXSourceLocation location,
2486 CXFile *file,
2487 unsigned *line,
2488 unsigned *column,
2489 unsigned *offset) {
2490 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2491
2492 if (!location.ptr_data[0] || Loc.isInvalid()) {
2493 if (file)
2494 *file = 0;
2495 if (line)
2496 *line = 0;
2497 if (column)
2498 *column = 0;
2499 if (offset)
2500 *offset = 0;
2501 return;
2502 }
2503
2504 const SourceManager &SM =
2505 *static_cast<const SourceManager*>(location.ptr_data[0]);
2506 SourceLocation SpellLoc = Loc;
2507 if (SpellLoc.isMacroID()) {
2508 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2509 if (SimpleSpellingLoc.isFileID() &&
2510 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2511 SpellLoc = SimpleSpellingLoc;
2512 else
2513 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2514 }
2515
2516 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2517 FileID FID = LocInfo.first;
2518 unsigned FileOffset = LocInfo.second;
2519
2520 if (file)
2521 *file = (void *)SM.getFileEntryForID(FID);
2522 if (line)
2523 *line = SM.getLineNumber(FID, FileOffset);
2524 if (column)
2525 *column = SM.getColumnNumber(FID, FileOffset);
2526 if (offset)
2527 *offset = FileOffset;
2528}
2529
Douglas Gregor1db19de2010-01-19 21:36:55 +00002530CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002531 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002532 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002533 return Result;
2534}
2535
2536CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002537 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002538 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002539 return Result;
2540}
2541
Douglas Gregorb9790342010-01-22 21:44:22 +00002542} // end: extern "C"
2543
Douglas Gregor1db19de2010-01-19 21:36:55 +00002544//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002545// CXFile Operations.
2546//===----------------------------------------------------------------------===//
2547
2548extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002549CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002550 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002551 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002552
Steve Naroff88145032009-10-27 14:35:18 +00002553 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002554 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002555}
2556
2557time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002558 if (!SFile)
2559 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002560
Steve Naroff88145032009-10-27 14:35:18 +00002561 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2562 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002563}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002564
Douglas Gregorb9790342010-01-22 21:44:22 +00002565CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2566 if (!tu)
2567 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002568
Douglas Gregorb9790342010-01-22 21:44:22 +00002569 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002570
Douglas Gregorb9790342010-01-22 21:44:22 +00002571 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002572 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2573 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002574 return const_cast<FileEntry *>(File);
2575}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002576
Ted Kremenekfb480492010-01-13 21:46:36 +00002577} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002578
Ted Kremenekfb480492010-01-13 21:46:36 +00002579//===----------------------------------------------------------------------===//
2580// CXCursor Operations.
2581//===----------------------------------------------------------------------===//
2582
Ted Kremenekfb480492010-01-13 21:46:36 +00002583static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002584 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2585 return getDeclFromExpr(CE->getSubExpr());
2586
Ted Kremenekfb480492010-01-13 21:46:36 +00002587 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2588 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002589 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2590 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002591 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2592 return ME->getMemberDecl();
2593 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2594 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002595 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2596 return PRE->getProperty();
2597
Ted Kremenekfb480492010-01-13 21:46:36 +00002598 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2599 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002600 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2601 if (!CE->isElidable())
2602 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002603 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2604 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002605
Douglas Gregordb1314e2010-10-01 21:11:22 +00002606 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2607 return PE->getProtocol();
2608
Ted Kremenekfb480492010-01-13 21:46:36 +00002609 return 0;
2610}
2611
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002612static SourceLocation getLocationFromExpr(Expr *E) {
2613 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2614 return /*FIXME:*/Msg->getLeftLoc();
2615 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2616 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002617 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2618 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002619 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2620 return Member->getMemberLoc();
2621 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2622 return Ivar->getLocation();
2623 return E->getLocStart();
2624}
2625
Ted Kremenekfb480492010-01-13 21:46:36 +00002626extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002627
2628unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002629 CXCursorVisitor visitor,
2630 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002631 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002632
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002633 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2634 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002635 return CursorVis.VisitChildren(parent);
2636}
2637
David Chisnall3387c652010-11-03 14:12:26 +00002638#ifndef __has_feature
2639#define __has_feature(x) 0
2640#endif
2641#if __has_feature(blocks)
2642typedef enum CXChildVisitResult
2643 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2644
2645static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2646 CXClientData client_data) {
2647 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2648 return block(cursor, parent);
2649}
2650#else
2651// If we are compiled with a compiler that doesn't have native blocks support,
2652// define and call the block manually, so the
2653typedef struct _CXChildVisitResult
2654{
2655 void *isa;
2656 int flags;
2657 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002658 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2659 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002660} *CXCursorVisitorBlock;
2661
2662static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2663 CXClientData client_data) {
2664 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2665 return block->invoke(block, cursor, parent);
2666}
2667#endif
2668
2669
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002670unsigned clang_visitChildrenWithBlock(CXCursor parent,
2671 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002672 return clang_visitChildren(parent, visitWithBlock, block);
2673}
2674
Douglas Gregor78205d42010-01-20 21:45:58 +00002675static CXString getDeclSpelling(Decl *D) {
2676 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2677 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002678 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002679
Douglas Gregor78205d42010-01-20 21:45:58 +00002680 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002681 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002682
Douglas Gregor78205d42010-01-20 21:45:58 +00002683 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2684 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2685 // and returns different names. NamedDecl returns the class name and
2686 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002687 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002688
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002689 if (isa<UsingDirectiveDecl>(D))
2690 return createCXString("");
2691
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002692 llvm::SmallString<1024> S;
2693 llvm::raw_svector_ostream os(S);
2694 ND->printName(os);
2695
2696 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002697}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002698
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002699CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002700 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002701 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002702
Steve Narofff334b4e2009-09-02 18:26:48 +00002703 if (clang_isReference(C.kind)) {
2704 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002705 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002706 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002707 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002708 }
2709 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002710 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002711 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002712 }
2713 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002714 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002715 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002716 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002717 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002718 case CXCursor_CXXBaseSpecifier: {
2719 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2720 return createCXString(B->getType().getAsString());
2721 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002722 case CXCursor_TypeRef: {
2723 TypeDecl *Type = getCursorTypeRef(C).first;
2724 assert(Type && "Missing type decl");
2725
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002726 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2727 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002728 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002729 case CXCursor_TemplateRef: {
2730 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002731 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002732
2733 return createCXString(Template->getNameAsString());
2734 }
Douglas Gregor69319002010-08-31 23:48:11 +00002735
2736 case CXCursor_NamespaceRef: {
2737 NamedDecl *NS = getCursorNamespaceRef(C).first;
2738 assert(NS && "Missing namespace decl");
2739
2740 return createCXString(NS->getNameAsString());
2741 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002742
Douglas Gregora67e03f2010-09-09 21:42:20 +00002743 case CXCursor_MemberRef: {
2744 FieldDecl *Field = getCursorMemberRef(C).first;
2745 assert(Field && "Missing member decl");
2746
2747 return createCXString(Field->getNameAsString());
2748 }
2749
Douglas Gregor36897b02010-09-10 00:22:18 +00002750 case CXCursor_LabelRef: {
2751 LabelStmt *Label = getCursorLabelRef(C).first;
2752 assert(Label && "Missing label");
2753
2754 return createCXString(Label->getID()->getName());
2755 }
2756
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002757 case CXCursor_OverloadedDeclRef: {
2758 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2759 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2760 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2761 return createCXString(ND->getNameAsString());
2762 return createCXString("");
2763 }
2764 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2765 return createCXString(E->getName().getAsString());
2766 OverloadedTemplateStorage *Ovl
2767 = Storage.get<OverloadedTemplateStorage*>();
2768 if (Ovl->size() == 0)
2769 return createCXString("");
2770 return createCXString((*Ovl->begin())->getNameAsString());
2771 }
2772
Daniel Dunbaracca7252009-11-30 20:42:49 +00002773 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002774 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002775 }
2776 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002777
2778 if (clang_isExpression(C.kind)) {
2779 Decl *D = getDeclFromExpr(getCursorExpr(C));
2780 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002781 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002782 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002783 }
2784
Douglas Gregor36897b02010-09-10 00:22:18 +00002785 if (clang_isStatement(C.kind)) {
2786 Stmt *S = getCursorStmt(C);
2787 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2788 return createCXString(Label->getID()->getName());
2789
2790 return createCXString("");
2791 }
2792
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002793 if (C.kind == CXCursor_MacroInstantiation)
2794 return createCXString(getCursorMacroInstantiation(C)->getName()
2795 ->getNameStart());
2796
Douglas Gregor572feb22010-03-18 18:04:21 +00002797 if (C.kind == CXCursor_MacroDefinition)
2798 return createCXString(getCursorMacroDefinition(C)->getName()
2799 ->getNameStart());
2800
Douglas Gregorecdcb882010-10-20 22:00:55 +00002801 if (C.kind == CXCursor_InclusionDirective)
2802 return createCXString(getCursorInclusionDirective(C)->getFileName());
2803
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002804 if (clang_isDeclaration(C.kind))
2805 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002806
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002807 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002808}
2809
Douglas Gregor358559d2010-10-02 22:49:11 +00002810CXString clang_getCursorDisplayName(CXCursor C) {
2811 if (!clang_isDeclaration(C.kind))
2812 return clang_getCursorSpelling(C);
2813
2814 Decl *D = getCursorDecl(C);
2815 if (!D)
2816 return createCXString("");
2817
2818 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2819 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2820 D = FunTmpl->getTemplatedDecl();
2821
2822 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2823 llvm::SmallString<64> Str;
2824 llvm::raw_svector_ostream OS(Str);
2825 OS << Function->getNameAsString();
2826 if (Function->getPrimaryTemplate())
2827 OS << "<>";
2828 OS << "(";
2829 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2830 if (I)
2831 OS << ", ";
2832 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2833 }
2834
2835 if (Function->isVariadic()) {
2836 if (Function->getNumParams())
2837 OS << ", ";
2838 OS << "...";
2839 }
2840 OS << ")";
2841 return createCXString(OS.str());
2842 }
2843
2844 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2845 llvm::SmallString<64> Str;
2846 llvm::raw_svector_ostream OS(Str);
2847 OS << ClassTemplate->getNameAsString();
2848 OS << "<";
2849 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2850 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2851 if (I)
2852 OS << ", ";
2853
2854 NamedDecl *Param = Params->getParam(I);
2855 if (Param->getIdentifier()) {
2856 OS << Param->getIdentifier()->getName();
2857 continue;
2858 }
2859
2860 // There is no parameter name, which makes this tricky. Try to come up
2861 // with something useful that isn't too long.
2862 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2863 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2864 else if (NonTypeTemplateParmDecl *NTTP
2865 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2866 OS << NTTP->getType().getAsString(Policy);
2867 else
2868 OS << "template<...> class";
2869 }
2870
2871 OS << ">";
2872 return createCXString(OS.str());
2873 }
2874
2875 if (ClassTemplateSpecializationDecl *ClassSpec
2876 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2877 // If the type was explicitly written, use that.
2878 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2879 return createCXString(TSInfo->getType().getAsString(Policy));
2880
2881 llvm::SmallString<64> Str;
2882 llvm::raw_svector_ostream OS(Str);
2883 OS << ClassSpec->getNameAsString();
2884 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002885 ClassSpec->getTemplateArgs().data(),
2886 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002887 Policy);
2888 return createCXString(OS.str());
2889 }
2890
2891 return clang_getCursorSpelling(C);
2892}
2893
Ted Kremeneke68fff62010-02-17 00:41:32 +00002894CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002895 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002896 case CXCursor_FunctionDecl:
2897 return createCXString("FunctionDecl");
2898 case CXCursor_TypedefDecl:
2899 return createCXString("TypedefDecl");
2900 case CXCursor_EnumDecl:
2901 return createCXString("EnumDecl");
2902 case CXCursor_EnumConstantDecl:
2903 return createCXString("EnumConstantDecl");
2904 case CXCursor_StructDecl:
2905 return createCXString("StructDecl");
2906 case CXCursor_UnionDecl:
2907 return createCXString("UnionDecl");
2908 case CXCursor_ClassDecl:
2909 return createCXString("ClassDecl");
2910 case CXCursor_FieldDecl:
2911 return createCXString("FieldDecl");
2912 case CXCursor_VarDecl:
2913 return createCXString("VarDecl");
2914 case CXCursor_ParmDecl:
2915 return createCXString("ParmDecl");
2916 case CXCursor_ObjCInterfaceDecl:
2917 return createCXString("ObjCInterfaceDecl");
2918 case CXCursor_ObjCCategoryDecl:
2919 return createCXString("ObjCCategoryDecl");
2920 case CXCursor_ObjCProtocolDecl:
2921 return createCXString("ObjCProtocolDecl");
2922 case CXCursor_ObjCPropertyDecl:
2923 return createCXString("ObjCPropertyDecl");
2924 case CXCursor_ObjCIvarDecl:
2925 return createCXString("ObjCIvarDecl");
2926 case CXCursor_ObjCInstanceMethodDecl:
2927 return createCXString("ObjCInstanceMethodDecl");
2928 case CXCursor_ObjCClassMethodDecl:
2929 return createCXString("ObjCClassMethodDecl");
2930 case CXCursor_ObjCImplementationDecl:
2931 return createCXString("ObjCImplementationDecl");
2932 case CXCursor_ObjCCategoryImplDecl:
2933 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002934 case CXCursor_CXXMethod:
2935 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002936 case CXCursor_UnexposedDecl:
2937 return createCXString("UnexposedDecl");
2938 case CXCursor_ObjCSuperClassRef:
2939 return createCXString("ObjCSuperClassRef");
2940 case CXCursor_ObjCProtocolRef:
2941 return createCXString("ObjCProtocolRef");
2942 case CXCursor_ObjCClassRef:
2943 return createCXString("ObjCClassRef");
2944 case CXCursor_TypeRef:
2945 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002946 case CXCursor_TemplateRef:
2947 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002948 case CXCursor_NamespaceRef:
2949 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002950 case CXCursor_MemberRef:
2951 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002952 case CXCursor_LabelRef:
2953 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002954 case CXCursor_OverloadedDeclRef:
2955 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002956 case CXCursor_UnexposedExpr:
2957 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002958 case CXCursor_BlockExpr:
2959 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002960 case CXCursor_DeclRefExpr:
2961 return createCXString("DeclRefExpr");
2962 case CXCursor_MemberRefExpr:
2963 return createCXString("MemberRefExpr");
2964 case CXCursor_CallExpr:
2965 return createCXString("CallExpr");
2966 case CXCursor_ObjCMessageExpr:
2967 return createCXString("ObjCMessageExpr");
2968 case CXCursor_UnexposedStmt:
2969 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002970 case CXCursor_LabelStmt:
2971 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002972 case CXCursor_InvalidFile:
2973 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002974 case CXCursor_InvalidCode:
2975 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002976 case CXCursor_NoDeclFound:
2977 return createCXString("NoDeclFound");
2978 case CXCursor_NotImplemented:
2979 return createCXString("NotImplemented");
2980 case CXCursor_TranslationUnit:
2981 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002982 case CXCursor_UnexposedAttr:
2983 return createCXString("UnexposedAttr");
2984 case CXCursor_IBActionAttr:
2985 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002986 case CXCursor_IBOutletAttr:
2987 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002988 case CXCursor_IBOutletCollectionAttr:
2989 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002990 case CXCursor_PreprocessingDirective:
2991 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002992 case CXCursor_MacroDefinition:
2993 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002994 case CXCursor_MacroInstantiation:
2995 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002996 case CXCursor_InclusionDirective:
2997 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002998 case CXCursor_Namespace:
2999 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003000 case CXCursor_LinkageSpec:
3001 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003002 case CXCursor_CXXBaseSpecifier:
3003 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003004 case CXCursor_Constructor:
3005 return createCXString("CXXConstructor");
3006 case CXCursor_Destructor:
3007 return createCXString("CXXDestructor");
3008 case CXCursor_ConversionFunction:
3009 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003010 case CXCursor_TemplateTypeParameter:
3011 return createCXString("TemplateTypeParameter");
3012 case CXCursor_NonTypeTemplateParameter:
3013 return createCXString("NonTypeTemplateParameter");
3014 case CXCursor_TemplateTemplateParameter:
3015 return createCXString("TemplateTemplateParameter");
3016 case CXCursor_FunctionTemplate:
3017 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003018 case CXCursor_ClassTemplate:
3019 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003020 case CXCursor_ClassTemplatePartialSpecialization:
3021 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003022 case CXCursor_NamespaceAlias:
3023 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003024 case CXCursor_UsingDirective:
3025 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003026 case CXCursor_UsingDeclaration:
3027 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003028 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003029
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003030 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003031 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003032}
Steve Naroff89922f82009-08-31 00:59:03 +00003033
Ted Kremeneke68fff62010-02-17 00:41:32 +00003034enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3035 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003036 CXClientData client_data) {
3037 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003038
3039 // If our current best cursor is the construction of a temporary object,
3040 // don't replace that cursor with a type reference, because we want
3041 // clang_getCursor() to point at the constructor.
3042 if (clang_isExpression(BestCursor->kind) &&
3043 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3044 cursor.kind == CXCursor_TypeRef)
3045 return CXChildVisit_Recurse;
3046
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003047 *BestCursor = cursor;
3048 return CXChildVisit_Recurse;
3049}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003050
Douglas Gregorb9790342010-01-22 21:44:22 +00003051CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3052 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003053 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003054
Douglas Gregorb9790342010-01-22 21:44:22 +00003055 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003056 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3057
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003058 // Translate the given source location to make it point at the beginning of
3059 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003060 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003061
3062 // Guard against an invalid SourceLocation, or we may assert in one
3063 // of the following calls.
3064 if (SLoc.isInvalid())
3065 return clang_getNullCursor();
3066
Douglas Gregor40749ee2010-11-03 00:35:38 +00003067 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003068 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3069 CXXUnit->getASTContext().getLangOptions());
3070
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003071 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3072 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003073 // FIXME: Would be great to have a "hint" cursor, then walk from that
3074 // hint cursor upward until we find a cursor whose source range encloses
3075 // the region of interest, rather than starting from the translation unit.
3076 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003077 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003078 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003079 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003080 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003081
3082 if (Logging) {
3083 CXFile SearchFile;
3084 unsigned SearchLine, SearchColumn;
3085 CXFile ResultFile;
3086 unsigned ResultLine, ResultColumn;
3087 CXString SearchFileName, ResultFileName, KindSpelling;
3088 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3089
3090 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3091 0);
3092 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3093 &ResultColumn, 0);
3094 SearchFileName = clang_getFileName(SearchFile);
3095 ResultFileName = clang_getFileName(ResultFile);
3096 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3097 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3098 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3099 clang_getCString(KindSpelling),
3100 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3101 clang_disposeString(SearchFileName);
3102 clang_disposeString(ResultFileName);
3103 clang_disposeString(KindSpelling);
3104 }
3105
Ted Kremeneke68fff62010-02-17 00:41:32 +00003106 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003107}
3108
Ted Kremenek73885552009-11-17 19:28:59 +00003109CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003110 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003111}
3112
3113unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003114 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003115}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003116
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003117unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003118 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3119}
3120
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003121unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003122 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3123}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003124
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003125unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003126 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3127}
3128
Douglas Gregor97b98722010-01-19 23:20:36 +00003129unsigned clang_isExpression(enum CXCursorKind K) {
3130 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3131}
3132
3133unsigned clang_isStatement(enum CXCursorKind K) {
3134 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3135}
3136
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003137unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3138 return K == CXCursor_TranslationUnit;
3139}
3140
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003141unsigned clang_isPreprocessing(enum CXCursorKind K) {
3142 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3143}
3144
Ted Kremenekad6eff62010-03-08 21:17:29 +00003145unsigned clang_isUnexposed(enum CXCursorKind K) {
3146 switch (K) {
3147 case CXCursor_UnexposedDecl:
3148 case CXCursor_UnexposedExpr:
3149 case CXCursor_UnexposedStmt:
3150 case CXCursor_UnexposedAttr:
3151 return true;
3152 default:
3153 return false;
3154 }
3155}
3156
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003157CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003158 return C.kind;
3159}
3160
Douglas Gregor98258af2010-01-18 22:46:11 +00003161CXSourceLocation clang_getCursorLocation(CXCursor C) {
3162 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003163 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003164 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003165 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3166 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003167 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003168 }
3169
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003170 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003171 std::pair<ObjCProtocolDecl *, SourceLocation> P
3172 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003173 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003174 }
3175
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003176 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003177 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3178 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003179 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003180 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003181
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003182 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003183 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003184 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003185 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003186
3187 case CXCursor_TemplateRef: {
3188 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3189 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3190 }
3191
Douglas Gregor69319002010-08-31 23:48:11 +00003192 case CXCursor_NamespaceRef: {
3193 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3194 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3195 }
3196
Douglas Gregora67e03f2010-09-09 21:42:20 +00003197 case CXCursor_MemberRef: {
3198 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3199 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3200 }
3201
Ted Kremenek3064ef92010-08-27 21:34:58 +00003202 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003203 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3204 if (!BaseSpec)
3205 return clang_getNullLocation();
3206
3207 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3208 return cxloc::translateSourceLocation(getCursorContext(C),
3209 TSInfo->getTypeLoc().getBeginLoc());
3210
3211 return cxloc::translateSourceLocation(getCursorContext(C),
3212 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003213 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003214
Douglas Gregor36897b02010-09-10 00:22:18 +00003215 case CXCursor_LabelRef: {
3216 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3217 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3218 }
3219
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003220 case CXCursor_OverloadedDeclRef:
3221 return cxloc::translateSourceLocation(getCursorContext(C),
3222 getCursorOverloadedDeclRef(C).second);
3223
Douglas Gregorf46034a2010-01-18 23:41:10 +00003224 default:
3225 // FIXME: Need a way to enumerate all non-reference cases.
3226 llvm_unreachable("Missed a reference kind");
3227 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003228 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003229
3230 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003231 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003232 getLocationFromExpr(getCursorExpr(C)));
3233
Douglas Gregor36897b02010-09-10 00:22:18 +00003234 if (clang_isStatement(C.kind))
3235 return cxloc::translateSourceLocation(getCursorContext(C),
3236 getCursorStmt(C)->getLocStart());
3237
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003238 if (C.kind == CXCursor_PreprocessingDirective) {
3239 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3240 return cxloc::translateSourceLocation(getCursorContext(C), L);
3241 }
Douglas Gregor48072312010-03-18 15:23:44 +00003242
3243 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003244 SourceLocation L
3245 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003246 return cxloc::translateSourceLocation(getCursorContext(C), L);
3247 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003248
3249 if (C.kind == CXCursor_MacroDefinition) {
3250 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3251 return cxloc::translateSourceLocation(getCursorContext(C), L);
3252 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003253
3254 if (C.kind == CXCursor_InclusionDirective) {
3255 SourceLocation L
3256 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3257 return cxloc::translateSourceLocation(getCursorContext(C), L);
3258 }
3259
Ted Kremenek9a700d22010-05-12 06:16:13 +00003260 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003261 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003262
Douglas Gregorf46034a2010-01-18 23:41:10 +00003263 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003264 SourceLocation Loc = D->getLocation();
3265 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3266 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003267 // FIXME: Multiple variables declared in a single declaration
3268 // currently lack the information needed to correctly determine their
3269 // ranges when accounting for the type-specifier. We use context
3270 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3271 // and if so, whether it is the first decl.
3272 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3273 if (!cxcursor::isFirstInDeclGroup(C))
3274 Loc = VD->getLocation();
3275 }
3276
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003277 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003278}
Douglas Gregora7bde202010-01-19 00:34:46 +00003279
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003280} // end extern "C"
3281
3282static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003283 if (clang_isReference(C.kind)) {
3284 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003285 case CXCursor_ObjCSuperClassRef:
3286 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003287
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003288 case CXCursor_ObjCProtocolRef:
3289 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003290
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003291 case CXCursor_ObjCClassRef:
3292 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003293
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003294 case CXCursor_TypeRef:
3295 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003296
3297 case CXCursor_TemplateRef:
3298 return getCursorTemplateRef(C).second;
3299
Douglas Gregor69319002010-08-31 23:48:11 +00003300 case CXCursor_NamespaceRef:
3301 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003302
3303 case CXCursor_MemberRef:
3304 return getCursorMemberRef(C).second;
3305
Ted Kremenek3064ef92010-08-27 21:34:58 +00003306 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003307 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003308
Douglas Gregor36897b02010-09-10 00:22:18 +00003309 case CXCursor_LabelRef:
3310 return getCursorLabelRef(C).second;
3311
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003312 case CXCursor_OverloadedDeclRef:
3313 return getCursorOverloadedDeclRef(C).second;
3314
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003315 default:
3316 // FIXME: Need a way to enumerate all non-reference cases.
3317 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003318 }
3319 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003320
3321 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003322 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003323
3324 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003325 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003326
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003327 if (C.kind == CXCursor_PreprocessingDirective)
3328 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003329
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003330 if (C.kind == CXCursor_MacroInstantiation)
3331 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003332
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003333 if (C.kind == CXCursor_MacroDefinition)
3334 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003335
3336 if (C.kind == CXCursor_InclusionDirective)
3337 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3338
Ted Kremenek007a7c92010-11-01 23:26:51 +00003339 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3340 Decl *D = cxcursor::getCursorDecl(C);
3341 SourceRange R = D->getSourceRange();
3342 // FIXME: Multiple variables declared in a single declaration
3343 // currently lack the information needed to correctly determine their
3344 // ranges when accounting for the type-specifier. We use context
3345 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3346 // and if so, whether it is the first decl.
3347 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3348 if (!cxcursor::isFirstInDeclGroup(C))
3349 R.setBegin(VD->getLocation());
3350 }
3351 return R;
3352 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003353 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003354
3355extern "C" {
3356
3357CXSourceRange clang_getCursorExtent(CXCursor C) {
3358 SourceRange R = getRawCursorExtent(C);
3359 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003360 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003361
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003362 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003363}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003364
3365CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003366 if (clang_isInvalid(C.kind))
3367 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003368
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003369 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003370 if (clang_isDeclaration(C.kind)) {
3371 Decl *D = getCursorDecl(C);
3372 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3373 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3374 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3375 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3376 if (ObjCForwardProtocolDecl *Protocols
3377 = dyn_cast<ObjCForwardProtocolDecl>(D))
3378 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3379
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003380 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003381 }
3382
Douglas Gregor97b98722010-01-19 23:20:36 +00003383 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003384 Expr *E = getCursorExpr(C);
3385 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003386 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003387 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003388
3389 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3390 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3391
Douglas Gregor97b98722010-01-19 23:20:36 +00003392 return clang_getNullCursor();
3393 }
3394
Douglas Gregor36897b02010-09-10 00:22:18 +00003395 if (clang_isStatement(C.kind)) {
3396 Stmt *S = getCursorStmt(C);
3397 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3398 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3399 getCursorASTUnit(C));
3400
3401 return clang_getNullCursor();
3402 }
3403
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003404 if (C.kind == CXCursor_MacroInstantiation) {
3405 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3406 return MakeMacroDefinitionCursor(Def, CXXUnit);
3407 }
3408
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003409 if (!clang_isReference(C.kind))
3410 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003411
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003412 switch (C.kind) {
3413 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003414 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003415
3416 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003417 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003418
3419 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003420 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003421
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003422 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003423 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003424
3425 case CXCursor_TemplateRef:
3426 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3427
Douglas Gregor69319002010-08-31 23:48:11 +00003428 case CXCursor_NamespaceRef:
3429 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3430
Douglas Gregora67e03f2010-09-09 21:42:20 +00003431 case CXCursor_MemberRef:
3432 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3433
Ted Kremenek3064ef92010-08-27 21:34:58 +00003434 case CXCursor_CXXBaseSpecifier: {
3435 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3436 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3437 CXXUnit));
3438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003439
Douglas Gregor36897b02010-09-10 00:22:18 +00003440 case CXCursor_LabelRef:
3441 // FIXME: We end up faking the "parent" declaration here because we
3442 // don't want to make CXCursor larger.
3443 return MakeCXCursor(getCursorLabelRef(C).first,
3444 CXXUnit->getASTContext().getTranslationUnitDecl(),
3445 CXXUnit);
3446
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003447 case CXCursor_OverloadedDeclRef:
3448 return C;
3449
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003450 default:
3451 // We would prefer to enumerate all non-reference cursor kinds here.
3452 llvm_unreachable("Unhandled reference cursor kind");
3453 break;
3454 }
3455 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003457 return clang_getNullCursor();
3458}
3459
Douglas Gregorb6998662010-01-19 19:34:47 +00003460CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003461 if (clang_isInvalid(C.kind))
3462 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003463
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003464 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003465
Douglas Gregorb6998662010-01-19 19:34:47 +00003466 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003467 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003468 C = clang_getCursorReferenced(C);
3469 WasReference = true;
3470 }
3471
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003472 if (C.kind == CXCursor_MacroInstantiation)
3473 return clang_getCursorReferenced(C);
3474
Douglas Gregorb6998662010-01-19 19:34:47 +00003475 if (!clang_isDeclaration(C.kind))
3476 return clang_getNullCursor();
3477
3478 Decl *D = getCursorDecl(C);
3479 if (!D)
3480 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003481
Douglas Gregorb6998662010-01-19 19:34:47 +00003482 switch (D->getKind()) {
3483 // Declaration kinds that don't really separate the notions of
3484 // declaration and definition.
3485 case Decl::Namespace:
3486 case Decl::Typedef:
3487 case Decl::TemplateTypeParm:
3488 case Decl::EnumConstant:
3489 case Decl::Field:
3490 case Decl::ObjCIvar:
3491 case Decl::ObjCAtDefsField:
3492 case Decl::ImplicitParam:
3493 case Decl::ParmVar:
3494 case Decl::NonTypeTemplateParm:
3495 case Decl::TemplateTemplateParm:
3496 case Decl::ObjCCategoryImpl:
3497 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003498 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003499 case Decl::LinkageSpec:
3500 case Decl::ObjCPropertyImpl:
3501 case Decl::FileScopeAsm:
3502 case Decl::StaticAssert:
3503 case Decl::Block:
3504 return C;
3505
3506 // Declaration kinds that don't make any sense here, but are
3507 // nonetheless harmless.
3508 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003509 break;
3510
3511 // Declaration kinds for which the definition is not resolvable.
3512 case Decl::UnresolvedUsingTypename:
3513 case Decl::UnresolvedUsingValue:
3514 break;
3515
3516 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003517 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3518 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003519
3520 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003521 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003522
3523 case Decl::Enum:
3524 case Decl::Record:
3525 case Decl::CXXRecord:
3526 case Decl::ClassTemplateSpecialization:
3527 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003528 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003529 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003530 return clang_getNullCursor();
3531
3532 case Decl::Function:
3533 case Decl::CXXMethod:
3534 case Decl::CXXConstructor:
3535 case Decl::CXXDestructor:
3536 case Decl::CXXConversion: {
3537 const FunctionDecl *Def = 0;
3538 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003539 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003540 return clang_getNullCursor();
3541 }
3542
3543 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003544 // Ask the variable if it has a definition.
3545 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3546 return MakeCXCursor(Def, CXXUnit);
3547 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003548 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003549
Douglas Gregorb6998662010-01-19 19:34:47 +00003550 case Decl::FunctionTemplate: {
3551 const FunctionDecl *Def = 0;
3552 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003553 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003554 return clang_getNullCursor();
3555 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003556
Douglas Gregorb6998662010-01-19 19:34:47 +00003557 case Decl::ClassTemplate: {
3558 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003559 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003560 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003561 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003562 return clang_getNullCursor();
3563 }
3564
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003565 case Decl::Using:
3566 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3567 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003568
3569 case Decl::UsingShadow:
3570 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003571 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003572 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003573
3574 case Decl::ObjCMethod: {
3575 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3576 if (Method->isThisDeclarationADefinition())
3577 return C;
3578
3579 // Dig out the method definition in the associated
3580 // @implementation, if we have it.
3581 // FIXME: The ASTs should make finding the definition easier.
3582 if (ObjCInterfaceDecl *Class
3583 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3584 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3585 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3586 Method->isInstanceMethod()))
3587 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003588 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003589
3590 return clang_getNullCursor();
3591 }
3592
3593 case Decl::ObjCCategory:
3594 if (ObjCCategoryImplDecl *Impl
3595 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003596 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003597 return clang_getNullCursor();
3598
3599 case Decl::ObjCProtocol:
3600 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3601 return C;
3602 return clang_getNullCursor();
3603
3604 case Decl::ObjCInterface:
3605 // There are two notions of a "definition" for an Objective-C
3606 // class: the interface and its implementation. When we resolved a
3607 // reference to an Objective-C class, produce the @interface as
3608 // the definition; when we were provided with the interface,
3609 // produce the @implementation as the definition.
3610 if (WasReference) {
3611 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3612 return C;
3613 } else if (ObjCImplementationDecl *Impl
3614 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003615 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003616 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003617
Douglas Gregorb6998662010-01-19 19:34:47 +00003618 case Decl::ObjCProperty:
3619 // FIXME: We don't really know where to find the
3620 // ObjCPropertyImplDecls that implement this property.
3621 return clang_getNullCursor();
3622
3623 case Decl::ObjCCompatibleAlias:
3624 if (ObjCInterfaceDecl *Class
3625 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3626 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003627 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003628
Douglas Gregorb6998662010-01-19 19:34:47 +00003629 return clang_getNullCursor();
3630
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003631 case Decl::ObjCForwardProtocol:
3632 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3633 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003634
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003635 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003636 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003637 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003638
3639 case Decl::Friend:
3640 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003641 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003642 return clang_getNullCursor();
3643
3644 case Decl::FriendTemplate:
3645 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003646 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003647 return clang_getNullCursor();
3648 }
3649
3650 return clang_getNullCursor();
3651}
3652
3653unsigned clang_isCursorDefinition(CXCursor C) {
3654 if (!clang_isDeclaration(C.kind))
3655 return 0;
3656
3657 return clang_getCursorDefinition(C) == C;
3658}
3659
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003660unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003661 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003662 return 0;
3663
3664 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3665 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3666 return E->getNumDecls();
3667
3668 if (OverloadedTemplateStorage *S
3669 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3670 return S->size();
3671
3672 Decl *D = Storage.get<Decl*>();
3673 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003674 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003675 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3676 return Classes->size();
3677 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3678 return Protocols->protocol_size();
3679
3680 return 0;
3681}
3682
3683CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003684 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003685 return clang_getNullCursor();
3686
3687 if (index >= clang_getNumOverloadedDecls(cursor))
3688 return clang_getNullCursor();
3689
3690 ASTUnit *Unit = getCursorASTUnit(cursor);
3691 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3692 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3693 return MakeCXCursor(E->decls_begin()[index], Unit);
3694
3695 if (OverloadedTemplateStorage *S
3696 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3697 return MakeCXCursor(S->begin()[index], Unit);
3698
3699 Decl *D = Storage.get<Decl*>();
3700 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3701 // FIXME: This is, unfortunately, linear time.
3702 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3703 std::advance(Pos, index);
3704 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3705 }
3706
3707 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3708 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3709
3710 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3711 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3712
3713 return clang_getNullCursor();
3714}
3715
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003716void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003717 const char **startBuf,
3718 const char **endBuf,
3719 unsigned *startLine,
3720 unsigned *startColumn,
3721 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003722 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003723 assert(getCursorDecl(C) && "CXCursor has null decl");
3724 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003725 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3726 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003727
Steve Naroff4ade6d62009-09-23 17:52:52 +00003728 SourceManager &SM = FD->getASTContext().getSourceManager();
3729 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3730 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3731 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3732 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3733 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3734 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3735}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003736
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003737void clang_enableStackTraces(void) {
3738 llvm::sys::PrintStackTraceOnErrorSignal();
3739}
3740
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003741void clang_executeOnThread(void (*fn)(void*), void *user_data,
3742 unsigned stack_size) {
3743 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3744}
3745
Ted Kremenekfb480492010-01-13 21:46:36 +00003746} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003747
Ted Kremenekfb480492010-01-13 21:46:36 +00003748//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003749// Token-based Operations.
3750//===----------------------------------------------------------------------===//
3751
3752/* CXToken layout:
3753 * int_data[0]: a CXTokenKind
3754 * int_data[1]: starting token location
3755 * int_data[2]: token length
3756 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003757 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003758 * otherwise unused.
3759 */
3760extern "C" {
3761
3762CXTokenKind clang_getTokenKind(CXToken CXTok) {
3763 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3764}
3765
3766CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3767 switch (clang_getTokenKind(CXTok)) {
3768 case CXToken_Identifier:
3769 case CXToken_Keyword:
3770 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003771 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3772 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003773
3774 case CXToken_Literal: {
3775 // We have stashed the starting pointer in the ptr_data field. Use it.
3776 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003777 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003778 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003779
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003780 case CXToken_Punctuation:
3781 case CXToken_Comment:
3782 break;
3783 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003784
3785 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003786 // deconstructing the source location.
3787 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3788 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003789 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003790
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003791 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3792 std::pair<FileID, unsigned> LocInfo
3793 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003794 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003795 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003796 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3797 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003798 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003799
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003800 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003801}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003802
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003803CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3804 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3805 if (!CXXUnit)
3806 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003807
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003808 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3809 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3810}
3811
3812CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3813 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003814 if (!CXXUnit)
3815 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003816
3817 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003818 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3819}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003820
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003821void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3822 CXToken **Tokens, unsigned *NumTokens) {
3823 if (Tokens)
3824 *Tokens = 0;
3825 if (NumTokens)
3826 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003827
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003828 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3829 if (!CXXUnit || !Tokens || !NumTokens)
3830 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003831
Douglas Gregorbdf60622010-03-05 21:16:25 +00003832 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3833
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003834 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003835 if (R.isInvalid())
3836 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003837
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003838 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3839 std::pair<FileID, unsigned> BeginLocInfo
3840 = SourceMgr.getDecomposedLoc(R.getBegin());
3841 std::pair<FileID, unsigned> EndLocInfo
3842 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003844 // Cannot tokenize across files.
3845 if (BeginLocInfo.first != EndLocInfo.first)
3846 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
3848 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003849 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003850 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003851 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003852 if (Invalid)
3853 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003854
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003855 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3856 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003857 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003858 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003860 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003861 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003862 llvm::SmallVector<CXToken, 32> CXTokens;
3863 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003864 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003865 do {
3866 // Lex the next token
3867 Lex.LexFromRawLexer(Tok);
3868 if (Tok.is(tok::eof))
3869 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003870
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003871 // Initialize the CXToken.
3872 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003873
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 // - Common fields
3875 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3876 CXTok.int_data[2] = Tok.getLength();
3877 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003878
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003879 // - Kind-specific fields
3880 if (Tok.isLiteral()) {
3881 CXTok.int_data[0] = CXToken_Literal;
3882 CXTok.ptr_data = (void *)Tok.getLiteralData();
3883 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003884 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003885 std::pair<FileID, unsigned> LocInfo
3886 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003887 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003888 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003889 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3890 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003891 return;
3892
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003893 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 IdentifierInfo *II
3895 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003896
David Chisnall096428b2010-10-13 21:44:48 +00003897 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003898 CXTok.int_data[0] = CXToken_Keyword;
3899 }
3900 else {
3901 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3902 CXToken_Identifier
3903 : CXToken_Keyword;
3904 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003905 CXTok.ptr_data = II;
3906 } else if (Tok.is(tok::comment)) {
3907 CXTok.int_data[0] = CXToken_Comment;
3908 CXTok.ptr_data = 0;
3909 } else {
3910 CXTok.int_data[0] = CXToken_Punctuation;
3911 CXTok.ptr_data = 0;
3912 }
3913 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003914 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003915 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003916
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003917 if (CXTokens.empty())
3918 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003919
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003920 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3921 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3922 *NumTokens = CXTokens.size();
3923}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003924
Ted Kremenek6db61092010-05-05 00:55:15 +00003925void clang_disposeTokens(CXTranslationUnit TU,
3926 CXToken *Tokens, unsigned NumTokens) {
3927 free(Tokens);
3928}
3929
3930} // end: extern "C"
3931
3932//===----------------------------------------------------------------------===//
3933// Token annotation APIs.
3934//===----------------------------------------------------------------------===//
3935
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003936typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003937static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3938 CXCursor parent,
3939 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003940namespace {
3941class AnnotateTokensWorker {
3942 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003943 CXToken *Tokens;
3944 CXCursor *Cursors;
3945 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003946 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003947 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003948 CursorVisitor AnnotateVis;
3949 SourceManager &SrcMgr;
3950
3951 bool MoreTokens() const { return TokIdx < NumTokens; }
3952 unsigned NextToken() const { return TokIdx; }
3953 void AdvanceToken() { ++TokIdx; }
3954 SourceLocation GetTokenLoc(unsigned tokI) {
3955 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3956 }
3957
Ted Kremenek6db61092010-05-05 00:55:15 +00003958public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003959 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003960 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3961 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003962 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003963 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003964 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3965 Decl::MaxPCHLevel, RegionOfInterest),
3966 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003967
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003968 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003969 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003970 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003971 void AnnotateTokens() {
3972 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3973 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003974};
3975}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003976
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003977void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3978 // Walk the AST within the region of interest, annotating tokens
3979 // along the way.
3980 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003981
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003982 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3983 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003984 if (Pos != Annotated.end() &&
3985 (clang_isInvalid(Cursors[I].kind) ||
3986 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003987 Cursors[I] = Pos->second;
3988 }
3989
3990 // Finish up annotating any tokens left.
3991 if (!MoreTokens())
3992 return;
3993
3994 const CXCursor &C = clang_getNullCursor();
3995 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3996 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3997 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003998 }
3999}
4000
Ted Kremenek6db61092010-05-05 00:55:15 +00004001enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004002AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004003 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004004 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004005 if (cursorRange.isInvalid())
4006 return CXChildVisit_Recurse;
4007
Douglas Gregor4419b672010-10-21 06:10:04 +00004008 if (clang_isPreprocessing(cursor.kind)) {
4009 // For macro instantiations, just note where the beginning of the macro
4010 // instantiation occurs.
4011 if (cursor.kind == CXCursor_MacroInstantiation) {
4012 Annotated[Loc.int_data] = cursor;
4013 return CXChildVisit_Recurse;
4014 }
4015
Douglas Gregor4419b672010-10-21 06:10:04 +00004016 // Items in the preprocessing record are kept separate from items in
4017 // declarations, so we keep a separate token index.
4018 unsigned SavedTokIdx = TokIdx;
4019 TokIdx = PreprocessingTokIdx;
4020
4021 // Skip tokens up until we catch up to the beginning of the preprocessing
4022 // entry.
4023 while (MoreTokens()) {
4024 const unsigned I = NextToken();
4025 SourceLocation TokLoc = GetTokenLoc(I);
4026 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4027 case RangeBefore:
4028 AdvanceToken();
4029 continue;
4030 case RangeAfter:
4031 case RangeOverlap:
4032 break;
4033 }
4034 break;
4035 }
4036
4037 // Look at all of the tokens within this range.
4038 while (MoreTokens()) {
4039 const unsigned I = NextToken();
4040 SourceLocation TokLoc = GetTokenLoc(I);
4041 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4042 case RangeBefore:
4043 assert(0 && "Infeasible");
4044 case RangeAfter:
4045 break;
4046 case RangeOverlap:
4047 Cursors[I] = cursor;
4048 AdvanceToken();
4049 continue;
4050 }
4051 break;
4052 }
4053
4054 // Save the preprocessing token index; restore the non-preprocessing
4055 // token index.
4056 PreprocessingTokIdx = TokIdx;
4057 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004058 return CXChildVisit_Recurse;
4059 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004060
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004061 if (cursorRange.isInvalid())
4062 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004063
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004064 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4065
Ted Kremeneka333c662010-05-12 05:29:33 +00004066 // Adjust the annotated range based specific declarations.
4067 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4068 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004069 Decl *D = cxcursor::getCursorDecl(cursor);
4070 // Don't visit synthesized ObjC methods, since they have no syntatic
4071 // representation in the source.
4072 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4073 if (MD->isSynthesized())
4074 return CXChildVisit_Continue;
4075 }
4076 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004077 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4078 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004079 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004080 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004081 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004082 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004083 }
4084 }
4085 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004086
Ted Kremenek3f404602010-08-14 01:14:06 +00004087 // If the location of the cursor occurs within a macro instantiation, record
4088 // the spelling location of the cursor in our annotation map. We can then
4089 // paper over the token labelings during a post-processing step to try and
4090 // get cursor mappings for tokens that are the *arguments* of a macro
4091 // instantiation.
4092 if (L.isMacroID()) {
4093 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4094 // Only invalidate the old annotation if it isn't part of a preprocessing
4095 // directive. Here we assume that the default construction of CXCursor
4096 // results in CXCursor.kind being an initialized value (i.e., 0). If
4097 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004098
Ted Kremenek3f404602010-08-14 01:14:06 +00004099 CXCursor &oldC = Annotated[rawEncoding];
4100 if (!clang_isPreprocessing(oldC.kind))
4101 oldC = cursor;
4102 }
4103
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004104 const enum CXCursorKind K = clang_getCursorKind(parent);
4105 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004106 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4107 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004108
4109 while (MoreTokens()) {
4110 const unsigned I = NextToken();
4111 SourceLocation TokLoc = GetTokenLoc(I);
4112 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4113 case RangeBefore:
4114 Cursors[I] = updateC;
4115 AdvanceToken();
4116 continue;
4117 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004118 case RangeOverlap:
4119 break;
4120 }
4121 break;
4122 }
4123
4124 // Visit children to get their cursor information.
4125 const unsigned BeforeChildren = NextToken();
4126 VisitChildren(cursor);
4127 const unsigned AfterChildren = NextToken();
4128
4129 // Adjust 'Last' to the last token within the extent of the cursor.
4130 while (MoreTokens()) {
4131 const unsigned I = NextToken();
4132 SourceLocation TokLoc = GetTokenLoc(I);
4133 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4134 case RangeBefore:
4135 assert(0 && "Infeasible");
4136 case RangeAfter:
4137 break;
4138 case RangeOverlap:
4139 Cursors[I] = updateC;
4140 AdvanceToken();
4141 continue;
4142 }
4143 break;
4144 }
4145 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004146
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004147 // Scan the tokens that are at the beginning of the cursor, but are not
4148 // capture by the child cursors.
4149
4150 // For AST elements within macros, rely on a post-annotate pass to
4151 // to correctly annotate the tokens with cursors. Otherwise we can
4152 // get confusing results of having tokens that map to cursors that really
4153 // are expanded by an instantiation.
4154 if (L.isMacroID())
4155 cursor = clang_getNullCursor();
4156
4157 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4158 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4159 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004160
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004161 Cursors[I] = cursor;
4162 }
4163 // Scan the tokens that are at the end of the cursor, but are not captured
4164 // but the child cursors.
4165 for (unsigned I = AfterChildren; I != Last; ++I)
4166 Cursors[I] = cursor;
4167
4168 TokIdx = Last;
4169 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004170}
4171
Ted Kremenek6db61092010-05-05 00:55:15 +00004172static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4173 CXCursor parent,
4174 CXClientData client_data) {
4175 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4176}
4177
Ted Kremenekab979612010-11-11 08:05:23 +00004178// This gets run a separate thread to avoid stack blowout.
4179static void runAnnotateTokensWorker(void *UserData) {
4180 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4181}
4182
Ted Kremenek6db61092010-05-05 00:55:15 +00004183extern "C" {
4184
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004185void clang_annotateTokens(CXTranslationUnit TU,
4186 CXToken *Tokens, unsigned NumTokens,
4187 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004188
4189 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004190 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004191
Douglas Gregor4419b672010-10-21 06:10:04 +00004192 // Any token we don't specifically annotate will have a NULL cursor.
4193 CXCursor C = clang_getNullCursor();
4194 for (unsigned I = 0; I != NumTokens; ++I)
4195 Cursors[I] = C;
4196
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004197 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004198 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004199 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004200
Douglas Gregorbdf60622010-03-05 21:16:25 +00004201 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004202
Douglas Gregor0396f462010-03-19 05:22:59 +00004203 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004204 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004205 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4206 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004207 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4208 clang_getTokenLocation(TU,
4209 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004210
Douglas Gregor0396f462010-03-19 05:22:59 +00004211 // A mapping from the source locations found when re-lexing or traversing the
4212 // region of interest to the corresponding cursors.
4213 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004214
4215 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004216 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004217 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4218 std::pair<FileID, unsigned> BeginLocInfo
4219 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4220 std::pair<FileID, unsigned> EndLocInfo
4221 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004222
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004223 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004224 bool Invalid = false;
4225 if (BeginLocInfo.first == EndLocInfo.first &&
4226 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4227 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004228 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4229 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004230 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004231 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004232 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004233
4234 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004235 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004236 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004237 Token Tok;
4238 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004240 reprocess:
4241 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4242 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004243 // don't see it while preprocessing these tokens later, but keep track
4244 // of all of the token locations inside this preprocessing directive so
4245 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004246 //
4247 // FIXME: Some simple tests here could identify macro definitions and
4248 // #undefs, to provide specific cursor kinds for those.
4249 std::vector<SourceLocation> Locations;
4250 do {
4251 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004254
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004255 using namespace cxcursor;
4256 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004257 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4258 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004259 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004260 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4261 Annotated[Locations[I].getRawEncoding()] = Cursor;
4262 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004263
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004264 if (Tok.isAtStartOfLine())
4265 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004266
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004267 continue;
4268 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004269
Douglas Gregor48072312010-03-18 15:23:44 +00004270 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004271 break;
4272 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004273 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004274
Douglas Gregor0396f462010-03-19 05:22:59 +00004275 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004276 // a specific cursor.
4277 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4278 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004279
4280 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004281 // FIXME: We use a ridiculous stack size here because the data-recursion
4282 // algorithm uses a large stack frame than the non-data recursive version,
4283 // and AnnotationTokensWorker currently transforms the data-recursion
4284 // algorithm back into a traditional recursion by explicitly calling
4285 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004286 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004287 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4288 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004289 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4290 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004291}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004292} // end: extern "C"
4293
4294//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004295// Operations for querying linkage of a cursor.
4296//===----------------------------------------------------------------------===//
4297
4298extern "C" {
4299CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004300 if (!clang_isDeclaration(cursor.kind))
4301 return CXLinkage_Invalid;
4302
Ted Kremenek16b42592010-03-03 06:36:57 +00004303 Decl *D = cxcursor::getCursorDecl(cursor);
4304 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4305 switch (ND->getLinkage()) {
4306 case NoLinkage: return CXLinkage_NoLinkage;
4307 case InternalLinkage: return CXLinkage_Internal;
4308 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4309 case ExternalLinkage: return CXLinkage_External;
4310 };
4311
4312 return CXLinkage_Invalid;
4313}
4314} // end: extern "C"
4315
4316//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004317// Operations for querying language of a cursor.
4318//===----------------------------------------------------------------------===//
4319
4320static CXLanguageKind getDeclLanguage(const Decl *D) {
4321 switch (D->getKind()) {
4322 default:
4323 break;
4324 case Decl::ImplicitParam:
4325 case Decl::ObjCAtDefsField:
4326 case Decl::ObjCCategory:
4327 case Decl::ObjCCategoryImpl:
4328 case Decl::ObjCClass:
4329 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004330 case Decl::ObjCForwardProtocol:
4331 case Decl::ObjCImplementation:
4332 case Decl::ObjCInterface:
4333 case Decl::ObjCIvar:
4334 case Decl::ObjCMethod:
4335 case Decl::ObjCProperty:
4336 case Decl::ObjCPropertyImpl:
4337 case Decl::ObjCProtocol:
4338 return CXLanguage_ObjC;
4339 case Decl::CXXConstructor:
4340 case Decl::CXXConversion:
4341 case Decl::CXXDestructor:
4342 case Decl::CXXMethod:
4343 case Decl::CXXRecord:
4344 case Decl::ClassTemplate:
4345 case Decl::ClassTemplatePartialSpecialization:
4346 case Decl::ClassTemplateSpecialization:
4347 case Decl::Friend:
4348 case Decl::FriendTemplate:
4349 case Decl::FunctionTemplate:
4350 case Decl::LinkageSpec:
4351 case Decl::Namespace:
4352 case Decl::NamespaceAlias:
4353 case Decl::NonTypeTemplateParm:
4354 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004355 case Decl::TemplateTemplateParm:
4356 case Decl::TemplateTypeParm:
4357 case Decl::UnresolvedUsingTypename:
4358 case Decl::UnresolvedUsingValue:
4359 case Decl::Using:
4360 case Decl::UsingDirective:
4361 case Decl::UsingShadow:
4362 return CXLanguage_CPlusPlus;
4363 }
4364
4365 return CXLanguage_C;
4366}
4367
4368extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004369
4370enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4371 if (clang_isDeclaration(cursor.kind))
4372 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4373 if (D->hasAttr<UnavailableAttr>() ||
4374 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4375 return CXAvailability_Available;
4376
4377 if (D->hasAttr<DeprecatedAttr>())
4378 return CXAvailability_Deprecated;
4379 }
4380
4381 return CXAvailability_Available;
4382}
4383
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004384CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4385 if (clang_isDeclaration(cursor.kind))
4386 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4387
4388 return CXLanguage_Invalid;
4389}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004390
4391CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4392 if (clang_isDeclaration(cursor.kind)) {
4393 if (Decl *D = getCursorDecl(cursor)) {
4394 DeclContext *DC = D->getDeclContext();
4395 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4396 }
4397 }
4398
4399 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4400 if (Decl *D = getCursorDecl(cursor))
4401 return MakeCXCursor(D, getCursorASTUnit(cursor));
4402 }
4403
4404 return clang_getNullCursor();
4405}
4406
4407CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4408 if (clang_isDeclaration(cursor.kind)) {
4409 if (Decl *D = getCursorDecl(cursor)) {
4410 DeclContext *DC = D->getLexicalDeclContext();
4411 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4412 }
4413 }
4414
4415 // FIXME: Note that we can't easily compute the lexical context of a
4416 // statement or expression, so we return nothing.
4417 return clang_getNullCursor();
4418}
4419
Douglas Gregor9f592342010-10-01 20:25:15 +00004420static void CollectOverriddenMethods(DeclContext *Ctx,
4421 ObjCMethodDecl *Method,
4422 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4423 if (!Ctx)
4424 return;
4425
4426 // If we have a class or category implementation, jump straight to the
4427 // interface.
4428 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4429 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4430
4431 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4432 if (!Container)
4433 return;
4434
4435 // Check whether we have a matching method at this level.
4436 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4437 Method->isInstanceMethod()))
4438 if (Method != Overridden) {
4439 // We found an override at this level; there is no need to look
4440 // into other protocols or categories.
4441 Methods.push_back(Overridden);
4442 return;
4443 }
4444
4445 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4446 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4447 PEnd = Protocol->protocol_end();
4448 P != PEnd; ++P)
4449 CollectOverriddenMethods(*P, Method, Methods);
4450 }
4451
4452 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4453 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4454 PEnd = Category->protocol_end();
4455 P != PEnd; ++P)
4456 CollectOverriddenMethods(*P, Method, Methods);
4457 }
4458
4459 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4460 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4461 PEnd = Interface->protocol_end();
4462 P != PEnd; ++P)
4463 CollectOverriddenMethods(*P, Method, Methods);
4464
4465 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4466 Category; Category = Category->getNextClassCategory())
4467 CollectOverriddenMethods(Category, Method, Methods);
4468
4469 // We only look into the superclass if we haven't found anything yet.
4470 if (Methods.empty())
4471 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4472 return CollectOverriddenMethods(Super, Method, Methods);
4473 }
4474}
4475
4476void clang_getOverriddenCursors(CXCursor cursor,
4477 CXCursor **overridden,
4478 unsigned *num_overridden) {
4479 if (overridden)
4480 *overridden = 0;
4481 if (num_overridden)
4482 *num_overridden = 0;
4483 if (!overridden || !num_overridden)
4484 return;
4485
4486 if (!clang_isDeclaration(cursor.kind))
4487 return;
4488
4489 Decl *D = getCursorDecl(cursor);
4490 if (!D)
4491 return;
4492
4493 // Handle C++ member functions.
4494 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4495 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4496 *num_overridden = CXXMethod->size_overridden_methods();
4497 if (!*num_overridden)
4498 return;
4499
4500 *overridden = new CXCursor [*num_overridden];
4501 unsigned I = 0;
4502 for (CXXMethodDecl::method_iterator
4503 M = CXXMethod->begin_overridden_methods(),
4504 MEnd = CXXMethod->end_overridden_methods();
4505 M != MEnd; (void)++M, ++I)
4506 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4507 return;
4508 }
4509
4510 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4511 if (!Method)
4512 return;
4513
4514 // Handle Objective-C methods.
4515 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4516 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4517
4518 if (Methods.empty())
4519 return;
4520
4521 *num_overridden = Methods.size();
4522 *overridden = new CXCursor [Methods.size()];
4523 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4524 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4525}
4526
4527void clang_disposeOverriddenCursors(CXCursor *overridden) {
4528 delete [] overridden;
4529}
4530
Douglas Gregorecdcb882010-10-20 22:00:55 +00004531CXFile clang_getIncludedFile(CXCursor cursor) {
4532 if (cursor.kind != CXCursor_InclusionDirective)
4533 return 0;
4534
4535 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4536 return (void *)ID->getFile();
4537}
4538
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004539} // end: extern "C"
4540
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004541
4542//===----------------------------------------------------------------------===//
4543// C++ AST instrospection.
4544//===----------------------------------------------------------------------===//
4545
4546extern "C" {
4547unsigned clang_CXXMethod_isStatic(CXCursor C) {
4548 if (!clang_isDeclaration(C.kind))
4549 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004550
4551 CXXMethodDecl *Method = 0;
4552 Decl *D = cxcursor::getCursorDecl(C);
4553 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4554 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4555 else
4556 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4557 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004558}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004559
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004560} // end: extern "C"
4561
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004562//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004563// Attribute introspection.
4564//===----------------------------------------------------------------------===//
4565
4566extern "C" {
4567CXType clang_getIBOutletCollectionType(CXCursor C) {
4568 if (C.kind != CXCursor_IBOutletCollectionAttr)
4569 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4570
4571 IBOutletCollectionAttr *A =
4572 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4573
4574 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4575}
4576} // end: extern "C"
4577
4578//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004579// Misc. utility functions.
4580//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004581
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004582/// Default to using an 8 MB stack size on "safety" threads.
4583static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004584
4585namespace clang {
4586
4587bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004588 void (*Fn)(void*), void *UserData,
4589 unsigned Size) {
4590 if (!Size)
4591 Size = GetSafetyThreadStackSize();
4592 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004593 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4594 return CRC.RunSafely(Fn, UserData);
4595}
4596
4597unsigned GetSafetyThreadStackSize() {
4598 return SafetyStackThreadSize;
4599}
4600
4601void SetSafetyThreadStackSize(unsigned Value) {
4602 SafetyStackThreadSize = Value;
4603}
4604
4605}
4606
Ted Kremenek04bb7162010-01-22 22:44:15 +00004607extern "C" {
4608
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004609CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004610 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004611}
4612
4613} // end: extern "C"