blob: 6d5df9f7c10eccc9bfcc7e10ee5de1fe1d0e7eb5 [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
Ted Kremeneka60ed472010-11-16 08:15:36 +000052static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
53 if (!TU)
54 return 0;
55 CXTranslationUnit D = new CXTranslationUnitImpl();
56 D->TUData = TU;
57 D->StringPool = createCXStringPool();
58 return D;
59}
60
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061/// \brief The result of comparing two source ranges.
62enum RangeComparisonResult {
63 /// \brief Either the ranges overlap or one of the ranges is invalid.
64 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066 /// \brief The first range ends before the second range starts.
67 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000068
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 /// \brief The first range starts after the second range ends.
70 RangeAfter
71};
72
Ted Kremenekf0e23e82010-02-17 00:41:40 +000073/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075static RangeComparisonResult RangeCompare(SourceManager &SM,
76 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 SourceRange R2) {
78 assert(R1.isValid() && "First range is invalid?");
79 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000080 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000081 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000082 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000083 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000084 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000085 return RangeAfter;
86 return RangeOverlap;
87}
88
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089/// \brief Determine if a source location falls within, before, or after a
90/// a given source range.
91static RangeComparisonResult LocationCompare(SourceManager &SM,
92 SourceLocation L, SourceRange R) {
93 assert(R.isValid() && "First range is invalid?");
94 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000095 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000096 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
98 return RangeBefore;
99 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
100 return RangeAfter;
101 return RangeOverlap;
102}
103
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000104/// \brief Translate a Clang source range into a CIndex source range.
105///
106/// Clang internally represents ranges where the end location points to the
107/// start of the token at the end. However, for external clients it is more
108/// useful to have a CXSourceRange be a proper half-open interval. This routine
109/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000110CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000112 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000113 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000114 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000115 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000116 if (EndLoc.isValid() && EndLoc.isMacroID())
117 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000118 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000119 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000120 EndLoc = EndLoc.getFileLocWithOffset(Length);
121 }
122
123 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
124 R.getBegin().getRawEncoding(),
125 EndLoc.getRawEncoding() };
126 return Result;
127}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000128
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000130// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000131//===----------------------------------------------------------------------===//
132
Steve Naroff89922f82009-08-31 00:59:03 +0000133namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000134
135class VisitorJob {
136public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000137 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000138 TypeLocVisitKind, OverloadExprPartsKind,
139 DeclRefExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000140protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000141 void *dataA;
142 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000143 CXCursor parent;
144 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000145 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
146 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147public:
148 Kind getKind() const { return K; }
149 const CXCursor &getParent() const { return parent; }
150 static bool classof(VisitorJob *VJ) { return true; }
151};
152
153typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
154
Douglas Gregorb1373d02010-01-20 20:59:29 +0000155// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000156class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000157 public TypeLocVisitor<CursorVisitor, bool>,
158 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000159{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000160 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000161 CXTranslationUnit TU;
162 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000163
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000164 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000166
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 /// \brief The declaration that serves at the parent of any statement or
168 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000169 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000175 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000177 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
178 // to the visitor. Declarations with a PCH level greater than this value will
179 // be suppressed.
180 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181
182 /// \brief When valid, a source range to which the cursor should restrict
183 /// its search.
184 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000186 // FIXME: Eventually remove. This part of a hack to support proper
187 // iteration over all Decls contained lexically within an ObjC container.
188 DeclContext::decl_iterator *DI_current;
189 DeclContext::decl_iterator DE_current;
190
Ted Kremenekd1ded662010-11-15 23:31:32 +0000191 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
192 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
193 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
194
Douglas Gregorb1373d02010-01-20 20:59:29 +0000195 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000196 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000197 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000198
199 /// \brief Determine whether this particular source range comes before, comes
200 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000201 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000202 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000203 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
204
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000205 class SetParentRAII {
206 CXCursor &Parent;
207 Decl *&StmtParent;
208 CXCursor OldParent;
209
210 public:
211 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
212 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
213 {
214 Parent = NewParent;
215 if (clang_isDeclaration(Parent.kind))
216 StmtParent = getCursorDecl(Parent);
217 }
218
219 ~SetParentRAII() {
220 Parent = OldParent;
221 if (clang_isDeclaration(Parent.kind))
222 StmtParent = getCursorDecl(Parent);
223 }
224 };
225
Steve Naroff89922f82009-08-31 00:59:03 +0000226public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000227 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
228 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000229 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000230 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000231 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
232 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000233 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
234 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000235 {
236 Parent.kind = CXCursor_NoDeclFound;
237 Parent.data[0] = 0;
238 Parent.data[1] = 0;
239 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000240 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242
Ted Kremenekd1ded662010-11-15 23:31:32 +0000243 ~CursorVisitor() {
244 // Free the pre-allocated worklists for data-recursion.
245 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
246 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
247 delete *I;
248 }
249 }
250
Ted Kremeneka60ed472010-11-16 08:15:36 +0000251 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
252 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000253
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000254 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000255
256 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
257 getPreprocessedEntities();
258
Douglas Gregorb1373d02010-01-20 20:59:29 +0000259 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000260
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000261 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000262 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000263 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000264 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000265 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000266 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000267 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
268 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000270 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000271 bool VisitClassTemplatePartialSpecializationDecl(
272 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000273 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000274 bool VisitEnumConstantDecl(EnumConstantDecl *D);
275 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
276 bool VisitFunctionDecl(FunctionDecl *ND);
277 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000278 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000279 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000280 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000281 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000282 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000283 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
284 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
285 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
286 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000287 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
289 bool VisitObjCImplDecl(ObjCImplDecl *D);
290 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
291 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000292 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
293 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
294 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000295 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000296 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000297 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000298 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000299 bool VisitUsingDecl(UsingDecl *D);
300 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
301 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000302
Douglas Gregor01829d32010-08-31 14:41:23 +0000303 // Name visitor
304 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000305 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000306
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000307 // Template visitors
308 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000309 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000310 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
311
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000312 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000313 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000315 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000316 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
317 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000318 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000319 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000320 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
322 bool VisitPointerTypeLoc(PointerTypeLoc TL);
323 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
324 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
325 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
326 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000327 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000329 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000330 // FIXME: Implement visitors here when the unimplemented TypeLocs get
331 // implemented
332 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
333 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000334
Douglas Gregora59e3902010-01-21 23:27:09 +0000335 // Statement visitors
336 bool VisitStmt(Stmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000337
Douglas Gregor336fd812010-01-23 00:40:08 +0000338 // Expression visitors
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000339 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000340 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000341 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000342 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000343 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000344 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000345 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000346 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000347 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000348 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000349 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000350
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000351 // Data-recursive visitor functions.
352 bool IsInRegionOfInterest(CXCursor C);
353 bool RunVisitorWorkList(VisitorWorkList &WL);
354 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Benjamin Kramere645c722010-11-16 15:45:46 +0000355 LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000356};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000357
Ted Kremenekab188932010-01-05 19:32:54 +0000358} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000359
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000360static SourceRange getRawCursorExtent(CXCursor C);
361
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000363 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000364}
365
Douglas Gregorb1373d02010-01-20 20:59:29 +0000366/// \brief Visit the given cursor and, if requested by the visitor,
367/// its children.
368///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000369/// \param Cursor the cursor to visit.
370///
371/// \param CheckRegionOfInterest if true, then the caller already checked that
372/// this cursor is within the region of interest.
373///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374/// \returns true if the visitation should be aborted, false if it
375/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000376bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 if (clang_isInvalid(Cursor.kind))
378 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000379
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380 if (clang_isDeclaration(Cursor.kind)) {
381 Decl *D = getCursorDecl(Cursor);
382 assert(D && "Invalid declaration cursor");
383 if (D->getPCHLevel() > MaxPCHLevel)
384 return false;
385
386 if (D->isImplicit())
387 return false;
388 }
389
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390 // If we have a range of interest, and this cursor doesn't intersect with it,
391 // we're done.
392 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000393 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000394 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000395 return false;
396 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000397
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398 switch (Visitor(Cursor, Parent, ClientData)) {
399 case CXChildVisit_Break:
400 return true;
401
402 case CXChildVisit_Continue:
403 return false;
404
405 case CXChildVisit_Recurse:
406 return VisitChildren(Cursor);
407 }
408
Douglas Gregorfd643772010-01-25 16:45:46 +0000409 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410}
411
Douglas Gregor788f5a12010-03-20 00:41:21 +0000412std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
413CursorVisitor::getPreprocessedEntities() {
414 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000415 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000416
417 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000418 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000419
420 // There is no region of interest; we have to walk everything.
421 if (RegionOfInterest.isInvalid())
422 return std::make_pair(PPRec.begin(OnlyLocalDecls),
423 PPRec.end(OnlyLocalDecls));
424
425 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000426 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000427 std::pair<FileID, unsigned> Begin
428 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
429 std::pair<FileID, unsigned> End
430 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
431
432 // The region of interest spans files; we have to walk everything.
433 if (Begin.first != End.first)
434 return std::make_pair(PPRec.begin(OnlyLocalDecls),
435 PPRec.end(OnlyLocalDecls));
436
437 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000438 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000439 if (ByFileMap.empty()) {
440 // Build the mapping from files to sets of preprocessed entities.
441 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
442 EEnd = PPRec.end(OnlyLocalDecls);
443 E != EEnd; ++E) {
444 std::pair<FileID, unsigned> P
445 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
446 ByFileMap[P.first].push_back(*E);
447 }
448 }
449
450 return std::make_pair(ByFileMap[Begin.first].begin(),
451 ByFileMap[Begin.first].end());
452}
453
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000455///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456/// \returns true if the visitation should be aborted, false if it
457/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000458bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000459 if (clang_isReference(Cursor.kind)) {
460 // By definition, references have no children.
461 return false;
462 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000463
464 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000465 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000466 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000467
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 if (clang_isDeclaration(Cursor.kind)) {
469 Decl *D = getCursorDecl(Cursor);
470 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000471 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000473
Douglas Gregora59e3902010-01-21 23:27:09 +0000474 if (clang_isStatement(Cursor.kind))
475 return Visit(getCursorStmt(Cursor));
476 if (clang_isExpression(Cursor.kind))
477 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478
Douglas Gregorb1373d02010-01-20 20:59:29 +0000479 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000480 CXTranslationUnit tu = getCursorTU(Cursor);
481 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000482 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
483 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000484 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
485 TLEnd = CXXUnit->top_level_end();
486 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000487 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000488 return true;
489 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000490 } else if (VisitDeclContext(
491 CXXUnit->getASTContext().getTranslationUnitDecl()))
492 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000493
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000495 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000496 // FIXME: Once we have the ability to deserialize a preprocessing record,
497 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000498 PreprocessingRecord::iterator E, EEnd;
499 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000500 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000501 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000503
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 continue;
505 }
506
507 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000508 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000509 return true;
510
511 continue;
512 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000513
514 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000515 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000516 return true;
517
518 continue;
519 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000520 }
521 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000522 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000524
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 return false;
527}
528
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000529bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000530 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
531 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000532
Ted Kremenek664cffd2010-07-22 11:30:19 +0000533 if (Stmt *Body = B->getBody())
534 return Visit(MakeCXCursor(Body, StmtParent, TU));
535
536 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000537}
538
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000539llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
540 if (RegionOfInterest.isValid()) {
541 SourceRange Range = getRawCursorExtent(Cursor);
542 if (Range.isInvalid())
543 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000544
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000545 switch (CompareRegionOfInterest(Range)) {
546 case RangeBefore:
547 // This declaration comes before the region of interest; skip it.
548 return llvm::Optional<bool>();
549
550 case RangeAfter:
551 // This declaration comes after the region of interest; we're done.
552 return false;
553
554 case RangeOverlap:
555 // This declaration overlaps the region of interest; visit it.
556 break;
557 }
558 }
559 return true;
560}
561
562bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
563 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
564
565 // FIXME: Eventually remove. This part of a hack to support proper
566 // iteration over all Decls contained lexically within an ObjC container.
567 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
568 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
569
570 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000571 Decl *D = *I;
572 if (D->getLexicalDeclContext() != DC)
573 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000574 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000575 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
576 if (!V.hasValue())
577 continue;
578 if (!V.getValue())
579 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000580 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581 return true;
582 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000584}
585
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000586bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
587 llvm_unreachable("Translation units are visited directly by Visit()");
588 return false;
589}
590
591bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
592 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
593 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595 return false;
596}
597
598bool CursorVisitor::VisitTagDecl(TagDecl *D) {
599 return VisitDeclContext(D);
600}
601
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000602bool CursorVisitor::VisitClassTemplateSpecializationDecl(
603 ClassTemplateSpecializationDecl *D) {
604 bool ShouldVisitBody = false;
605 switch (D->getSpecializationKind()) {
606 case TSK_Undeclared:
607 case TSK_ImplicitInstantiation:
608 // Nothing to visit
609 return false;
610
611 case TSK_ExplicitInstantiationDeclaration:
612 case TSK_ExplicitInstantiationDefinition:
613 break;
614
615 case TSK_ExplicitSpecialization:
616 ShouldVisitBody = true;
617 break;
618 }
619
620 // Visit the template arguments used in the specialization.
621 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
622 TypeLoc TL = SpecType->getTypeLoc();
623 if (TemplateSpecializationTypeLoc *TSTLoc
624 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
625 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
626 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
627 return true;
628 }
629 }
630
631 if (ShouldVisitBody && VisitCXXRecordDecl(D))
632 return true;
633
634 return false;
635}
636
Douglas Gregor74dbe642010-08-31 19:31:58 +0000637bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
638 ClassTemplatePartialSpecializationDecl *D) {
639 // FIXME: Visit the "outer" template parameter lists on the TagDecl
640 // before visiting these template parameters.
641 if (VisitTemplateParameters(D->getTemplateParameters()))
642 return true;
643
644 // Visit the partial specialization arguments.
645 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
646 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
647 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
648 return true;
649
650 return VisitCXXRecordDecl(D);
651}
652
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000653bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000654 // Visit the default argument.
655 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
656 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
657 if (Visit(DefArg->getTypeLoc()))
658 return true;
659
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000660 return false;
661}
662
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000663bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
664 if (Expr *Init = D->getInitExpr())
665 return Visit(MakeCXCursor(Init, StmtParent, TU));
666 return false;
667}
668
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000669bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
670 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
671 if (Visit(TSInfo->getTypeLoc()))
672 return true;
673
674 return false;
675}
676
Douglas Gregora67e03f2010-09-09 21:42:20 +0000677/// \brief Compare two base or member initializers based on their source order.
678static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
679 CXXBaseOrMemberInitializer const * const *X
680 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
681 CXXBaseOrMemberInitializer const * const *Y
682 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
683
684 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
685 return -1;
686 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
687 return 1;
688 else
689 return 0;
690}
691
Douglas Gregorb1373d02010-01-20 20:59:29 +0000692bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000693 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
694 // Visit the function declaration's syntactic components in the order
695 // written. This requires a bit of work.
696 TypeLoc TL = TSInfo->getTypeLoc();
697 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
698
699 // If we have a function declared directly (without the use of a typedef),
700 // visit just the return type. Otherwise, just visit the function's type
701 // now.
702 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
703 (!FTL && Visit(TL)))
704 return true;
705
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000706 // Visit the nested-name-specifier, if present.
707 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
708 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
709 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000710
711 // Visit the declaration name.
712 if (VisitDeclarationNameInfo(ND->getNameInfo()))
713 return true;
714
715 // FIXME: Visit explicitly-specified template arguments!
716
717 // Visit the function parameters, if we have a function type.
718 if (FTL && VisitFunctionTypeLoc(*FTL, true))
719 return true;
720
721 // FIXME: Attributes?
722 }
723
Douglas Gregora67e03f2010-09-09 21:42:20 +0000724 if (ND->isThisDeclarationADefinition()) {
725 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
726 // Find the initializers that were written in the source.
727 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
728 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
729 IEnd = Constructor->init_end();
730 I != IEnd; ++I) {
731 if (!(*I)->isWritten())
732 continue;
733
734 WrittenInits.push_back(*I);
735 }
736
737 // Sort the initializers in source order
738 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
739 &CompareCXXBaseOrMemberInitializers);
740
741 // Visit the initializers in source order
742 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
743 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
744 if (Init->isMemberInitializer()) {
745 if (Visit(MakeCursorMemberRef(Init->getMember(),
746 Init->getMemberLocation(), TU)))
747 return true;
748 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
749 if (Visit(BaseInfo->getTypeLoc()))
750 return true;
751 }
752
753 // Visit the initializer value.
754 if (Expr *Initializer = Init->getInit())
755 if (Visit(MakeCXCursor(Initializer, ND, TU)))
756 return true;
757 }
758 }
759
760 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
761 return true;
762 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000763
Douglas Gregorb1373d02010-01-20 20:59:29 +0000764 return false;
765}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000766
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000767bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
768 if (VisitDeclaratorDecl(D))
769 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000770
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000771 if (Expr *BitWidth = D->getBitWidth())
772 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000773
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000774 return false;
775}
776
777bool CursorVisitor::VisitVarDecl(VarDecl *D) {
778 if (VisitDeclaratorDecl(D))
779 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781 if (Expr *Init = D->getInit())
782 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 return false;
785}
786
Douglas Gregor84b51d72010-09-01 20:16:53 +0000787bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
788 if (VisitDeclaratorDecl(D))
789 return true;
790
791 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
792 if (Expr *DefArg = D->getDefaultArgument())
793 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
794
795 return false;
796}
797
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000798bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
799 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
800 // before visiting these template parameters.
801 if (VisitTemplateParameters(D->getTemplateParameters()))
802 return true;
803
804 return VisitFunctionDecl(D->getTemplatedDecl());
805}
806
Douglas Gregor39d6f072010-08-31 19:02:00 +0000807bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
808 // FIXME: Visit the "outer" template parameter lists on the TagDecl
809 // before visiting these template parameters.
810 if (VisitTemplateParameters(D->getTemplateParameters()))
811 return true;
812
813 return VisitCXXRecordDecl(D->getTemplatedDecl());
814}
815
Douglas Gregor84b51d72010-09-01 20:16:53 +0000816bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
817 if (VisitTemplateParameters(D->getTemplateParameters()))
818 return true;
819
820 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
821 VisitTemplateArgumentLoc(D->getDefaultArgument()))
822 return true;
823
824 return false;
825}
826
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000827bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000828 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
829 if (Visit(TSInfo->getTypeLoc()))
830 return true;
831
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000833 PEnd = ND->param_end();
834 P != PEnd; ++P) {
835 if (Visit(MakeCXCursor(*P, TU)))
836 return true;
837 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839 if (ND->isThisDeclarationADefinition() &&
840 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
841 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 return false;
844}
845
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000846namespace {
847 struct ContainerDeclsSort {
848 SourceManager &SM;
849 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
850 bool operator()(Decl *A, Decl *B) {
851 SourceLocation L_A = A->getLocStart();
852 SourceLocation L_B = B->getLocStart();
853 assert(L_A.isValid() && L_B.isValid());
854 return SM.isBeforeInTranslationUnit(L_A, L_B);
855 }
856 };
857}
858
Douglas Gregora59e3902010-01-21 23:27:09 +0000859bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000860 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
861 // an @implementation can lexically contain Decls that are not properly
862 // nested in the AST. When we identify such cases, we need to retrofit
863 // this nesting here.
864 if (!DI_current)
865 return VisitDeclContext(D);
866
867 // Scan the Decls that immediately come after the container
868 // in the current DeclContext. If any fall within the
869 // container's lexical region, stash them into a vector
870 // for later processing.
871 llvm::SmallVector<Decl *, 24> DeclsInContainer;
872 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000873 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000874 if (EndLoc.isValid()) {
875 DeclContext::decl_iterator next = *DI_current;
876 while (++next != DE_current) {
877 Decl *D_next = *next;
878 if (!D_next)
879 break;
880 SourceLocation L = D_next->getLocStart();
881 if (!L.isValid())
882 break;
883 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
884 *DI_current = next;
885 DeclsInContainer.push_back(D_next);
886 continue;
887 }
888 break;
889 }
890 }
891
892 // The common case.
893 if (DeclsInContainer.empty())
894 return VisitDeclContext(D);
895
896 // Get all the Decls in the DeclContext, and sort them with the
897 // additional ones we've collected. Then visit them.
898 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
899 I!=E; ++I) {
900 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000901 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
902 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000903 continue;
904 DeclsInContainer.push_back(subDecl);
905 }
906
907 // Now sort the Decls so that they appear in lexical order.
908 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
909 ContainerDeclsSort(SM));
910
911 // Now visit the decls.
912 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
913 E = DeclsInContainer.end(); I != E; ++I) {
914 CXCursor Cursor = MakeCXCursor(*I, TU);
915 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
916 if (!V.hasValue())
917 continue;
918 if (!V.getValue())
919 return false;
920 if (Visit(Cursor, true))
921 return true;
922 }
923 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000924}
925
Douglas Gregorb1373d02010-01-20 20:59:29 +0000926bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000927 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
928 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000929 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000930
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000931 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
932 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
933 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000934 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000935 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000936
Douglas Gregora59e3902010-01-21 23:27:09 +0000937 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000938}
939
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000940bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
941 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
942 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
943 E = PID->protocol_end(); I != E; ++I, ++PL)
944 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
945 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000946
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000947 return VisitObjCContainerDecl(PID);
948}
949
Ted Kremenek23173d72010-05-18 21:09:07 +0000950bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000951 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000952 return true;
953
Ted Kremenek23173d72010-05-18 21:09:07 +0000954 // FIXME: This implements a workaround with @property declarations also being
955 // installed in the DeclContext for the @interface. Eventually this code
956 // should be removed.
957 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
958 if (!CDecl || !CDecl->IsClassExtension())
959 return false;
960
961 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
962 if (!ID)
963 return false;
964
965 IdentifierInfo *PropertyId = PD->getIdentifier();
966 ObjCPropertyDecl *prevDecl =
967 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
968
969 if (!prevDecl)
970 return false;
971
972 // Visit synthesized methods since they will be skipped when visiting
973 // the @interface.
974 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000975 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000976 if (Visit(MakeCXCursor(MD, TU)))
977 return true;
978
979 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000980 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000981 if (Visit(MakeCXCursor(MD, TU)))
982 return true;
983
984 return false;
985}
986
Douglas Gregorb1373d02010-01-20 20:59:29 +0000987bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000988 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000989 if (D->getSuperClass() &&
990 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000991 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000992 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000993 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000995 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
996 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
997 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000998 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000999 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001000
Douglas Gregora59e3902010-01-21 23:27:09 +00001001 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001002}
1003
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001004bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1005 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001006}
1007
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001008bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001009 // 'ID' could be null when dealing with invalid code.
1010 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1011 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1012 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001014 return VisitObjCImplDecl(D);
1015}
1016
1017bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1018#if 0
1019 // Issue callbacks for super class.
1020 // FIXME: No source location information!
1021 if (D->getSuperClass() &&
1022 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001023 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001024 TU)))
1025 return true;
1026#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028 return VisitObjCImplDecl(D);
1029}
1030
1031bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1032 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1033 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1034 E = D->protocol_end();
1035 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001036 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001037 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001038
1039 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001040}
1041
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1043 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1044 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1045 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001046
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001047 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001048}
1049
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001050bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1051 return VisitDeclContext(D);
1052}
1053
Douglas Gregor69319002010-08-31 23:48:11 +00001054bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001055 // Visit nested-name-specifier.
1056 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1057 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1058 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001059
1060 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1061 D->getTargetNameLoc(), TU));
1062}
1063
Douglas Gregor7e242562010-09-01 19:52:22 +00001064bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001065 // Visit nested-name-specifier.
1066 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1067 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1068 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001069
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001070 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1071 return true;
1072
Douglas Gregor7e242562010-09-01 19:52:22 +00001073 return VisitDeclarationNameInfo(D->getNameInfo());
1074}
1075
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001076bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
1078 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1079 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1080 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001081
1082 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1083 D->getIdentLocation(), TU));
1084}
1085
Douglas Gregor7e242562010-09-01 19:52:22 +00001086bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 // Visit nested-name-specifier.
1088 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1089 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1090 return true;
1091
Douglas Gregor7e242562010-09-01 19:52:22 +00001092 return VisitDeclarationNameInfo(D->getNameInfo());
1093}
1094
1095bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1096 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001097 // Visit nested-name-specifier.
1098 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1099 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1100 return true;
1101
Douglas Gregor7e242562010-09-01 19:52:22 +00001102 return false;
1103}
1104
Douglas Gregor01829d32010-08-31 14:41:23 +00001105bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1106 switch (Name.getName().getNameKind()) {
1107 case clang::DeclarationName::Identifier:
1108 case clang::DeclarationName::CXXLiteralOperatorName:
1109 case clang::DeclarationName::CXXOperatorName:
1110 case clang::DeclarationName::CXXUsingDirective:
1111 return false;
1112
1113 case clang::DeclarationName::CXXConstructorName:
1114 case clang::DeclarationName::CXXDestructorName:
1115 case clang::DeclarationName::CXXConversionFunctionName:
1116 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1117 return Visit(TSInfo->getTypeLoc());
1118 return false;
1119
1120 case clang::DeclarationName::ObjCZeroArgSelector:
1121 case clang::DeclarationName::ObjCOneArgSelector:
1122 case clang::DeclarationName::ObjCMultiArgSelector:
1123 // FIXME: Per-identifier location info?
1124 return false;
1125 }
1126
1127 return false;
1128}
1129
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001130bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1131 SourceRange Range) {
1132 // FIXME: This whole routine is a hack to work around the lack of proper
1133 // source information in nested-name-specifiers (PR5791). Since we do have
1134 // a beginning source location, we can visit the first component of the
1135 // nested-name-specifier, if it's a single-token component.
1136 if (!NNS)
1137 return false;
1138
1139 // Get the first component in the nested-name-specifier.
1140 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1141 NNS = Prefix;
1142
1143 switch (NNS->getKind()) {
1144 case NestedNameSpecifier::Namespace:
1145 // FIXME: The token at this source location might actually have been a
1146 // namespace alias, but we don't model that. Lame!
1147 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1148 TU));
1149
1150 case NestedNameSpecifier::TypeSpec: {
1151 // If the type has a form where we know that the beginning of the source
1152 // range matches up with a reference cursor. Visit the appropriate reference
1153 // cursor.
1154 Type *T = NNS->getAsType();
1155 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1156 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1157 if (const TagType *Tag = dyn_cast<TagType>(T))
1158 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1159 if (const TemplateSpecializationType *TST
1160 = dyn_cast<TemplateSpecializationType>(T))
1161 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1162 break;
1163 }
1164
1165 case NestedNameSpecifier::TypeSpecWithTemplate:
1166 case NestedNameSpecifier::Global:
1167 case NestedNameSpecifier::Identifier:
1168 break;
1169 }
1170
1171 return false;
1172}
1173
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001174bool CursorVisitor::VisitTemplateParameters(
1175 const TemplateParameterList *Params) {
1176 if (!Params)
1177 return false;
1178
1179 for (TemplateParameterList::const_iterator P = Params->begin(),
1180 PEnd = Params->end();
1181 P != PEnd; ++P) {
1182 if (Visit(MakeCXCursor(*P, TU)))
1183 return true;
1184 }
1185
1186 return false;
1187}
1188
Douglas Gregor0b36e612010-08-31 20:37:03 +00001189bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1190 switch (Name.getKind()) {
1191 case TemplateName::Template:
1192 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1193
1194 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001195 // Visit the overloaded template set.
1196 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1197 return true;
1198
Douglas Gregor0b36e612010-08-31 20:37:03 +00001199 return false;
1200
1201 case TemplateName::DependentTemplate:
1202 // FIXME: Visit nested-name-specifier.
1203 return false;
1204
1205 case TemplateName::QualifiedTemplate:
1206 // FIXME: Visit nested-name-specifier.
1207 return Visit(MakeCursorTemplateRef(
1208 Name.getAsQualifiedTemplateName()->getDecl(),
1209 Loc, TU));
1210 }
1211
1212 return false;
1213}
1214
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001215bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1216 switch (TAL.getArgument().getKind()) {
1217 case TemplateArgument::Null:
1218 case TemplateArgument::Integral:
1219 return false;
1220
1221 case TemplateArgument::Pack:
1222 // FIXME: Implement when variadic templates come along.
1223 return false;
1224
1225 case TemplateArgument::Type:
1226 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1227 return Visit(TSInfo->getTypeLoc());
1228 return false;
1229
1230 case TemplateArgument::Declaration:
1231 if (Expr *E = TAL.getSourceDeclExpression())
1232 return Visit(MakeCXCursor(E, StmtParent, TU));
1233 return false;
1234
1235 case TemplateArgument::Expression:
1236 if (Expr *E = TAL.getSourceExpression())
1237 return Visit(MakeCXCursor(E, StmtParent, TU));
1238 return false;
1239
1240 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001241 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1242 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001243 }
1244
1245 return false;
1246}
1247
Ted Kremeneka0536d82010-05-07 01:04:29 +00001248bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1249 return VisitDeclContext(D);
1250}
1251
Douglas Gregor01829d32010-08-31 14:41:23 +00001252bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1253 return Visit(TL.getUnqualifiedLoc());
1254}
1255
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001256bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001257 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001258
1259 // Some builtin types (such as Objective-C's "id", "sel", and
1260 // "Class") have associated declarations. Create cursors for those.
1261 QualType VisitType;
1262 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001263 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001264 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001265 case BuiltinType::Char_U:
1266 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267 case BuiltinType::Char16:
1268 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001269 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270 case BuiltinType::UInt:
1271 case BuiltinType::ULong:
1272 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001273 case BuiltinType::UInt128:
1274 case BuiltinType::Char_S:
1275 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277 case BuiltinType::Short:
1278 case BuiltinType::Int:
1279 case BuiltinType::Long:
1280 case BuiltinType::LongLong:
1281 case BuiltinType::Int128:
1282 case BuiltinType::Float:
1283 case BuiltinType::Double:
1284 case BuiltinType::LongDouble:
1285 case BuiltinType::NullPtr:
1286 case BuiltinType::Overload:
1287 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001288 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001289
1290 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001292
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001293 case BuiltinType::ObjCId:
1294 VisitType = Context.getObjCIdType();
1295 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001296
1297 case BuiltinType::ObjCClass:
1298 VisitType = Context.getObjCClassType();
1299 break;
1300
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001301 case BuiltinType::ObjCSel:
1302 VisitType = Context.getObjCSelType();
1303 break;
1304 }
1305
1306 if (!VisitType.isNull()) {
1307 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001308 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001309 TU));
1310 }
1311
1312 return false;
1313}
1314
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001315bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1316 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1317}
1318
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001319bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1320 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1321}
1322
1323bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1324 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1325}
1326
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001327bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001328 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001329 // no context information with which we can match up the depth/index in the
1330 // type to the appropriate
1331 return false;
1332}
1333
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1335 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1336 return true;
1337
John McCallc12c5bb2010-05-15 11:32:37 +00001338 return false;
1339}
1340
1341bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1342 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1343 return true;
1344
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001345 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1346 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1347 TU)))
1348 return true;
1349 }
1350
1351 return false;
1352}
1353
1354bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001355 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001356}
1357
1358bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1359 return Visit(TL.getPointeeLoc());
1360}
1361
1362bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1363 return Visit(TL.getPointeeLoc());
1364}
1365
1366bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1367 return Visit(TL.getPointeeLoc());
1368}
1369
1370bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001371 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001372}
1373
1374bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001375 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376}
1377
Douglas Gregor01829d32010-08-31 14:41:23 +00001378bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1379 bool SkipResultType) {
1380 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381 return true;
1382
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001383 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001384 if (Decl *D = TL.getArg(I))
1385 if (Visit(MakeCXCursor(D, TU)))
1386 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387
1388 return false;
1389}
1390
1391bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1392 if (Visit(TL.getElementLoc()))
1393 return true;
1394
1395 if (Expr *Size = TL.getSizeExpr())
1396 return Visit(MakeCXCursor(Size, StmtParent, TU));
1397
1398 return false;
1399}
1400
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001401bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1402 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001403 // Visit the template name.
1404 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1405 TL.getTemplateNameLoc()))
1406 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001407
1408 // Visit the template arguments.
1409 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1410 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1411 return true;
1412
1413 return false;
1414}
1415
Douglas Gregor2332c112010-01-21 20:48:56 +00001416bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1417 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1418}
1419
1420bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1421 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1422 return Visit(TSInfo->getTypeLoc());
1423
1424 return false;
1425}
1426
Douglas Gregora59e3902010-01-21 23:27:09 +00001427bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001428 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001429}
1430
Ted Kremenek3064ef92010-08-27 21:34:58 +00001431bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1432 if (D->isDefinition()) {
1433 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1434 E = D->bases_end(); I != E; ++I) {
1435 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1436 return true;
1437 }
1438 }
1439
1440 return VisitTagDecl(D);
1441}
1442
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001443bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001444 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001445 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1446 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001447
1448 // Visit the components of the offsetof expression.
1449 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1450 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1451 const OffsetOfNode &Node = E->getComponent(I);
1452 switch (Node.getKind()) {
1453 case OffsetOfNode::Array:
1454 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1455 StmtParent, TU)))
1456 return true;
1457 break;
1458
1459 case OffsetOfNode::Field:
1460 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1461 TU)))
1462 return true;
1463 break;
1464
1465 case OffsetOfNode::Identifier:
1466 case OffsetOfNode::Base:
1467 continue;
1468 }
1469 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001470
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001471 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001472}
1473
Douglas Gregor336fd812010-01-23 00:40:08 +00001474bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1475 if (E->isArgumentType()) {
1476 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1477 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001478
Douglas Gregor336fd812010-01-23 00:40:08 +00001479 return false;
1480 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001481
Douglas Gregor336fd812010-01-23 00:40:08 +00001482 return VisitExpr(E);
1483}
1484
Douglas Gregor36897b02010-09-10 00:22:18 +00001485bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1486 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1487}
1488
Douglas Gregor648220e2010-08-10 15:02:34 +00001489bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1490 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1491 return true;
1492
1493 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1494}
1495
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001496bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1497 // Visit the designators.
1498 typedef DesignatedInitExpr::Designator Designator;
1499 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1500 DEnd = E->designators_end();
1501 D != DEnd; ++D) {
1502 if (D->isFieldDesignator()) {
1503 if (FieldDecl *Field = D->getField())
1504 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1505 return true;
1506
1507 continue;
1508 }
1509
1510 if (D->isArrayDesignator()) {
1511 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1512 return true;
1513
1514 continue;
1515 }
1516
1517 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1518 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1519 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1520 return true;
1521 }
1522
1523 // Visit the initializer value itself.
1524 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1525}
1526
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001527bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1528 if (E->isTypeOperand()) {
1529 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1530 return Visit(TSInfo->getTypeLoc());
1531
1532 return false;
1533 }
1534
1535 return VisitExpr(E);
1536}
1537
Douglas Gregorab6677e2010-09-08 00:15:04 +00001538bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1539 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1540 return Visit(TSInfo->getTypeLoc());
1541
1542 return false;
1543}
1544
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001545bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1546 // Visit base expression.
1547 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1548 return true;
1549
1550 // Visit the nested-name-specifier.
1551 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1552 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1553 return true;
1554
1555 // Visit the scope type that looks disturbingly like the nested-name-specifier
1556 // but isn't.
1557 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1558 if (Visit(TSInfo->getTypeLoc()))
1559 return true;
1560
1561 // Visit the name of the type being destroyed.
1562 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1563 if (Visit(TSInfo->getTypeLoc()))
1564 return true;
1565
1566 return false;
1567}
1568
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001569bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1570 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1571}
1572
Douglas Gregorbfebed22010-09-03 17:24:10 +00001573bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1574 DependentScopeDeclRefExpr *E) {
1575 // Visit the nested-name-specifier.
1576 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1577 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1578 return true;
1579
1580 // Visit the declaration name.
1581 if (VisitDeclarationNameInfo(E->getNameInfo()))
1582 return true;
1583
1584 // Visit the explicitly-specified template arguments.
1585 if (const ExplicitTemplateArgumentList *ArgList
1586 = E->getOptionalExplicitTemplateArgs()) {
1587 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1588 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1589 Arg != ArgEnd; ++Arg) {
1590 if (VisitTemplateArgumentLoc(*Arg))
1591 return true;
1592 }
1593 }
1594
1595 return false;
1596}
1597
Douglas Gregor25d63622010-09-03 17:35:34 +00001598bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1599 CXXDependentScopeMemberExpr *E) {
1600 // Visit the base expression, if there is one.
1601 if (!E->isImplicitAccess() &&
1602 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1603 return true;
1604
1605 // Visit the nested-name-specifier.
1606 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1607 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1608 return true;
1609
1610 // Visit the declaration name.
1611 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1612 return true;
1613
1614 // Visit the explicitly-specified template arguments.
1615 if (const ExplicitTemplateArgumentList *ArgList
1616 = E->getOptionalExplicitTemplateArgs()) {
1617 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1618 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1619 Arg != ArgEnd; ++Arg) {
1620 if (VisitTemplateArgumentLoc(*Arg))
1621 return true;
1622 }
1623 }
1624
1625 return false;
1626}
1627
Ted Kremenek09dfa372010-02-18 05:46:33 +00001628bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001629 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1630 i != e; ++i)
1631 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001632 return true;
1633
1634 return false;
1635}
1636
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001637//===----------------------------------------------------------------------===//
1638// Data-recursive visitor methods.
1639//===----------------------------------------------------------------------===//
1640
Ted Kremenek28a71942010-11-13 00:36:47 +00001641namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001642#define DEF_JOB(NAME, DATA, KIND)\
1643class NAME : public VisitorJob {\
1644public:\
1645 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1646 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1647 DATA *get() const { return static_cast<DATA*>(dataA); }\
1648};
1649
1650DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1651DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001652DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001653DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1654#undef DEF_JOB
1655
1656class DeclVisit : public VisitorJob {
1657public:
1658 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1659 VisitorJob(parent, VisitorJob::DeclVisitKind,
1660 d, isFirst ? (void*) 1 : (void*) 0) {}
1661 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001662 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001663 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001664 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001665 bool isFirst() const { return dataB ? true : false; }
1666};
1667
1668class TypeLocVisit : public VisitorJob {
1669public:
1670 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1671 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1672 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1673
1674 static bool classof(const VisitorJob *VJ) {
1675 return VJ->getKind() == TypeLocVisitKind;
1676 }
1677
Ted Kremenek82f3c502010-11-15 22:23:26 +00001678 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001679 QualType T = QualType::getFromOpaquePtr(dataA);
1680 return TypeLoc(T, dataB);
1681 }
1682};
1683
Ted Kremenek28a71942010-11-13 00:36:47 +00001684class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1685 VisitorWorkList &WL;
1686 CXCursor Parent;
1687public:
1688 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1689 : WL(wl), Parent(parent) {}
1690
Ted Kremenek73d15c42010-11-13 01:09:29 +00001691 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001692 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001693 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001694 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1695 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001697 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001698 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001699 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001700 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001701 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001702 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1703 void VisitForStmt(ForStmt *FS);
1704 void VisitIfStmt(IfStmt *If);
1705 void VisitInitListExpr(InitListExpr *IE);
1706 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001707 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001708 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1709 void VisitOverloadExpr(OverloadExpr *E);
1710 void VisitStmt(Stmt *S);
1711 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001712 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001713 void VisitWhileStmt(WhileStmt *W);
1714 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1715
1716private:
1717 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001718 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001719 void AddTypeLoc(TypeSourceInfo *TI);
1720 void EnqueueChildren(Stmt *S);
1721};
1722} // end anonyous namespace
1723
1724void EnqueueVisitor::AddStmt(Stmt *S) {
1725 if (S)
1726 WL.push_back(StmtVisit(S, Parent));
1727}
Ted Kremenek035dc412010-11-13 00:36:50 +00001728void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001729 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001730 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001731}
1732void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1733 if (TI)
1734 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1735 }
1736void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001737 unsigned size = WL.size();
1738 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1739 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001740 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001741 }
1742 if (size == WL.size())
1743 return;
1744 // Now reverse the entries we just added. This will match the DFS
1745 // ordering performed by the worklist.
1746 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1747 std::reverse(I, E);
1748}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001749void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1750 AddDecl(B->getBlockDecl());
1751}
Ted Kremenek28a71942010-11-13 00:36:47 +00001752void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1753 EnqueueChildren(E);
1754 AddTypeLoc(E->getTypeSourceInfo());
1755}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001756void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1757 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1758 E = S->body_rend(); I != E; ++I) {
1759 AddStmt(*I);
1760 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001761}
1762void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1763 // Enqueue the initializer or constructor arguments.
1764 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1765 AddStmt(E->getConstructorArg(I-1));
1766 // Enqueue the array size, if any.
1767 AddStmt(E->getArraySize());
1768 // Enqueue the allocated type.
1769 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1770 // Enqueue the placement arguments.
1771 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1772 AddStmt(E->getPlacementArg(I-1));
1773}
Ted Kremenek28a71942010-11-13 00:36:47 +00001774void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001775 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1776 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001777 AddStmt(CE->getCallee());
1778 AddStmt(CE->getArg(0));
1779}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001780void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1781 EnqueueChildren(E);
1782 AddTypeLoc(E->getTypeSourceInfo());
1783}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001784void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1785 EnqueueChildren(E);
1786 if (E->isTypeOperand())
1787 AddTypeLoc(E->getTypeOperandSourceInfo());
1788}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001789
1790void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1791 *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}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001858void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1859 AddTypeLoc(E->getArgTInfo2());
1860 AddTypeLoc(E->getArgTInfo1());
1861}
1862
Ted Kremenek28a71942010-11-13 00:36:47 +00001863void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1864 AddStmt(W->getBody());
1865 AddStmt(W->getCond());
1866 AddDecl(W->getConditionVariable());
1867}
1868void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1869 VisitOverloadExpr(U);
1870 if (!U->isImplicitAccess())
1871 AddStmt(U->getBase());
1872}
Ted Kremenek60458782010-11-12 21:34:16 +00001873
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001874void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001875 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001876}
1877
1878bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1879 if (RegionOfInterest.isValid()) {
1880 SourceRange Range = getRawCursorExtent(C);
1881 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1882 return false;
1883 }
1884 return true;
1885}
1886
1887bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1888 while (!WL.empty()) {
1889 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001890 VisitorJob LI = WL.back();
1891 WL.pop_back();
1892
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001893 // Set the Parent field, then back to its old value once we're done.
1894 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1895
1896 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001897 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001898 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001899 if (!D)
1900 continue;
1901
1902 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001903 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001904 return true;
1905
1906 continue;
1907 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001908 case VisitorJob::TypeLocVisitKind: {
1909 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001910 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001911 return true;
1912 continue;
1913 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001914 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001915 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001916 if (!S)
1917 continue;
1918
Ted Kremenekf1107452010-11-12 18:26:56 +00001919 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001920 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1921
1922 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001923 case Stmt::GotoStmtClass: {
1924 GotoStmt *GS = cast<GotoStmt>(S);
1925 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1926 GS->getLabelLoc(), TU))) {
1927 return true;
1928 }
1929 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001930 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001931 // Cases not yet handled by the data-recursion
1932 // algorithm.
1933 case Stmt::OffsetOfExprClass:
1934 case Stmt::SizeOfAlignOfExprClass:
1935 case Stmt::AddrLabelExprClass:
1936 case Stmt::TypesCompatibleExprClass:
1937 case Stmt::VAArgExprClass:
1938 case Stmt::DesignatedInitExprClass:
1939 case Stmt::CXXTypeidExprClass:
1940 case Stmt::CXXUuidofExprClass:
1941 case Stmt::CXXScalarValueInitExprClass:
1942 case Stmt::CXXPseudoDestructorExprClass:
1943 case Stmt::UnaryTypeTraitExprClass:
1944 case Stmt::DependentScopeDeclRefExprClass:
1945 case Stmt::CXXUnresolvedConstructExprClass:
1946 case Stmt::CXXDependentScopeMemberExprClass:
1947 if (Visit(Cursor))
1948 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001949 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001950 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001951 if (!IsInRegionOfInterest(Cursor))
1952 continue;
1953 switch (Visitor(Cursor, Parent, ClientData)) {
1954 case CXChildVisit_Break:
1955 return true;
1956 case CXChildVisit_Continue:
1957 break;
1958 case CXChildVisit_Recurse:
1959 EnqueueWorkList(WL, S);
1960 break;
1961 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001962 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001963 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001964 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001965 }
1966 case VisitorJob::MemberExprPartsKind: {
1967 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001968 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001969
1970 // Visit the nested-name-specifier
1971 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1972 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1973 return true;
1974
1975 // Visit the declaration name.
1976 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1977 return true;
1978
1979 // Visit the explicitly-specified template arguments, if any.
1980 if (M->hasExplicitTemplateArgs()) {
1981 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1982 *ArgEnd = Arg + M->getNumTemplateArgs();
1983 Arg != ArgEnd; ++Arg) {
1984 if (VisitTemplateArgumentLoc(*Arg))
1985 return true;
1986 }
1987 }
1988 continue;
1989 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001990 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001991 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001992 // Visit nested-name-specifier, if present.
1993 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
1994 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
1995 return true;
1996 // Visit declaration name.
1997 if (VisitDeclarationNameInfo(DR->getNameInfo()))
1998 return true;
1999 // Visit explicitly-specified template arguments.
2000 if (DR->hasExplicitTemplateArgs()) {
2001 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2002 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2003 *ArgEnd = Arg + Args.NumTemplateArgs;
2004 Arg != ArgEnd; ++Arg)
2005 if (VisitTemplateArgumentLoc(*Arg))
2006 return true;
2007 }
2008 continue;
2009 }
Ted Kremenek60458782010-11-12 21:34:16 +00002010 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002011 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002012 // Visit the nested-name-specifier.
2013 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2014 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2015 return true;
2016 // Visit the declaration name.
2017 if (VisitDeclarationNameInfo(O->getNameInfo()))
2018 return true;
2019 // Visit the overloaded declaration reference.
2020 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2021 return true;
2022 // Visit the explicitly-specified template arguments.
2023 if (const ExplicitTemplateArgumentList *ArgList
2024 = O->getOptionalExplicitTemplateArgs()) {
2025 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2026 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2027 Arg != ArgEnd; ++Arg) {
2028 if (VisitTemplateArgumentLoc(*Arg))
2029 return true;
2030 }
2031 }
2032 continue;
2033 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002034 }
2035 }
2036 return false;
2037}
2038
2039bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002040 VisitorWorkList *WL = 0;
2041 if (!WorkListFreeList.empty()) {
2042 WL = WorkListFreeList.back();
2043 WL->clear();
2044 WorkListFreeList.pop_back();
2045 }
2046 else {
2047 WL = new VisitorWorkList();
2048 WorkListCache.push_back(WL);
2049 }
2050 EnqueueWorkList(*WL, S);
2051 bool result = RunVisitorWorkList(*WL);
2052 WorkListFreeList.push_back(WL);
2053 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002054}
2055
2056//===----------------------------------------------------------------------===//
2057// Misc. API hooks.
2058//===----------------------------------------------------------------------===//
2059
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002060static llvm::sys::Mutex EnableMultithreadingMutex;
2061static bool EnabledMultithreading;
2062
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002063extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002064CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2065 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002066 // Disable pretty stack trace functionality, which will otherwise be a very
2067 // poor citizen of the world and set up all sorts of signal handlers.
2068 llvm::DisablePrettyStackTrace = true;
2069
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002070 // We use crash recovery to make some of our APIs more reliable, implicitly
2071 // enable it.
2072 llvm::CrashRecoveryContext::Enable();
2073
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002074 // Enable support for multithreading in LLVM.
2075 {
2076 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2077 if (!EnabledMultithreading) {
2078 llvm::llvm_start_multithreaded();
2079 EnabledMultithreading = true;
2080 }
2081 }
2082
Douglas Gregora030b7c2010-01-22 20:35:53 +00002083 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002084 if (excludeDeclarationsFromPCH)
2085 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002086 if (displayDiagnostics)
2087 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002088 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002089}
2090
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002091void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002092 if (CIdx)
2093 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002094}
2095
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002096CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002097 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002098 if (!CIdx)
2099 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002100
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002101 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002102 FileSystemOptions FileSystemOpts;
2103 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002104
Douglas Gregor28019772010-04-05 23:52:57 +00002105 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002106 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002107 CXXIdx->getOnlyLocalDecls(),
2108 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002109 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002110}
2111
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002112unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002113 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002114 CXTranslationUnit_CacheCompletionResults |
2115 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002116}
2117
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002118CXTranslationUnit
2119clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2120 const char *source_filename,
2121 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002122 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002123 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002124 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002125 return clang_parseTranslationUnit(CIdx, source_filename,
2126 command_line_args, num_command_line_args,
2127 unsaved_files, num_unsaved_files,
2128 CXTranslationUnit_DetailedPreprocessingRecord);
2129}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002130
2131struct ParseTranslationUnitInfo {
2132 CXIndex CIdx;
2133 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002134 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002135 int num_command_line_args;
2136 struct CXUnsavedFile *unsaved_files;
2137 unsigned num_unsaved_files;
2138 unsigned options;
2139 CXTranslationUnit result;
2140};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002141static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002142 ParseTranslationUnitInfo *PTUI =
2143 static_cast<ParseTranslationUnitInfo*>(UserData);
2144 CXIndex CIdx = PTUI->CIdx;
2145 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002146 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002147 int num_command_line_args = PTUI->num_command_line_args;
2148 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2149 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2150 unsigned options = PTUI->options;
2151 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002152
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002153 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002154 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002155
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002156 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2157
Douglas Gregor44c181a2010-07-23 00:33:23 +00002158 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002159 bool CompleteTranslationUnit
2160 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002161 bool CacheCodeCompetionResults
2162 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002163 bool CXXPrecompilePreamble
2164 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2165 bool CXXChainedPCH
2166 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002167
Douglas Gregor5352ac02010-01-28 00:27:43 +00002168 // Configure the diagnostics.
2169 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002170 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2171 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002172
Douglas Gregor4db64a42010-01-23 00:14:00 +00002173 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2174 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002175 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002176 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002177 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002178 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2179 Buffer));
2180 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002181
Douglas Gregorb10daed2010-10-11 16:52:23 +00002182 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002183
Ted Kremenek139ba862009-10-22 00:03:57 +00002184 // The 'source_filename' argument is optional. If the caller does not
2185 // specify it then it is assumed that the source file is specified
2186 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002187 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002188 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002189
2190 // Since the Clang C library is primarily used by batch tools dealing with
2191 // (often very broken) source code, where spell-checking can have a
2192 // significant negative impact on performance (particularly when
2193 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002194 // Only do this if we haven't found a spell-checking-related argument.
2195 bool FoundSpellCheckingArgument = false;
2196 for (int I = 0; I != num_command_line_args; ++I) {
2197 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2198 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2199 FoundSpellCheckingArgument = true;
2200 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002201 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002202 }
2203 if (!FoundSpellCheckingArgument)
2204 Args.push_back("-fno-spell-checking");
2205
2206 Args.insert(Args.end(), command_line_args,
2207 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002208
Douglas Gregor44c181a2010-07-23 00:33:23 +00002209 // Do we need the detailed preprocessing record?
2210 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002211 Args.push_back("-Xclang");
2212 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002213 }
2214
Douglas Gregorb10daed2010-10-11 16:52:23 +00002215 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002216 llvm::OwningPtr<ASTUnit> Unit(
2217 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2218 Diags,
2219 CXXIdx->getClangResourcesPath(),
2220 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002221 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002222 RemappedFiles.data(),
2223 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002224 PrecompilePreamble,
2225 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002226 CacheCodeCompetionResults,
2227 CXXPrecompilePreamble,
2228 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002229
Douglas Gregorb10daed2010-10-11 16:52:23 +00002230 if (NumErrors != Diags->getNumErrors()) {
2231 // Make sure to check that 'Unit' is non-NULL.
2232 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2233 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2234 DEnd = Unit->stored_diag_end();
2235 D != DEnd; ++D) {
2236 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2237 CXString Msg = clang_formatDiagnostic(&Diag,
2238 clang_defaultDiagnosticDisplayOptions());
2239 fprintf(stderr, "%s\n", clang_getCString(Msg));
2240 clang_disposeString(Msg);
2241 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002242#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002243 // On Windows, force a flush, since there may be multiple copies of
2244 // stderr and stdout in the file system, all with different buffers
2245 // but writing to the same device.
2246 fflush(stderr);
2247#endif
2248 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002249 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002250
Ted Kremeneka60ed472010-11-16 08:15:36 +00002251 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002252}
2253CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2254 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002255 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002256 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002257 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002258 unsigned num_unsaved_files,
2259 unsigned options) {
2260 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002261 num_command_line_args, unsaved_files,
2262 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002263 llvm::CrashRecoveryContext CRC;
2264
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002265 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002266 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2267 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2268 fprintf(stderr, " 'command_line_args' : [");
2269 for (int i = 0; i != num_command_line_args; ++i) {
2270 if (i)
2271 fprintf(stderr, ", ");
2272 fprintf(stderr, "'%s'", command_line_args[i]);
2273 }
2274 fprintf(stderr, "],\n");
2275 fprintf(stderr, " 'unsaved_files' : [");
2276 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2277 if (i)
2278 fprintf(stderr, ", ");
2279 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2280 unsaved_files[i].Length);
2281 }
2282 fprintf(stderr, "],\n");
2283 fprintf(stderr, " 'options' : %d,\n", options);
2284 fprintf(stderr, "}\n");
2285
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002286 return 0;
2287 }
2288
2289 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002290}
2291
Douglas Gregor19998442010-08-13 15:35:05 +00002292unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2293 return CXSaveTranslationUnit_None;
2294}
2295
2296int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2297 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002298 if (!TU)
2299 return 1;
2300
Ted Kremeneka60ed472010-11-16 08:15:36 +00002301 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002302}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002303
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002304void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002305 if (CTUnit) {
2306 // If the translation unit has been marked as unsafe to free, just discard
2307 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002308 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002309 return;
2310
Ted Kremeneka60ed472010-11-16 08:15:36 +00002311 delete static_cast<ASTUnit *>(CTUnit->TUData);
2312 disposeCXStringPool(CTUnit->StringPool);
2313 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002314 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002315}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002316
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002317unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2318 return CXReparse_None;
2319}
2320
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002321struct ReparseTranslationUnitInfo {
2322 CXTranslationUnit TU;
2323 unsigned num_unsaved_files;
2324 struct CXUnsavedFile *unsaved_files;
2325 unsigned options;
2326 int result;
2327};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002328
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002329static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002330 ReparseTranslationUnitInfo *RTUI =
2331 static_cast<ReparseTranslationUnitInfo*>(UserData);
2332 CXTranslationUnit TU = RTUI->TU;
2333 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2334 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2335 unsigned options = RTUI->options;
2336 (void) options;
2337 RTUI->result = 1;
2338
Douglas Gregorabc563f2010-07-19 21:46:24 +00002339 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002340 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002341
Ted Kremeneka60ed472010-11-16 08:15:36 +00002342 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002343 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002344
2345 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2346 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2347 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2348 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002349 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002350 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2351 Buffer));
2352 }
2353
Douglas Gregor593b0c12010-09-23 18:47:53 +00002354 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2355 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002356}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002357
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002358int clang_reparseTranslationUnit(CXTranslationUnit TU,
2359 unsigned num_unsaved_files,
2360 struct CXUnsavedFile *unsaved_files,
2361 unsigned options) {
2362 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2363 options, 0 };
2364 llvm::CrashRecoveryContext CRC;
2365
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002366 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002367 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002368 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002369 return 1;
2370 }
2371
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002372
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002373 return RTUI.result;
2374}
2375
Douglas Gregordf95a132010-08-09 20:45:32 +00002376
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002377CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002378 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002379 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002380
Ted Kremeneka60ed472010-11-16 08:15:36 +00002381 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002382 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002383}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002384
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002385CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002386 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002387 return Result;
2388}
2389
Ted Kremenekfb480492010-01-13 21:46:36 +00002390} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002391
Ted Kremenekfb480492010-01-13 21:46:36 +00002392//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002393// CXSourceLocation and CXSourceRange Operations.
2394//===----------------------------------------------------------------------===//
2395
Douglas Gregorb9790342010-01-22 21:44:22 +00002396extern "C" {
2397CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002398 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002399 return Result;
2400}
2401
2402unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002403 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2404 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2405 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002406}
2407
2408CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2409 CXFile file,
2410 unsigned line,
2411 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002412 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002413 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002414
Ted Kremeneka60ed472010-11-16 08:15:36 +00002415 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002416 SourceLocation SLoc
2417 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002418 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002419 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002420 if (SLoc.isInvalid()) return clang_getNullLocation();
2421
2422 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2423}
2424
2425CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2426 CXFile file,
2427 unsigned offset) {
2428 if (!tu || !file)
2429 return clang_getNullLocation();
2430
Ted Kremeneka60ed472010-11-16 08:15:36 +00002431 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002432 SourceLocation Start
2433 = CXXUnit->getSourceManager().getLocation(
2434 static_cast<const FileEntry *>(file),
2435 1, 1);
2436 if (Start.isInvalid()) return clang_getNullLocation();
2437
2438 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2439
2440 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002442 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002443}
2444
Douglas Gregor5352ac02010-01-28 00:27:43 +00002445CXSourceRange clang_getNullRange() {
2446 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2447 return Result;
2448}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002449
Douglas Gregor5352ac02010-01-28 00:27:43 +00002450CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2451 if (begin.ptr_data[0] != end.ptr_data[0] ||
2452 begin.ptr_data[1] != end.ptr_data[1])
2453 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002454
2455 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002456 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002457 return Result;
2458}
2459
Douglas Gregor46766dc2010-01-26 19:19:08 +00002460void clang_getInstantiationLocation(CXSourceLocation location,
2461 CXFile *file,
2462 unsigned *line,
2463 unsigned *column,
2464 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002465 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2466
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002467 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002468 if (file)
2469 *file = 0;
2470 if (line)
2471 *line = 0;
2472 if (column)
2473 *column = 0;
2474 if (offset)
2475 *offset = 0;
2476 return;
2477 }
2478
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002479 const SourceManager &SM =
2480 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002481 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002482
2483 if (file)
2484 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2485 if (line)
2486 *line = SM.getInstantiationLineNumber(InstLoc);
2487 if (column)
2488 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002489 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002490 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002491}
2492
Douglas Gregora9b06d42010-11-09 06:24:54 +00002493void clang_getSpellingLocation(CXSourceLocation location,
2494 CXFile *file,
2495 unsigned *line,
2496 unsigned *column,
2497 unsigned *offset) {
2498 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2499
2500 if (!location.ptr_data[0] || Loc.isInvalid()) {
2501 if (file)
2502 *file = 0;
2503 if (line)
2504 *line = 0;
2505 if (column)
2506 *column = 0;
2507 if (offset)
2508 *offset = 0;
2509 return;
2510 }
2511
2512 const SourceManager &SM =
2513 *static_cast<const SourceManager*>(location.ptr_data[0]);
2514 SourceLocation SpellLoc = Loc;
2515 if (SpellLoc.isMacroID()) {
2516 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2517 if (SimpleSpellingLoc.isFileID() &&
2518 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2519 SpellLoc = SimpleSpellingLoc;
2520 else
2521 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2522 }
2523
2524 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2525 FileID FID = LocInfo.first;
2526 unsigned FileOffset = LocInfo.second;
2527
2528 if (file)
2529 *file = (void *)SM.getFileEntryForID(FID);
2530 if (line)
2531 *line = SM.getLineNumber(FID, FileOffset);
2532 if (column)
2533 *column = SM.getColumnNumber(FID, FileOffset);
2534 if (offset)
2535 *offset = FileOffset;
2536}
2537
Douglas Gregor1db19de2010-01-19 21:36:55 +00002538CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002539 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002540 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002541 return Result;
2542}
2543
2544CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002545 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002546 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002547 return Result;
2548}
2549
Douglas Gregorb9790342010-01-22 21:44:22 +00002550} // end: extern "C"
2551
Douglas Gregor1db19de2010-01-19 21:36:55 +00002552//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002553// CXFile Operations.
2554//===----------------------------------------------------------------------===//
2555
2556extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002557CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002558 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002559 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002560
Steve Naroff88145032009-10-27 14:35:18 +00002561 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002562 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002563}
2564
2565time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002566 if (!SFile)
2567 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002568
Steve Naroff88145032009-10-27 14:35:18 +00002569 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2570 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002571}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002572
Douglas Gregorb9790342010-01-22 21:44:22 +00002573CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2574 if (!tu)
2575 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002576
Ted Kremeneka60ed472010-11-16 08:15:36 +00002577 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002578
Douglas Gregorb9790342010-01-22 21:44:22 +00002579 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002580 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2581 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002582 return const_cast<FileEntry *>(File);
2583}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002584
Ted Kremenekfb480492010-01-13 21:46:36 +00002585} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002586
Ted Kremenekfb480492010-01-13 21:46:36 +00002587//===----------------------------------------------------------------------===//
2588// CXCursor Operations.
2589//===----------------------------------------------------------------------===//
2590
Ted Kremenekfb480492010-01-13 21:46:36 +00002591static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002592 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2593 return getDeclFromExpr(CE->getSubExpr());
2594
Ted Kremenekfb480492010-01-13 21:46:36 +00002595 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2596 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002597 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2598 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002599 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2600 return ME->getMemberDecl();
2601 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2602 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002603 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2604 return PRE->getProperty();
2605
Ted Kremenekfb480492010-01-13 21:46:36 +00002606 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2607 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002608 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2609 if (!CE->isElidable())
2610 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002611 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2612 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002613
Douglas Gregordb1314e2010-10-01 21:11:22 +00002614 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2615 return PE->getProtocol();
2616
Ted Kremenekfb480492010-01-13 21:46:36 +00002617 return 0;
2618}
2619
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002620static SourceLocation getLocationFromExpr(Expr *E) {
2621 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2622 return /*FIXME:*/Msg->getLeftLoc();
2623 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2624 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002625 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2626 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002627 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2628 return Member->getMemberLoc();
2629 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2630 return Ivar->getLocation();
2631 return E->getLocStart();
2632}
2633
Ted Kremenekfb480492010-01-13 21:46:36 +00002634extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002635
2636unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002637 CXCursorVisitor visitor,
2638 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002639 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2640 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002641 return CursorVis.VisitChildren(parent);
2642}
2643
David Chisnall3387c652010-11-03 14:12:26 +00002644#ifndef __has_feature
2645#define __has_feature(x) 0
2646#endif
2647#if __has_feature(blocks)
2648typedef enum CXChildVisitResult
2649 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2650
2651static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2652 CXClientData client_data) {
2653 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2654 return block(cursor, parent);
2655}
2656#else
2657// If we are compiled with a compiler that doesn't have native blocks support,
2658// define and call the block manually, so the
2659typedef struct _CXChildVisitResult
2660{
2661 void *isa;
2662 int flags;
2663 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002664 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2665 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002666} *CXCursorVisitorBlock;
2667
2668static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2669 CXClientData client_data) {
2670 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2671 return block->invoke(block, cursor, parent);
2672}
2673#endif
2674
2675
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002676unsigned clang_visitChildrenWithBlock(CXCursor parent,
2677 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002678 return clang_visitChildren(parent, visitWithBlock, block);
2679}
2680
Douglas Gregor78205d42010-01-20 21:45:58 +00002681static CXString getDeclSpelling(Decl *D) {
2682 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002683 if (!ND) {
2684 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2685 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2686 return createCXString(Property->getIdentifier()->getName());
2687
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002688 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002689 }
2690
Douglas Gregor78205d42010-01-20 21:45:58 +00002691 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002692 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002693
Douglas Gregor78205d42010-01-20 21:45:58 +00002694 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2695 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2696 // and returns different names. NamedDecl returns the class name and
2697 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002698 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002699
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002700 if (isa<UsingDirectiveDecl>(D))
2701 return createCXString("");
2702
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002703 llvm::SmallString<1024> S;
2704 llvm::raw_svector_ostream os(S);
2705 ND->printName(os);
2706
2707 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002708}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002709
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002710CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002711 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002712 return clang_getTranslationUnitSpelling(
2713 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002714
Steve Narofff334b4e2009-09-02 18:26:48 +00002715 if (clang_isReference(C.kind)) {
2716 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002717 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002718 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002719 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002720 }
2721 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002722 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002723 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002724 }
2725 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002726 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002727 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002728 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002729 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002730 case CXCursor_CXXBaseSpecifier: {
2731 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2732 return createCXString(B->getType().getAsString());
2733 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002734 case CXCursor_TypeRef: {
2735 TypeDecl *Type = getCursorTypeRef(C).first;
2736 assert(Type && "Missing type decl");
2737
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002738 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2739 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002740 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002741 case CXCursor_TemplateRef: {
2742 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002743 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002744
2745 return createCXString(Template->getNameAsString());
2746 }
Douglas Gregor69319002010-08-31 23:48:11 +00002747
2748 case CXCursor_NamespaceRef: {
2749 NamedDecl *NS = getCursorNamespaceRef(C).first;
2750 assert(NS && "Missing namespace decl");
2751
2752 return createCXString(NS->getNameAsString());
2753 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002754
Douglas Gregora67e03f2010-09-09 21:42:20 +00002755 case CXCursor_MemberRef: {
2756 FieldDecl *Field = getCursorMemberRef(C).first;
2757 assert(Field && "Missing member decl");
2758
2759 return createCXString(Field->getNameAsString());
2760 }
2761
Douglas Gregor36897b02010-09-10 00:22:18 +00002762 case CXCursor_LabelRef: {
2763 LabelStmt *Label = getCursorLabelRef(C).first;
2764 assert(Label && "Missing label");
2765
2766 return createCXString(Label->getID()->getName());
2767 }
2768
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002769 case CXCursor_OverloadedDeclRef: {
2770 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2771 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2772 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2773 return createCXString(ND->getNameAsString());
2774 return createCXString("");
2775 }
2776 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2777 return createCXString(E->getName().getAsString());
2778 OverloadedTemplateStorage *Ovl
2779 = Storage.get<OverloadedTemplateStorage*>();
2780 if (Ovl->size() == 0)
2781 return createCXString("");
2782 return createCXString((*Ovl->begin())->getNameAsString());
2783 }
2784
Daniel Dunbaracca7252009-11-30 20:42:49 +00002785 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002786 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002787 }
2788 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002789
2790 if (clang_isExpression(C.kind)) {
2791 Decl *D = getDeclFromExpr(getCursorExpr(C));
2792 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002793 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002794 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002795 }
2796
Douglas Gregor36897b02010-09-10 00:22:18 +00002797 if (clang_isStatement(C.kind)) {
2798 Stmt *S = getCursorStmt(C);
2799 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2800 return createCXString(Label->getID()->getName());
2801
2802 return createCXString("");
2803 }
2804
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002805 if (C.kind == CXCursor_MacroInstantiation)
2806 return createCXString(getCursorMacroInstantiation(C)->getName()
2807 ->getNameStart());
2808
Douglas Gregor572feb22010-03-18 18:04:21 +00002809 if (C.kind == CXCursor_MacroDefinition)
2810 return createCXString(getCursorMacroDefinition(C)->getName()
2811 ->getNameStart());
2812
Douglas Gregorecdcb882010-10-20 22:00:55 +00002813 if (C.kind == CXCursor_InclusionDirective)
2814 return createCXString(getCursorInclusionDirective(C)->getFileName());
2815
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002816 if (clang_isDeclaration(C.kind))
2817 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002818
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002819 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002820}
2821
Douglas Gregor358559d2010-10-02 22:49:11 +00002822CXString clang_getCursorDisplayName(CXCursor C) {
2823 if (!clang_isDeclaration(C.kind))
2824 return clang_getCursorSpelling(C);
2825
2826 Decl *D = getCursorDecl(C);
2827 if (!D)
2828 return createCXString("");
2829
2830 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2831 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2832 D = FunTmpl->getTemplatedDecl();
2833
2834 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2835 llvm::SmallString<64> Str;
2836 llvm::raw_svector_ostream OS(Str);
2837 OS << Function->getNameAsString();
2838 if (Function->getPrimaryTemplate())
2839 OS << "<>";
2840 OS << "(";
2841 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2842 if (I)
2843 OS << ", ";
2844 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2845 }
2846
2847 if (Function->isVariadic()) {
2848 if (Function->getNumParams())
2849 OS << ", ";
2850 OS << "...";
2851 }
2852 OS << ")";
2853 return createCXString(OS.str());
2854 }
2855
2856 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2857 llvm::SmallString<64> Str;
2858 llvm::raw_svector_ostream OS(Str);
2859 OS << ClassTemplate->getNameAsString();
2860 OS << "<";
2861 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2862 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2863 if (I)
2864 OS << ", ";
2865
2866 NamedDecl *Param = Params->getParam(I);
2867 if (Param->getIdentifier()) {
2868 OS << Param->getIdentifier()->getName();
2869 continue;
2870 }
2871
2872 // There is no parameter name, which makes this tricky. Try to come up
2873 // with something useful that isn't too long.
2874 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2875 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2876 else if (NonTypeTemplateParmDecl *NTTP
2877 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2878 OS << NTTP->getType().getAsString(Policy);
2879 else
2880 OS << "template<...> class";
2881 }
2882
2883 OS << ">";
2884 return createCXString(OS.str());
2885 }
2886
2887 if (ClassTemplateSpecializationDecl *ClassSpec
2888 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2889 // If the type was explicitly written, use that.
2890 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2891 return createCXString(TSInfo->getType().getAsString(Policy));
2892
2893 llvm::SmallString<64> Str;
2894 llvm::raw_svector_ostream OS(Str);
2895 OS << ClassSpec->getNameAsString();
2896 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002897 ClassSpec->getTemplateArgs().data(),
2898 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002899 Policy);
2900 return createCXString(OS.str());
2901 }
2902
2903 return clang_getCursorSpelling(C);
2904}
2905
Ted Kremeneke68fff62010-02-17 00:41:32 +00002906CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002907 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002908 case CXCursor_FunctionDecl:
2909 return createCXString("FunctionDecl");
2910 case CXCursor_TypedefDecl:
2911 return createCXString("TypedefDecl");
2912 case CXCursor_EnumDecl:
2913 return createCXString("EnumDecl");
2914 case CXCursor_EnumConstantDecl:
2915 return createCXString("EnumConstantDecl");
2916 case CXCursor_StructDecl:
2917 return createCXString("StructDecl");
2918 case CXCursor_UnionDecl:
2919 return createCXString("UnionDecl");
2920 case CXCursor_ClassDecl:
2921 return createCXString("ClassDecl");
2922 case CXCursor_FieldDecl:
2923 return createCXString("FieldDecl");
2924 case CXCursor_VarDecl:
2925 return createCXString("VarDecl");
2926 case CXCursor_ParmDecl:
2927 return createCXString("ParmDecl");
2928 case CXCursor_ObjCInterfaceDecl:
2929 return createCXString("ObjCInterfaceDecl");
2930 case CXCursor_ObjCCategoryDecl:
2931 return createCXString("ObjCCategoryDecl");
2932 case CXCursor_ObjCProtocolDecl:
2933 return createCXString("ObjCProtocolDecl");
2934 case CXCursor_ObjCPropertyDecl:
2935 return createCXString("ObjCPropertyDecl");
2936 case CXCursor_ObjCIvarDecl:
2937 return createCXString("ObjCIvarDecl");
2938 case CXCursor_ObjCInstanceMethodDecl:
2939 return createCXString("ObjCInstanceMethodDecl");
2940 case CXCursor_ObjCClassMethodDecl:
2941 return createCXString("ObjCClassMethodDecl");
2942 case CXCursor_ObjCImplementationDecl:
2943 return createCXString("ObjCImplementationDecl");
2944 case CXCursor_ObjCCategoryImplDecl:
2945 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002946 case CXCursor_CXXMethod:
2947 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002948 case CXCursor_UnexposedDecl:
2949 return createCXString("UnexposedDecl");
2950 case CXCursor_ObjCSuperClassRef:
2951 return createCXString("ObjCSuperClassRef");
2952 case CXCursor_ObjCProtocolRef:
2953 return createCXString("ObjCProtocolRef");
2954 case CXCursor_ObjCClassRef:
2955 return createCXString("ObjCClassRef");
2956 case CXCursor_TypeRef:
2957 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002958 case CXCursor_TemplateRef:
2959 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002960 case CXCursor_NamespaceRef:
2961 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002962 case CXCursor_MemberRef:
2963 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002964 case CXCursor_LabelRef:
2965 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002966 case CXCursor_OverloadedDeclRef:
2967 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002968 case CXCursor_UnexposedExpr:
2969 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002970 case CXCursor_BlockExpr:
2971 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002972 case CXCursor_DeclRefExpr:
2973 return createCXString("DeclRefExpr");
2974 case CXCursor_MemberRefExpr:
2975 return createCXString("MemberRefExpr");
2976 case CXCursor_CallExpr:
2977 return createCXString("CallExpr");
2978 case CXCursor_ObjCMessageExpr:
2979 return createCXString("ObjCMessageExpr");
2980 case CXCursor_UnexposedStmt:
2981 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002982 case CXCursor_LabelStmt:
2983 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002984 case CXCursor_InvalidFile:
2985 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002986 case CXCursor_InvalidCode:
2987 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002988 case CXCursor_NoDeclFound:
2989 return createCXString("NoDeclFound");
2990 case CXCursor_NotImplemented:
2991 return createCXString("NotImplemented");
2992 case CXCursor_TranslationUnit:
2993 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002994 case CXCursor_UnexposedAttr:
2995 return createCXString("UnexposedAttr");
2996 case CXCursor_IBActionAttr:
2997 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002998 case CXCursor_IBOutletAttr:
2999 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003000 case CXCursor_IBOutletCollectionAttr:
3001 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003002 case CXCursor_PreprocessingDirective:
3003 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003004 case CXCursor_MacroDefinition:
3005 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003006 case CXCursor_MacroInstantiation:
3007 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003008 case CXCursor_InclusionDirective:
3009 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003010 case CXCursor_Namespace:
3011 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003012 case CXCursor_LinkageSpec:
3013 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003014 case CXCursor_CXXBaseSpecifier:
3015 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003016 case CXCursor_Constructor:
3017 return createCXString("CXXConstructor");
3018 case CXCursor_Destructor:
3019 return createCXString("CXXDestructor");
3020 case CXCursor_ConversionFunction:
3021 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003022 case CXCursor_TemplateTypeParameter:
3023 return createCXString("TemplateTypeParameter");
3024 case CXCursor_NonTypeTemplateParameter:
3025 return createCXString("NonTypeTemplateParameter");
3026 case CXCursor_TemplateTemplateParameter:
3027 return createCXString("TemplateTemplateParameter");
3028 case CXCursor_FunctionTemplate:
3029 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003030 case CXCursor_ClassTemplate:
3031 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003032 case CXCursor_ClassTemplatePartialSpecialization:
3033 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003034 case CXCursor_NamespaceAlias:
3035 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003036 case CXCursor_UsingDirective:
3037 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003038 case CXCursor_UsingDeclaration:
3039 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003040 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003041
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003042 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003043 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003044}
Steve Naroff89922f82009-08-31 00:59:03 +00003045
Ted Kremeneke68fff62010-02-17 00:41:32 +00003046enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3047 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003048 CXClientData client_data) {
3049 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003050
3051 // If our current best cursor is the construction of a temporary object,
3052 // don't replace that cursor with a type reference, because we want
3053 // clang_getCursor() to point at the constructor.
3054 if (clang_isExpression(BestCursor->kind) &&
3055 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3056 cursor.kind == CXCursor_TypeRef)
3057 return CXChildVisit_Recurse;
3058
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003059 *BestCursor = cursor;
3060 return CXChildVisit_Recurse;
3061}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003062
Douglas Gregorb9790342010-01-22 21:44:22 +00003063CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3064 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003065 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003066
Ted Kremeneka60ed472010-11-16 08:15:36 +00003067 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003068 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3069
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003070 // Translate the given source location to make it point at the beginning of
3071 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003072 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003073
3074 // Guard against an invalid SourceLocation, or we may assert in one
3075 // of the following calls.
3076 if (SLoc.isInvalid())
3077 return clang_getNullCursor();
3078
Douglas Gregor40749ee2010-11-03 00:35:38 +00003079 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003080 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3081 CXXUnit->getASTContext().getLangOptions());
3082
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003083 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3084 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003085 // FIXME: Would be great to have a "hint" cursor, then walk from that
3086 // hint cursor upward until we find a cursor whose source range encloses
3087 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003088 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3089 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003090 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003091 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003092 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003093
3094 if (Logging) {
3095 CXFile SearchFile;
3096 unsigned SearchLine, SearchColumn;
3097 CXFile ResultFile;
3098 unsigned ResultLine, ResultColumn;
3099 CXString SearchFileName, ResultFileName, KindSpelling;
3100 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3101
3102 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3103 0);
3104 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3105 &ResultColumn, 0);
3106 SearchFileName = clang_getFileName(SearchFile);
3107 ResultFileName = clang_getFileName(ResultFile);
3108 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3109 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3110 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3111 clang_getCString(KindSpelling),
3112 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3113 clang_disposeString(SearchFileName);
3114 clang_disposeString(ResultFileName);
3115 clang_disposeString(KindSpelling);
3116 }
3117
Ted Kremeneke68fff62010-02-17 00:41:32 +00003118 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003119}
3120
Ted Kremenek73885552009-11-17 19:28:59 +00003121CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003122 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003123}
3124
3125unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003126 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003127}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003128
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003129unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003130 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3131}
3132
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003133unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003134 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3135}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003136
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003137unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003138 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3139}
3140
Douglas Gregor97b98722010-01-19 23:20:36 +00003141unsigned clang_isExpression(enum CXCursorKind K) {
3142 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3143}
3144
3145unsigned clang_isStatement(enum CXCursorKind K) {
3146 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3147}
3148
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003149unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3150 return K == CXCursor_TranslationUnit;
3151}
3152
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003153unsigned clang_isPreprocessing(enum CXCursorKind K) {
3154 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3155}
3156
Ted Kremenekad6eff62010-03-08 21:17:29 +00003157unsigned clang_isUnexposed(enum CXCursorKind K) {
3158 switch (K) {
3159 case CXCursor_UnexposedDecl:
3160 case CXCursor_UnexposedExpr:
3161 case CXCursor_UnexposedStmt:
3162 case CXCursor_UnexposedAttr:
3163 return true;
3164 default:
3165 return false;
3166 }
3167}
3168
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003169CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003170 return C.kind;
3171}
3172
Douglas Gregor98258af2010-01-18 22:46:11 +00003173CXSourceLocation clang_getCursorLocation(CXCursor C) {
3174 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003175 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003176 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003177 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3178 = getCursorObjCSuperClassRef(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 }
3181
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003182 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003183 std::pair<ObjCProtocolDecl *, SourceLocation> P
3184 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003185 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003186 }
3187
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003188 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003189 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3190 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003191 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003192 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003193
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003194 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003195 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003196 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003197 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003198
3199 case CXCursor_TemplateRef: {
3200 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3201 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3202 }
3203
Douglas Gregor69319002010-08-31 23:48:11 +00003204 case CXCursor_NamespaceRef: {
3205 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3206 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3207 }
3208
Douglas Gregora67e03f2010-09-09 21:42:20 +00003209 case CXCursor_MemberRef: {
3210 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3211 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3212 }
3213
Ted Kremenek3064ef92010-08-27 21:34:58 +00003214 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003215 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3216 if (!BaseSpec)
3217 return clang_getNullLocation();
3218
3219 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3220 return cxloc::translateSourceLocation(getCursorContext(C),
3221 TSInfo->getTypeLoc().getBeginLoc());
3222
3223 return cxloc::translateSourceLocation(getCursorContext(C),
3224 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003225 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003226
Douglas Gregor36897b02010-09-10 00:22:18 +00003227 case CXCursor_LabelRef: {
3228 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3229 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3230 }
3231
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003232 case CXCursor_OverloadedDeclRef:
3233 return cxloc::translateSourceLocation(getCursorContext(C),
3234 getCursorOverloadedDeclRef(C).second);
3235
Douglas Gregorf46034a2010-01-18 23:41:10 +00003236 default:
3237 // FIXME: Need a way to enumerate all non-reference cases.
3238 llvm_unreachable("Missed a reference kind");
3239 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003240 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003241
3242 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003243 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003244 getLocationFromExpr(getCursorExpr(C)));
3245
Douglas Gregor36897b02010-09-10 00:22:18 +00003246 if (clang_isStatement(C.kind))
3247 return cxloc::translateSourceLocation(getCursorContext(C),
3248 getCursorStmt(C)->getLocStart());
3249
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003250 if (C.kind == CXCursor_PreprocessingDirective) {
3251 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3252 return cxloc::translateSourceLocation(getCursorContext(C), L);
3253 }
Douglas Gregor48072312010-03-18 15:23:44 +00003254
3255 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003256 SourceLocation L
3257 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003258 return cxloc::translateSourceLocation(getCursorContext(C), L);
3259 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003260
3261 if (C.kind == CXCursor_MacroDefinition) {
3262 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3263 return cxloc::translateSourceLocation(getCursorContext(C), L);
3264 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003265
3266 if (C.kind == CXCursor_InclusionDirective) {
3267 SourceLocation L
3268 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3269 return cxloc::translateSourceLocation(getCursorContext(C), L);
3270 }
3271
Ted Kremenek9a700d22010-05-12 06:16:13 +00003272 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003273 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003274
Douglas Gregorf46034a2010-01-18 23:41:10 +00003275 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003276 SourceLocation Loc = D->getLocation();
3277 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3278 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003279 // FIXME: Multiple variables declared in a single declaration
3280 // currently lack the information needed to correctly determine their
3281 // ranges when accounting for the type-specifier. We use context
3282 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3283 // and if so, whether it is the first decl.
3284 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3285 if (!cxcursor::isFirstInDeclGroup(C))
3286 Loc = VD->getLocation();
3287 }
3288
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003289 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003290}
Douglas Gregora7bde202010-01-19 00:34:46 +00003291
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003292} // end extern "C"
3293
3294static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003295 if (clang_isReference(C.kind)) {
3296 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003297 case CXCursor_ObjCSuperClassRef:
3298 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003299
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003300 case CXCursor_ObjCProtocolRef:
3301 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003302
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003303 case CXCursor_ObjCClassRef:
3304 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003305
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003306 case CXCursor_TypeRef:
3307 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003308
3309 case CXCursor_TemplateRef:
3310 return getCursorTemplateRef(C).second;
3311
Douglas Gregor69319002010-08-31 23:48:11 +00003312 case CXCursor_NamespaceRef:
3313 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003314
3315 case CXCursor_MemberRef:
3316 return getCursorMemberRef(C).second;
3317
Ted Kremenek3064ef92010-08-27 21:34:58 +00003318 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003319 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003320
Douglas Gregor36897b02010-09-10 00:22:18 +00003321 case CXCursor_LabelRef:
3322 return getCursorLabelRef(C).second;
3323
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003324 case CXCursor_OverloadedDeclRef:
3325 return getCursorOverloadedDeclRef(C).second;
3326
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003327 default:
3328 // FIXME: Need a way to enumerate all non-reference cases.
3329 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003330 }
3331 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003332
3333 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003334 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003335
3336 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003337 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003338
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003339 if (C.kind == CXCursor_PreprocessingDirective)
3340 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003341
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003342 if (C.kind == CXCursor_MacroInstantiation)
3343 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003344
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003345 if (C.kind == CXCursor_MacroDefinition)
3346 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003347
3348 if (C.kind == CXCursor_InclusionDirective)
3349 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3350
Ted Kremenek007a7c92010-11-01 23:26:51 +00003351 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3352 Decl *D = cxcursor::getCursorDecl(C);
3353 SourceRange R = D->getSourceRange();
3354 // FIXME: Multiple variables declared in a single declaration
3355 // currently lack the information needed to correctly determine their
3356 // ranges when accounting for the type-specifier. We use context
3357 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3358 // and if so, whether it is the first decl.
3359 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3360 if (!cxcursor::isFirstInDeclGroup(C))
3361 R.setBegin(VD->getLocation());
3362 }
3363 return R;
3364 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003365 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003366
3367extern "C" {
3368
3369CXSourceRange clang_getCursorExtent(CXCursor C) {
3370 SourceRange R = getRawCursorExtent(C);
3371 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003372 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003373
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003374 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003375}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003376
3377CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003378 if (clang_isInvalid(C.kind))
3379 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003380
Ted Kremeneka60ed472010-11-16 08:15:36 +00003381 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003382 if (clang_isDeclaration(C.kind)) {
3383 Decl *D = getCursorDecl(C);
3384 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003385 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003386 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003387 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003388 if (ObjCForwardProtocolDecl *Protocols
3389 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003390 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003391 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3392 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3393 return MakeCXCursor(Property, tu);
3394
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003395 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003396 }
3397
Douglas Gregor97b98722010-01-19 23:20:36 +00003398 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003399 Expr *E = getCursorExpr(C);
3400 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003401 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003402 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003403
3404 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003405 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003406
Douglas Gregor97b98722010-01-19 23:20:36 +00003407 return clang_getNullCursor();
3408 }
3409
Douglas Gregor36897b02010-09-10 00:22:18 +00003410 if (clang_isStatement(C.kind)) {
3411 Stmt *S = getCursorStmt(C);
3412 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003413 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003414
3415 return clang_getNullCursor();
3416 }
3417
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003418 if (C.kind == CXCursor_MacroInstantiation) {
3419 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003420 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003421 }
3422
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003423 if (!clang_isReference(C.kind))
3424 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003425
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003426 switch (C.kind) {
3427 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003428 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003429
3430 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003431 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003432
3433 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003434 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003435
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003436 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003437 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003438
3439 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003440 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003441
Douglas Gregor69319002010-08-31 23:48:11 +00003442 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003443 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003444
Douglas Gregora67e03f2010-09-09 21:42:20 +00003445 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003446 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003447
Ted Kremenek3064ef92010-08-27 21:34:58 +00003448 case CXCursor_CXXBaseSpecifier: {
3449 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3450 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003451 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003452 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003453
Douglas Gregor36897b02010-09-10 00:22:18 +00003454 case CXCursor_LabelRef:
3455 // FIXME: We end up faking the "parent" declaration here because we
3456 // don't want to make CXCursor larger.
3457 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003458 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3459 .getTranslationUnitDecl(),
3460 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003461
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003462 case CXCursor_OverloadedDeclRef:
3463 return C;
3464
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003465 default:
3466 // We would prefer to enumerate all non-reference cursor kinds here.
3467 llvm_unreachable("Unhandled reference cursor kind");
3468 break;
3469 }
3470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003471
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003472 return clang_getNullCursor();
3473}
3474
Douglas Gregorb6998662010-01-19 19:34:47 +00003475CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003476 if (clang_isInvalid(C.kind))
3477 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003478
Ted Kremeneka60ed472010-11-16 08:15:36 +00003479 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003480
Douglas Gregorb6998662010-01-19 19:34:47 +00003481 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003482 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003483 C = clang_getCursorReferenced(C);
3484 WasReference = true;
3485 }
3486
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003487 if (C.kind == CXCursor_MacroInstantiation)
3488 return clang_getCursorReferenced(C);
3489
Douglas Gregorb6998662010-01-19 19:34:47 +00003490 if (!clang_isDeclaration(C.kind))
3491 return clang_getNullCursor();
3492
3493 Decl *D = getCursorDecl(C);
3494 if (!D)
3495 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003496
Douglas Gregorb6998662010-01-19 19:34:47 +00003497 switch (D->getKind()) {
3498 // Declaration kinds that don't really separate the notions of
3499 // declaration and definition.
3500 case Decl::Namespace:
3501 case Decl::Typedef:
3502 case Decl::TemplateTypeParm:
3503 case Decl::EnumConstant:
3504 case Decl::Field:
3505 case Decl::ObjCIvar:
3506 case Decl::ObjCAtDefsField:
3507 case Decl::ImplicitParam:
3508 case Decl::ParmVar:
3509 case Decl::NonTypeTemplateParm:
3510 case Decl::TemplateTemplateParm:
3511 case Decl::ObjCCategoryImpl:
3512 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003513 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003514 case Decl::LinkageSpec:
3515 case Decl::ObjCPropertyImpl:
3516 case Decl::FileScopeAsm:
3517 case Decl::StaticAssert:
3518 case Decl::Block:
3519 return C;
3520
3521 // Declaration kinds that don't make any sense here, but are
3522 // nonetheless harmless.
3523 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003524 break;
3525
3526 // Declaration kinds for which the definition is not resolvable.
3527 case Decl::UnresolvedUsingTypename:
3528 case Decl::UnresolvedUsingValue:
3529 break;
3530
3531 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003532 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003533 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003534
3535 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003536 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003537
3538 case Decl::Enum:
3539 case Decl::Record:
3540 case Decl::CXXRecord:
3541 case Decl::ClassTemplateSpecialization:
3542 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003543 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003544 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003545 return clang_getNullCursor();
3546
3547 case Decl::Function:
3548 case Decl::CXXMethod:
3549 case Decl::CXXConstructor:
3550 case Decl::CXXDestructor:
3551 case Decl::CXXConversion: {
3552 const FunctionDecl *Def = 0;
3553 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003554 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003555 return clang_getNullCursor();
3556 }
3557
3558 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003559 // Ask the variable if it has a definition.
3560 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003561 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003562 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003563 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003564
Douglas Gregorb6998662010-01-19 19:34:47 +00003565 case Decl::FunctionTemplate: {
3566 const FunctionDecl *Def = 0;
3567 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003568 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003569 return clang_getNullCursor();
3570 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003571
Douglas Gregorb6998662010-01-19 19:34:47 +00003572 case Decl::ClassTemplate: {
3573 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003574 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003575 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003576 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003577 return clang_getNullCursor();
3578 }
3579
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003580 case Decl::Using:
3581 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003582 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003583
3584 case Decl::UsingShadow:
3585 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003586 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003587 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003588
3589 case Decl::ObjCMethod: {
3590 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3591 if (Method->isThisDeclarationADefinition())
3592 return C;
3593
3594 // Dig out the method definition in the associated
3595 // @implementation, if we have it.
3596 // FIXME: The ASTs should make finding the definition easier.
3597 if (ObjCInterfaceDecl *Class
3598 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3599 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3600 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3601 Method->isInstanceMethod()))
3602 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003603 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003604
3605 return clang_getNullCursor();
3606 }
3607
3608 case Decl::ObjCCategory:
3609 if (ObjCCategoryImplDecl *Impl
3610 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003611 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003612 return clang_getNullCursor();
3613
3614 case Decl::ObjCProtocol:
3615 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3616 return C;
3617 return clang_getNullCursor();
3618
3619 case Decl::ObjCInterface:
3620 // There are two notions of a "definition" for an Objective-C
3621 // class: the interface and its implementation. When we resolved a
3622 // reference to an Objective-C class, produce the @interface as
3623 // the definition; when we were provided with the interface,
3624 // produce the @implementation as the definition.
3625 if (WasReference) {
3626 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3627 return C;
3628 } else if (ObjCImplementationDecl *Impl
3629 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003630 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003631 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003632
Douglas Gregorb6998662010-01-19 19:34:47 +00003633 case Decl::ObjCProperty:
3634 // FIXME: We don't really know where to find the
3635 // ObjCPropertyImplDecls that implement this property.
3636 return clang_getNullCursor();
3637
3638 case Decl::ObjCCompatibleAlias:
3639 if (ObjCInterfaceDecl *Class
3640 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3641 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003642 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003643
Douglas Gregorb6998662010-01-19 19:34:47 +00003644 return clang_getNullCursor();
3645
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003646 case Decl::ObjCForwardProtocol:
3647 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003648 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003649
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003650 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003651 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003652 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003653
3654 case Decl::Friend:
3655 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003656 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003657 return clang_getNullCursor();
3658
3659 case Decl::FriendTemplate:
3660 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003661 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003662 return clang_getNullCursor();
3663 }
3664
3665 return clang_getNullCursor();
3666}
3667
3668unsigned clang_isCursorDefinition(CXCursor C) {
3669 if (!clang_isDeclaration(C.kind))
3670 return 0;
3671
3672 return clang_getCursorDefinition(C) == C;
3673}
3674
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003675unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003676 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003677 return 0;
3678
3679 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3680 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3681 return E->getNumDecls();
3682
3683 if (OverloadedTemplateStorage *S
3684 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3685 return S->size();
3686
3687 Decl *D = Storage.get<Decl*>();
3688 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003689 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003690 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3691 return Classes->size();
3692 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3693 return Protocols->protocol_size();
3694
3695 return 0;
3696}
3697
3698CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003699 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003700 return clang_getNullCursor();
3701
3702 if (index >= clang_getNumOverloadedDecls(cursor))
3703 return clang_getNullCursor();
3704
Ted Kremeneka60ed472010-11-16 08:15:36 +00003705 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003706 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3707 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003708 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003709
3710 if (OverloadedTemplateStorage *S
3711 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003712 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003713
3714 Decl *D = Storage.get<Decl*>();
3715 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3716 // FIXME: This is, unfortunately, linear time.
3717 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3718 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003719 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003720 }
3721
3722 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003723 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003724
3725 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003726 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003727
3728 return clang_getNullCursor();
3729}
3730
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003731void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003732 const char **startBuf,
3733 const char **endBuf,
3734 unsigned *startLine,
3735 unsigned *startColumn,
3736 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003737 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003738 assert(getCursorDecl(C) && "CXCursor has null decl");
3739 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003740 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3741 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003742
Steve Naroff4ade6d62009-09-23 17:52:52 +00003743 SourceManager &SM = FD->getASTContext().getSourceManager();
3744 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3745 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3746 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3747 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3748 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3749 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3750}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003751
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003752void clang_enableStackTraces(void) {
3753 llvm::sys::PrintStackTraceOnErrorSignal();
3754}
3755
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003756void clang_executeOnThread(void (*fn)(void*), void *user_data,
3757 unsigned stack_size) {
3758 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3759}
3760
Ted Kremenekfb480492010-01-13 21:46:36 +00003761} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003762
Ted Kremenekfb480492010-01-13 21:46:36 +00003763//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003764// Token-based Operations.
3765//===----------------------------------------------------------------------===//
3766
3767/* CXToken layout:
3768 * int_data[0]: a CXTokenKind
3769 * int_data[1]: starting token location
3770 * int_data[2]: token length
3771 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003772 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003773 * otherwise unused.
3774 */
3775extern "C" {
3776
3777CXTokenKind clang_getTokenKind(CXToken CXTok) {
3778 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3779}
3780
3781CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3782 switch (clang_getTokenKind(CXTok)) {
3783 case CXToken_Identifier:
3784 case CXToken_Keyword:
3785 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003786 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3787 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003788
3789 case CXToken_Literal: {
3790 // We have stashed the starting pointer in the ptr_data field. Use it.
3791 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003792 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003793 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003794
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003795 case CXToken_Punctuation:
3796 case CXToken_Comment:
3797 break;
3798 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003799
3800 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003801 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003802 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003803 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003804 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003805
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003806 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3807 std::pair<FileID, unsigned> LocInfo
3808 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003809 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003810 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003811 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3812 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003813 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003814
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003815 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003816}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003817
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003818CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003819 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820 if (!CXXUnit)
3821 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003822
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003823 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3824 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3825}
3826
3827CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003828 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003829 if (!CXXUnit)
3830 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003831
3832 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003833 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3834}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003836void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3837 CXToken **Tokens, unsigned *NumTokens) {
3838 if (Tokens)
3839 *Tokens = 0;
3840 if (NumTokens)
3841 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003842
Ted Kremeneka60ed472010-11-16 08:15:36 +00003843 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003844 if (!CXXUnit || !Tokens || !NumTokens)
3845 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
Douglas Gregorbdf60622010-03-05 21:16:25 +00003847 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3848
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003849 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003850 if (R.isInvalid())
3851 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003852
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003853 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3854 std::pair<FileID, unsigned> BeginLocInfo
3855 = SourceMgr.getDecomposedLoc(R.getBegin());
3856 std::pair<FileID, unsigned> EndLocInfo
3857 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 // Cannot tokenize across files.
3860 if (BeginLocInfo.first != EndLocInfo.first)
3861 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003862
3863 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003864 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003865 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003866 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003867 if (Invalid)
3868 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003869
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3871 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003872 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003873 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003874
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003875 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003876 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003877 llvm::SmallVector<CXToken, 32> CXTokens;
3878 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003879 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003880 do {
3881 // Lex the next token
3882 Lex.LexFromRawLexer(Tok);
3883 if (Tok.is(tok::eof))
3884 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003885
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003886 // Initialize the CXToken.
3887 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003888
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003889 // - Common fields
3890 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3891 CXTok.int_data[2] = Tok.getLength();
3892 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003893
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 // - Kind-specific fields
3895 if (Tok.isLiteral()) {
3896 CXTok.int_data[0] = CXToken_Literal;
3897 CXTok.ptr_data = (void *)Tok.getLiteralData();
3898 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003899 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003900 std::pair<FileID, unsigned> LocInfo
3901 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003902 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003903 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003904 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3905 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003906 return;
3907
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003908 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003909 IdentifierInfo *II
3910 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003911
David Chisnall096428b2010-10-13 21:44:48 +00003912 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003913 CXTok.int_data[0] = CXToken_Keyword;
3914 }
3915 else {
3916 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3917 CXToken_Identifier
3918 : CXToken_Keyword;
3919 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003920 CXTok.ptr_data = II;
3921 } else if (Tok.is(tok::comment)) {
3922 CXTok.int_data[0] = CXToken_Comment;
3923 CXTok.ptr_data = 0;
3924 } else {
3925 CXTok.int_data[0] = CXToken_Punctuation;
3926 CXTok.ptr_data = 0;
3927 }
3928 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003929 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003930 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003931
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003932 if (CXTokens.empty())
3933 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003934
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003935 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3936 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3937 *NumTokens = CXTokens.size();
3938}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003939
Ted Kremenek6db61092010-05-05 00:55:15 +00003940void clang_disposeTokens(CXTranslationUnit TU,
3941 CXToken *Tokens, unsigned NumTokens) {
3942 free(Tokens);
3943}
3944
3945} // end: extern "C"
3946
3947//===----------------------------------------------------------------------===//
3948// Token annotation APIs.
3949//===----------------------------------------------------------------------===//
3950
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003951typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003952static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3953 CXCursor parent,
3954 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003955namespace {
3956class AnnotateTokensWorker {
3957 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003958 CXToken *Tokens;
3959 CXCursor *Cursors;
3960 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003961 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003962 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003963 CursorVisitor AnnotateVis;
3964 SourceManager &SrcMgr;
3965
3966 bool MoreTokens() const { return TokIdx < NumTokens; }
3967 unsigned NextToken() const { return TokIdx; }
3968 void AdvanceToken() { ++TokIdx; }
3969 SourceLocation GetTokenLoc(unsigned tokI) {
3970 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3971 }
3972
Ted Kremenek6db61092010-05-05 00:55:15 +00003973public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003974 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003975 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003976 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003977 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003978 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003979 AnnotateVis(tu,
3980 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003981 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003982 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003983
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003984 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003985 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003986 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003987 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003988 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00003989 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003990};
3991}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003992
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003993void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3994 // Walk the AST within the region of interest, annotating tokens
3995 // along the way.
3996 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003997
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003998 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3999 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004000 if (Pos != Annotated.end() &&
4001 (clang_isInvalid(Cursors[I].kind) ||
4002 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004003 Cursors[I] = Pos->second;
4004 }
4005
4006 // Finish up annotating any tokens left.
4007 if (!MoreTokens())
4008 return;
4009
4010 const CXCursor &C = clang_getNullCursor();
4011 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4012 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4013 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004014 }
4015}
4016
Ted Kremenek6db61092010-05-05 00:55:15 +00004017enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004018AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004019 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004020 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004021 if (cursorRange.isInvalid())
4022 return CXChildVisit_Recurse;
4023
Douglas Gregor4419b672010-10-21 06:10:04 +00004024 if (clang_isPreprocessing(cursor.kind)) {
4025 // For macro instantiations, just note where the beginning of the macro
4026 // instantiation occurs.
4027 if (cursor.kind == CXCursor_MacroInstantiation) {
4028 Annotated[Loc.int_data] = cursor;
4029 return CXChildVisit_Recurse;
4030 }
4031
Douglas Gregor4419b672010-10-21 06:10:04 +00004032 // Items in the preprocessing record are kept separate from items in
4033 // declarations, so we keep a separate token index.
4034 unsigned SavedTokIdx = TokIdx;
4035 TokIdx = PreprocessingTokIdx;
4036
4037 // Skip tokens up until we catch up to the beginning of the preprocessing
4038 // entry.
4039 while (MoreTokens()) {
4040 const unsigned I = NextToken();
4041 SourceLocation TokLoc = GetTokenLoc(I);
4042 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4043 case RangeBefore:
4044 AdvanceToken();
4045 continue;
4046 case RangeAfter:
4047 case RangeOverlap:
4048 break;
4049 }
4050 break;
4051 }
4052
4053 // Look at all of the tokens within this range.
4054 while (MoreTokens()) {
4055 const unsigned I = NextToken();
4056 SourceLocation TokLoc = GetTokenLoc(I);
4057 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4058 case RangeBefore:
4059 assert(0 && "Infeasible");
4060 case RangeAfter:
4061 break;
4062 case RangeOverlap:
4063 Cursors[I] = cursor;
4064 AdvanceToken();
4065 continue;
4066 }
4067 break;
4068 }
4069
4070 // Save the preprocessing token index; restore the non-preprocessing
4071 // token index.
4072 PreprocessingTokIdx = TokIdx;
4073 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004074 return CXChildVisit_Recurse;
4075 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004076
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004077 if (cursorRange.isInvalid())
4078 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004079
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004080 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4081
Ted Kremeneka333c662010-05-12 05:29:33 +00004082 // Adjust the annotated range based specific declarations.
4083 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4084 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004085 Decl *D = cxcursor::getCursorDecl(cursor);
4086 // Don't visit synthesized ObjC methods, since they have no syntatic
4087 // representation in the source.
4088 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4089 if (MD->isSynthesized())
4090 return CXChildVisit_Continue;
4091 }
4092 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004093 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4094 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004095 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004096 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004097 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004098 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004099 }
4100 }
4101 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004102
Ted Kremenek3f404602010-08-14 01:14:06 +00004103 // If the location of the cursor occurs within a macro instantiation, record
4104 // the spelling location of the cursor in our annotation map. We can then
4105 // paper over the token labelings during a post-processing step to try and
4106 // get cursor mappings for tokens that are the *arguments* of a macro
4107 // instantiation.
4108 if (L.isMacroID()) {
4109 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4110 // Only invalidate the old annotation if it isn't part of a preprocessing
4111 // directive. Here we assume that the default construction of CXCursor
4112 // results in CXCursor.kind being an initialized value (i.e., 0). If
4113 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004114
Ted Kremenek3f404602010-08-14 01:14:06 +00004115 CXCursor &oldC = Annotated[rawEncoding];
4116 if (!clang_isPreprocessing(oldC.kind))
4117 oldC = cursor;
4118 }
4119
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004120 const enum CXCursorKind K = clang_getCursorKind(parent);
4121 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004122 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4123 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004124
4125 while (MoreTokens()) {
4126 const unsigned I = NextToken();
4127 SourceLocation TokLoc = GetTokenLoc(I);
4128 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4129 case RangeBefore:
4130 Cursors[I] = updateC;
4131 AdvanceToken();
4132 continue;
4133 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004134 case RangeOverlap:
4135 break;
4136 }
4137 break;
4138 }
4139
4140 // Visit children to get their cursor information.
4141 const unsigned BeforeChildren = NextToken();
4142 VisitChildren(cursor);
4143 const unsigned AfterChildren = NextToken();
4144
4145 // Adjust 'Last' to the last token within the extent of the cursor.
4146 while (MoreTokens()) {
4147 const unsigned I = NextToken();
4148 SourceLocation TokLoc = GetTokenLoc(I);
4149 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4150 case RangeBefore:
4151 assert(0 && "Infeasible");
4152 case RangeAfter:
4153 break;
4154 case RangeOverlap:
4155 Cursors[I] = updateC;
4156 AdvanceToken();
4157 continue;
4158 }
4159 break;
4160 }
4161 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004162
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004163 // Scan the tokens that are at the beginning of the cursor, but are not
4164 // capture by the child cursors.
4165
4166 // For AST elements within macros, rely on a post-annotate pass to
4167 // to correctly annotate the tokens with cursors. Otherwise we can
4168 // get confusing results of having tokens that map to cursors that really
4169 // are expanded by an instantiation.
4170 if (L.isMacroID())
4171 cursor = clang_getNullCursor();
4172
4173 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4174 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4175 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004176
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004177 Cursors[I] = cursor;
4178 }
4179 // Scan the tokens that are at the end of the cursor, but are not captured
4180 // but the child cursors.
4181 for (unsigned I = AfterChildren; I != Last; ++I)
4182 Cursors[I] = cursor;
4183
4184 TokIdx = Last;
4185 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004186}
4187
Ted Kremenek6db61092010-05-05 00:55:15 +00004188static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4189 CXCursor parent,
4190 CXClientData client_data) {
4191 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4192}
4193
Ted Kremenekab979612010-11-11 08:05:23 +00004194// This gets run a separate thread to avoid stack blowout.
4195static void runAnnotateTokensWorker(void *UserData) {
4196 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4197}
4198
Ted Kremenek6db61092010-05-05 00:55:15 +00004199extern "C" {
4200
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004201void clang_annotateTokens(CXTranslationUnit TU,
4202 CXToken *Tokens, unsigned NumTokens,
4203 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004204
4205 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004206 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004207
Douglas Gregor4419b672010-10-21 06:10:04 +00004208 // Any token we don't specifically annotate will have a NULL cursor.
4209 CXCursor C = clang_getNullCursor();
4210 for (unsigned I = 0; I != NumTokens; ++I)
4211 Cursors[I] = C;
4212
Ted Kremeneka60ed472010-11-16 08:15:36 +00004213 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004214 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004215 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004216
Douglas Gregorbdf60622010-03-05 21:16:25 +00004217 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004218
Douglas Gregor0396f462010-03-19 05:22:59 +00004219 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004220 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004221 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4222 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004223 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4224 clang_getTokenLocation(TU,
4225 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004226
Douglas Gregor0396f462010-03-19 05:22:59 +00004227 // A mapping from the source locations found when re-lexing or traversing the
4228 // region of interest to the corresponding cursors.
4229 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004230
4231 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004232 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004233 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4234 std::pair<FileID, unsigned> BeginLocInfo
4235 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4236 std::pair<FileID, unsigned> EndLocInfo
4237 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004239 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004240 bool Invalid = false;
4241 if (BeginLocInfo.first == EndLocInfo.first &&
4242 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4243 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004244 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4245 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004246 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004247 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004248 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004249
4250 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004251 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004252 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 Token Tok;
4254 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004255
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004256 reprocess:
4257 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4258 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004259 // don't see it while preprocessing these tokens later, but keep track
4260 // of all of the token locations inside this preprocessing directive so
4261 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004262 //
4263 // FIXME: Some simple tests here could identify macro definitions and
4264 // #undefs, to provide specific cursor kinds for those.
4265 std::vector<SourceLocation> Locations;
4266 do {
4267 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004268 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004269 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004270
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004271 using namespace cxcursor;
4272 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004273 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4274 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004275 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004276 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4277 Annotated[Locations[I].getRawEncoding()] = Cursor;
4278 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004280 if (Tok.isAtStartOfLine())
4281 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004282
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004283 continue;
4284 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285
Douglas Gregor48072312010-03-18 15:23:44 +00004286 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004287 break;
4288 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004289 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004290
Douglas Gregor0396f462010-03-19 05:22:59 +00004291 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004292 // a specific cursor.
4293 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004294 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004295
4296 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004297 // FIXME: We use a ridiculous stack size here because the data-recursion
4298 // algorithm uses a large stack frame than the non-data recursive version,
4299 // and AnnotationTokensWorker currently transforms the data-recursion
4300 // algorithm back into a traditional recursion by explicitly calling
4301 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004302 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004303 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4304 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004305 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4306 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004307}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004308} // end: extern "C"
4309
4310//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004311// Operations for querying linkage of a cursor.
4312//===----------------------------------------------------------------------===//
4313
4314extern "C" {
4315CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004316 if (!clang_isDeclaration(cursor.kind))
4317 return CXLinkage_Invalid;
4318
Ted Kremenek16b42592010-03-03 06:36:57 +00004319 Decl *D = cxcursor::getCursorDecl(cursor);
4320 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4321 switch (ND->getLinkage()) {
4322 case NoLinkage: return CXLinkage_NoLinkage;
4323 case InternalLinkage: return CXLinkage_Internal;
4324 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4325 case ExternalLinkage: return CXLinkage_External;
4326 };
4327
4328 return CXLinkage_Invalid;
4329}
4330} // end: extern "C"
4331
4332//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004333// Operations for querying language of a cursor.
4334//===----------------------------------------------------------------------===//
4335
4336static CXLanguageKind getDeclLanguage(const Decl *D) {
4337 switch (D->getKind()) {
4338 default:
4339 break;
4340 case Decl::ImplicitParam:
4341 case Decl::ObjCAtDefsField:
4342 case Decl::ObjCCategory:
4343 case Decl::ObjCCategoryImpl:
4344 case Decl::ObjCClass:
4345 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004346 case Decl::ObjCForwardProtocol:
4347 case Decl::ObjCImplementation:
4348 case Decl::ObjCInterface:
4349 case Decl::ObjCIvar:
4350 case Decl::ObjCMethod:
4351 case Decl::ObjCProperty:
4352 case Decl::ObjCPropertyImpl:
4353 case Decl::ObjCProtocol:
4354 return CXLanguage_ObjC;
4355 case Decl::CXXConstructor:
4356 case Decl::CXXConversion:
4357 case Decl::CXXDestructor:
4358 case Decl::CXXMethod:
4359 case Decl::CXXRecord:
4360 case Decl::ClassTemplate:
4361 case Decl::ClassTemplatePartialSpecialization:
4362 case Decl::ClassTemplateSpecialization:
4363 case Decl::Friend:
4364 case Decl::FriendTemplate:
4365 case Decl::FunctionTemplate:
4366 case Decl::LinkageSpec:
4367 case Decl::Namespace:
4368 case Decl::NamespaceAlias:
4369 case Decl::NonTypeTemplateParm:
4370 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004371 case Decl::TemplateTemplateParm:
4372 case Decl::TemplateTypeParm:
4373 case Decl::UnresolvedUsingTypename:
4374 case Decl::UnresolvedUsingValue:
4375 case Decl::Using:
4376 case Decl::UsingDirective:
4377 case Decl::UsingShadow:
4378 return CXLanguage_CPlusPlus;
4379 }
4380
4381 return CXLanguage_C;
4382}
4383
4384extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004385
4386enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4387 if (clang_isDeclaration(cursor.kind))
4388 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4389 if (D->hasAttr<UnavailableAttr>() ||
4390 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4391 return CXAvailability_Available;
4392
4393 if (D->hasAttr<DeprecatedAttr>())
4394 return CXAvailability_Deprecated;
4395 }
4396
4397 return CXAvailability_Available;
4398}
4399
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004400CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4401 if (clang_isDeclaration(cursor.kind))
4402 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4403
4404 return CXLanguage_Invalid;
4405}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004406
4407CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4408 if (clang_isDeclaration(cursor.kind)) {
4409 if (Decl *D = getCursorDecl(cursor)) {
4410 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004411 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004412 }
4413 }
4414
4415 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4416 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004417 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004418 }
4419
4420 return clang_getNullCursor();
4421}
4422
4423CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4424 if (clang_isDeclaration(cursor.kind)) {
4425 if (Decl *D = getCursorDecl(cursor)) {
4426 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004427 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004428 }
4429 }
4430
4431 // FIXME: Note that we can't easily compute the lexical context of a
4432 // statement or expression, so we return nothing.
4433 return clang_getNullCursor();
4434}
4435
Douglas Gregor9f592342010-10-01 20:25:15 +00004436static void CollectOverriddenMethods(DeclContext *Ctx,
4437 ObjCMethodDecl *Method,
4438 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4439 if (!Ctx)
4440 return;
4441
4442 // If we have a class or category implementation, jump straight to the
4443 // interface.
4444 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4445 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4446
4447 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4448 if (!Container)
4449 return;
4450
4451 // Check whether we have a matching method at this level.
4452 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4453 Method->isInstanceMethod()))
4454 if (Method != Overridden) {
4455 // We found an override at this level; there is no need to look
4456 // into other protocols or categories.
4457 Methods.push_back(Overridden);
4458 return;
4459 }
4460
4461 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4462 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4463 PEnd = Protocol->protocol_end();
4464 P != PEnd; ++P)
4465 CollectOverriddenMethods(*P, Method, Methods);
4466 }
4467
4468 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4469 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4470 PEnd = Category->protocol_end();
4471 P != PEnd; ++P)
4472 CollectOverriddenMethods(*P, Method, Methods);
4473 }
4474
4475 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4476 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4477 PEnd = Interface->protocol_end();
4478 P != PEnd; ++P)
4479 CollectOverriddenMethods(*P, Method, Methods);
4480
4481 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4482 Category; Category = Category->getNextClassCategory())
4483 CollectOverriddenMethods(Category, Method, Methods);
4484
4485 // We only look into the superclass if we haven't found anything yet.
4486 if (Methods.empty())
4487 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4488 return CollectOverriddenMethods(Super, Method, Methods);
4489 }
4490}
4491
4492void clang_getOverriddenCursors(CXCursor cursor,
4493 CXCursor **overridden,
4494 unsigned *num_overridden) {
4495 if (overridden)
4496 *overridden = 0;
4497 if (num_overridden)
4498 *num_overridden = 0;
4499 if (!overridden || !num_overridden)
4500 return;
4501
4502 if (!clang_isDeclaration(cursor.kind))
4503 return;
4504
4505 Decl *D = getCursorDecl(cursor);
4506 if (!D)
4507 return;
4508
4509 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004510 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004511 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4512 *num_overridden = CXXMethod->size_overridden_methods();
4513 if (!*num_overridden)
4514 return;
4515
4516 *overridden = new CXCursor [*num_overridden];
4517 unsigned I = 0;
4518 for (CXXMethodDecl::method_iterator
4519 M = CXXMethod->begin_overridden_methods(),
4520 MEnd = CXXMethod->end_overridden_methods();
4521 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004522 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004523 return;
4524 }
4525
4526 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4527 if (!Method)
4528 return;
4529
4530 // Handle Objective-C methods.
4531 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4532 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4533
4534 if (Methods.empty())
4535 return;
4536
4537 *num_overridden = Methods.size();
4538 *overridden = new CXCursor [Methods.size()];
4539 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004540 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004541}
4542
4543void clang_disposeOverriddenCursors(CXCursor *overridden) {
4544 delete [] overridden;
4545}
4546
Douglas Gregorecdcb882010-10-20 22:00:55 +00004547CXFile clang_getIncludedFile(CXCursor cursor) {
4548 if (cursor.kind != CXCursor_InclusionDirective)
4549 return 0;
4550
4551 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4552 return (void *)ID->getFile();
4553}
4554
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004555} // end: extern "C"
4556
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004557
4558//===----------------------------------------------------------------------===//
4559// C++ AST instrospection.
4560//===----------------------------------------------------------------------===//
4561
4562extern "C" {
4563unsigned clang_CXXMethod_isStatic(CXCursor C) {
4564 if (!clang_isDeclaration(C.kind))
4565 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004566
4567 CXXMethodDecl *Method = 0;
4568 Decl *D = cxcursor::getCursorDecl(C);
4569 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4570 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4571 else
4572 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4573 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004574}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004575
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004576} // end: extern "C"
4577
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004578//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004579// Attribute introspection.
4580//===----------------------------------------------------------------------===//
4581
4582extern "C" {
4583CXType clang_getIBOutletCollectionType(CXCursor C) {
4584 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004585 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004586
4587 IBOutletCollectionAttr *A =
4588 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4589
Ted Kremeneka60ed472010-11-16 08:15:36 +00004590 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004591}
4592} // end: extern "C"
4593
4594//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004595// Misc. utility functions.
4596//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004597
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004598/// Default to using an 8 MB stack size on "safety" threads.
4599static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004600
4601namespace clang {
4602
4603bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004604 void (*Fn)(void*), void *UserData,
4605 unsigned Size) {
4606 if (!Size)
4607 Size = GetSafetyThreadStackSize();
4608 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004609 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4610 return CRC.RunSafely(Fn, UserData);
4611}
4612
4613unsigned GetSafetyThreadStackSize() {
4614 return SafetyStackThreadSize;
4615}
4616
4617void SetSafetyThreadStackSize(unsigned Value) {
4618 SafetyStackThreadSize = Value;
4619}
4620
4621}
4622
Ted Kremenek04bb7162010-01-22 22:44:15 +00004623extern "C" {
4624
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004625CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004626 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004627}
4628
4629} // end: extern "C"