blob: acf6b740f9a11e62e187f62ee56e4ba2b043de23 [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 Gregor94802292010-09-02 21:20:16 +0000344 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000345 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000346 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000347 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000348 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000349 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000350 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremeneka6b70432010-11-12 21:34:09 +0000351
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000352 // Data-recursive visitor functions.
353 bool IsInRegionOfInterest(CXCursor C);
354 bool RunVisitorWorkList(VisitorWorkList &WL);
355 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Benjamin Kramere645c722010-11-16 15:45:46 +0000356 LLVM_ATTRIBUTE_NOINLINE bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000357};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000358
Ted Kremenekab188932010-01-05 19:32:54 +0000359} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000360
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000361static SourceRange getRawCursorExtent(CXCursor C);
362
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000363RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000364 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000365}
366
Douglas Gregorb1373d02010-01-20 20:59:29 +0000367/// \brief Visit the given cursor and, if requested by the visitor,
368/// its children.
369///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000370/// \param Cursor the cursor to visit.
371///
372/// \param CheckRegionOfInterest if true, then the caller already checked that
373/// this cursor is within the region of interest.
374///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375/// \returns true if the visitation should be aborted, false if it
376/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000377bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378 if (clang_isInvalid(Cursor.kind))
379 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000380
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381 if (clang_isDeclaration(Cursor.kind)) {
382 Decl *D = getCursorDecl(Cursor);
383 assert(D && "Invalid declaration cursor");
384 if (D->getPCHLevel() > MaxPCHLevel)
385 return false;
386
387 if (D->isImplicit())
388 return false;
389 }
390
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391 // If we have a range of interest, and this cursor doesn't intersect with it,
392 // we're done.
393 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000394 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000395 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000396 return false;
397 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000398
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399 switch (Visitor(Cursor, Parent, ClientData)) {
400 case CXChildVisit_Break:
401 return true;
402
403 case CXChildVisit_Continue:
404 return false;
405
406 case CXChildVisit_Recurse:
407 return VisitChildren(Cursor);
408 }
409
Douglas Gregorfd643772010-01-25 16:45:46 +0000410 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000411}
412
Douglas Gregor788f5a12010-03-20 00:41:21 +0000413std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
414CursorVisitor::getPreprocessedEntities() {
415 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000416 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000417
418 bool OnlyLocalDecls
Ted Kremeneka60ed472010-11-16 08:15:36 +0000419 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000420
421 // There is no region of interest; we have to walk everything.
422 if (RegionOfInterest.isInvalid())
423 return std::make_pair(PPRec.begin(OnlyLocalDecls),
424 PPRec.end(OnlyLocalDecls));
425
426 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000427 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000428 std::pair<FileID, unsigned> Begin
429 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
430 std::pair<FileID, unsigned> End
431 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
432
433 // The region of interest spans files; we have to walk everything.
434 if (Begin.first != End.first)
435 return std::make_pair(PPRec.begin(OnlyLocalDecls),
436 PPRec.end(OnlyLocalDecls));
437
438 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000439 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000440 if (ByFileMap.empty()) {
441 // Build the mapping from files to sets of preprocessed entities.
442 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
443 EEnd = PPRec.end(OnlyLocalDecls);
444 E != EEnd; ++E) {
445 std::pair<FileID, unsigned> P
446 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
447 ByFileMap[P.first].push_back(*E);
448 }
449 }
450
451 return std::make_pair(ByFileMap[Begin.first].begin(),
452 ByFileMap[Begin.first].end());
453}
454
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000456///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457/// \returns true if the visitation should be aborted, false if it
458/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000459bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000460 if (clang_isReference(Cursor.kind)) {
461 // By definition, references have no children.
462 return false;
463 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464
465 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000467 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469 if (clang_isDeclaration(Cursor.kind)) {
470 Decl *D = getCursorDecl(Cursor);
471 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000472 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000474
Douglas Gregora59e3902010-01-21 23:27:09 +0000475 if (clang_isStatement(Cursor.kind))
476 return Visit(getCursorStmt(Cursor));
477 if (clang_isExpression(Cursor.kind))
478 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000481 CXTranslationUnit tu = getCursorTU(Cursor);
482 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000483 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
484 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000485 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
486 TLEnd = CXXUnit->top_level_end();
487 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000488 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000489 return true;
490 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 } else if (VisitDeclContext(
492 CXXUnit->getASTContext().getTranslationUnitDecl()))
493 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000494
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000496 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 // FIXME: Once we have the ability to deserialize a preprocessing record,
498 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000499 PreprocessingRecord::iterator E, EEnd;
500 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000502 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000504
Douglas Gregor0396f462010-03-19 05:22:59 +0000505 continue;
506 }
507
508 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000509 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 return true;
511
512 continue;
513 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000514
515 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000516 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000517 return true;
518
519 continue;
520 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 }
522 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000523 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000525
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 return false;
528}
529
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000531 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
532 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533
Ted Kremenek664cffd2010-07-22 11:30:19 +0000534 if (Stmt *Body = B->getBody())
535 return Visit(MakeCXCursor(Body, StmtParent, TU));
536
537 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000538}
539
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000540llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
541 if (RegionOfInterest.isValid()) {
542 SourceRange Range = getRawCursorExtent(Cursor);
543 if (Range.isInvalid())
544 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000545
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000546 switch (CompareRegionOfInterest(Range)) {
547 case RangeBefore:
548 // This declaration comes before the region of interest; skip it.
549 return llvm::Optional<bool>();
550
551 case RangeAfter:
552 // This declaration comes after the region of interest; we're done.
553 return false;
554
555 case RangeOverlap:
556 // This declaration overlaps the region of interest; visit it.
557 break;
558 }
559 }
560 return true;
561}
562
563bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
564 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
565
566 // FIXME: Eventually remove. This part of a hack to support proper
567 // iteration over all Decls contained lexically within an ObjC container.
568 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
569 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
570
571 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000572 Decl *D = *I;
573 if (D->getLexicalDeclContext() != DC)
574 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000575 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000576 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
577 if (!V.hasValue())
578 continue;
579 if (!V.getValue())
580 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000581 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582 return true;
583 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000585}
586
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000587bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
588 llvm_unreachable("Translation units are visited directly by Visit()");
589 return false;
590}
591
592bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
593 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
594 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000596 return false;
597}
598
599bool CursorVisitor::VisitTagDecl(TagDecl *D) {
600 return VisitDeclContext(D);
601}
602
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000603bool CursorVisitor::VisitClassTemplateSpecializationDecl(
604 ClassTemplateSpecializationDecl *D) {
605 bool ShouldVisitBody = false;
606 switch (D->getSpecializationKind()) {
607 case TSK_Undeclared:
608 case TSK_ImplicitInstantiation:
609 // Nothing to visit
610 return false;
611
612 case TSK_ExplicitInstantiationDeclaration:
613 case TSK_ExplicitInstantiationDefinition:
614 break;
615
616 case TSK_ExplicitSpecialization:
617 ShouldVisitBody = true;
618 break;
619 }
620
621 // Visit the template arguments used in the specialization.
622 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
623 TypeLoc TL = SpecType->getTypeLoc();
624 if (TemplateSpecializationTypeLoc *TSTLoc
625 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
626 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
627 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
628 return true;
629 }
630 }
631
632 if (ShouldVisitBody && VisitCXXRecordDecl(D))
633 return true;
634
635 return false;
636}
637
Douglas Gregor74dbe642010-08-31 19:31:58 +0000638bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
639 ClassTemplatePartialSpecializationDecl *D) {
640 // FIXME: Visit the "outer" template parameter lists on the TagDecl
641 // before visiting these template parameters.
642 if (VisitTemplateParameters(D->getTemplateParameters()))
643 return true;
644
645 // Visit the partial specialization arguments.
646 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
647 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
648 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
649 return true;
650
651 return VisitCXXRecordDecl(D);
652}
653
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000654bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000655 // Visit the default argument.
656 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
657 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
658 if (Visit(DefArg->getTypeLoc()))
659 return true;
660
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000661 return false;
662}
663
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000664bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
665 if (Expr *Init = D->getInitExpr())
666 return Visit(MakeCXCursor(Init, StmtParent, TU));
667 return false;
668}
669
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000670bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
671 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
672 if (Visit(TSInfo->getTypeLoc()))
673 return true;
674
675 return false;
676}
677
Douglas Gregora67e03f2010-09-09 21:42:20 +0000678/// \brief Compare two base or member initializers based on their source order.
679static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
680 CXXBaseOrMemberInitializer const * const *X
681 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
682 CXXBaseOrMemberInitializer const * const *Y
683 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
684
685 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
686 return -1;
687 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
688 return 1;
689 else
690 return 0;
691}
692
Douglas Gregorb1373d02010-01-20 20:59:29 +0000693bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000694 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
695 // Visit the function declaration's syntactic components in the order
696 // written. This requires a bit of work.
697 TypeLoc TL = TSInfo->getTypeLoc();
698 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
699
700 // If we have a function declared directly (without the use of a typedef),
701 // visit just the return type. Otherwise, just visit the function's type
702 // now.
703 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
704 (!FTL && Visit(TL)))
705 return true;
706
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000707 // Visit the nested-name-specifier, if present.
708 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
709 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
710 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000711
712 // Visit the declaration name.
713 if (VisitDeclarationNameInfo(ND->getNameInfo()))
714 return true;
715
716 // FIXME: Visit explicitly-specified template arguments!
717
718 // Visit the function parameters, if we have a function type.
719 if (FTL && VisitFunctionTypeLoc(*FTL, true))
720 return true;
721
722 // FIXME: Attributes?
723 }
724
Douglas Gregora67e03f2010-09-09 21:42:20 +0000725 if (ND->isThisDeclarationADefinition()) {
726 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
727 // Find the initializers that were written in the source.
728 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
729 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
730 IEnd = Constructor->init_end();
731 I != IEnd; ++I) {
732 if (!(*I)->isWritten())
733 continue;
734
735 WrittenInits.push_back(*I);
736 }
737
738 // Sort the initializers in source order
739 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
740 &CompareCXXBaseOrMemberInitializers);
741
742 // Visit the initializers in source order
743 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
744 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
745 if (Init->isMemberInitializer()) {
746 if (Visit(MakeCursorMemberRef(Init->getMember(),
747 Init->getMemberLocation(), TU)))
748 return true;
749 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
750 if (Visit(BaseInfo->getTypeLoc()))
751 return true;
752 }
753
754 // Visit the initializer value.
755 if (Expr *Initializer = Init->getInit())
756 if (Visit(MakeCXCursor(Initializer, ND, TU)))
757 return true;
758 }
759 }
760
761 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
762 return true;
763 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000764
Douglas Gregorb1373d02010-01-20 20:59:29 +0000765 return false;
766}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000767
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000768bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
769 if (VisitDeclaratorDecl(D))
770 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772 if (Expr *BitWidth = D->getBitWidth())
773 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000774
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000775 return false;
776}
777
778bool CursorVisitor::VisitVarDecl(VarDecl *D) {
779 if (VisitDeclaratorDecl(D))
780 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000781
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000782 if (Expr *Init = D->getInit())
783 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785 return false;
786}
787
Douglas Gregor84b51d72010-09-01 20:16:53 +0000788bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
789 if (VisitDeclaratorDecl(D))
790 return true;
791
792 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
793 if (Expr *DefArg = D->getDefaultArgument())
794 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
795
796 return false;
797}
798
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000799bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
800 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
801 // before visiting these template parameters.
802 if (VisitTemplateParameters(D->getTemplateParameters()))
803 return true;
804
805 return VisitFunctionDecl(D->getTemplatedDecl());
806}
807
Douglas Gregor39d6f072010-08-31 19:02:00 +0000808bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
809 // FIXME: Visit the "outer" template parameter lists on the TagDecl
810 // before visiting these template parameters.
811 if (VisitTemplateParameters(D->getTemplateParameters()))
812 return true;
813
814 return VisitCXXRecordDecl(D->getTemplatedDecl());
815}
816
Douglas Gregor84b51d72010-09-01 20:16:53 +0000817bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
818 if (VisitTemplateParameters(D->getTemplateParameters()))
819 return true;
820
821 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
822 VisitTemplateArgumentLoc(D->getDefaultArgument()))
823 return true;
824
825 return false;
826}
827
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000828bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000829 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
830 if (Visit(TSInfo->getTypeLoc()))
831 return true;
832
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000834 PEnd = ND->param_end();
835 P != PEnd; ++P) {
836 if (Visit(MakeCXCursor(*P, TU)))
837 return true;
838 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 if (ND->isThisDeclarationADefinition() &&
841 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
842 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000843
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000844 return false;
845}
846
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000847namespace {
848 struct ContainerDeclsSort {
849 SourceManager &SM;
850 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
851 bool operator()(Decl *A, Decl *B) {
852 SourceLocation L_A = A->getLocStart();
853 SourceLocation L_B = B->getLocStart();
854 assert(L_A.isValid() && L_B.isValid());
855 return SM.isBeforeInTranslationUnit(L_A, L_B);
856 }
857 };
858}
859
Douglas Gregora59e3902010-01-21 23:27:09 +0000860bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000861 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
862 // an @implementation can lexically contain Decls that are not properly
863 // nested in the AST. When we identify such cases, we need to retrofit
864 // this nesting here.
865 if (!DI_current)
866 return VisitDeclContext(D);
867
868 // Scan the Decls that immediately come after the container
869 // in the current DeclContext. If any fall within the
870 // container's lexical region, stash them into a vector
871 // for later processing.
872 llvm::SmallVector<Decl *, 24> DeclsInContainer;
873 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000874 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000875 if (EndLoc.isValid()) {
876 DeclContext::decl_iterator next = *DI_current;
877 while (++next != DE_current) {
878 Decl *D_next = *next;
879 if (!D_next)
880 break;
881 SourceLocation L = D_next->getLocStart();
882 if (!L.isValid())
883 break;
884 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
885 *DI_current = next;
886 DeclsInContainer.push_back(D_next);
887 continue;
888 }
889 break;
890 }
891 }
892
893 // The common case.
894 if (DeclsInContainer.empty())
895 return VisitDeclContext(D);
896
897 // Get all the Decls in the DeclContext, and sort them with the
898 // additional ones we've collected. Then visit them.
899 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
900 I!=E; ++I) {
901 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000902 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
903 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000904 continue;
905 DeclsInContainer.push_back(subDecl);
906 }
907
908 // Now sort the Decls so that they appear in lexical order.
909 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
910 ContainerDeclsSort(SM));
911
912 // Now visit the decls.
913 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
914 E = DeclsInContainer.end(); I != E; ++I) {
915 CXCursor Cursor = MakeCXCursor(*I, TU);
916 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
917 if (!V.hasValue())
918 continue;
919 if (!V.getValue())
920 return false;
921 if (Visit(Cursor, true))
922 return true;
923 }
924 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000925}
926
Douglas Gregorb1373d02010-01-20 20:59:29 +0000927bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000928 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
929 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000930 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000931
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000932 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
933 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
934 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000935 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000936 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000937
Douglas Gregora59e3902010-01-21 23:27:09 +0000938 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000939}
940
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000941bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
942 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
943 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
944 E = PID->protocol_end(); I != E; ++I, ++PL)
945 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
946 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000947
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000948 return VisitObjCContainerDecl(PID);
949}
950
Ted Kremenek23173d72010-05-18 21:09:07 +0000951bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000952 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000953 return true;
954
Ted Kremenek23173d72010-05-18 21:09:07 +0000955 // FIXME: This implements a workaround with @property declarations also being
956 // installed in the DeclContext for the @interface. Eventually this code
957 // should be removed.
958 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
959 if (!CDecl || !CDecl->IsClassExtension())
960 return false;
961
962 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
963 if (!ID)
964 return false;
965
966 IdentifierInfo *PropertyId = PD->getIdentifier();
967 ObjCPropertyDecl *prevDecl =
968 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
969
970 if (!prevDecl)
971 return false;
972
973 // Visit synthesized methods since they will be skipped when visiting
974 // the @interface.
975 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000976 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000977 if (Visit(MakeCXCursor(MD, TU)))
978 return true;
979
980 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000981 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000982 if (Visit(MakeCXCursor(MD, TU)))
983 return true;
984
985 return false;
986}
987
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000989 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000990 if (D->getSuperClass() &&
991 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000992 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000993 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000994 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000996 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
997 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
998 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000999 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001000 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001001
Douglas Gregora59e3902010-01-21 23:27:09 +00001002 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001003}
1004
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001005bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1006 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001007}
1008
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001009bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001010 // 'ID' could be null when dealing with invalid code.
1011 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1012 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001015 return VisitObjCImplDecl(D);
1016}
1017
1018bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1019#if 0
1020 // Issue callbacks for super class.
1021 // FIXME: No source location information!
1022 if (D->getSuperClass() &&
1023 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001025 TU)))
1026 return true;
1027#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029 return VisitObjCImplDecl(D);
1030}
1031
1032bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1033 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1034 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1035 E = D->protocol_end();
1036 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001037 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001038 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039
1040 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001041}
1042
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1044 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1045 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1046 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001048 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001049}
1050
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001051bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1052 return VisitDeclContext(D);
1053}
1054
Douglas Gregor69319002010-08-31 23:48:11 +00001055bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001056 // Visit nested-name-specifier.
1057 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1058 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1059 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001060
1061 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1062 D->getTargetNameLoc(), TU));
1063}
1064
Douglas Gregor7e242562010-09-01 19:52:22 +00001065bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001066 // Visit nested-name-specifier.
1067 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1068 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1069 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001070
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001071 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1072 return true;
1073
Douglas Gregor7e242562010-09-01 19:52:22 +00001074 return VisitDeclarationNameInfo(D->getNameInfo());
1075}
1076
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001077bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001078 // Visit nested-name-specifier.
1079 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1080 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1081 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001082
1083 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1084 D->getIdentLocation(), TU));
1085}
1086
Douglas Gregor7e242562010-09-01 19:52:22 +00001087bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001088 // Visit nested-name-specifier.
1089 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1090 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1091 return true;
1092
Douglas Gregor7e242562010-09-01 19:52:22 +00001093 return VisitDeclarationNameInfo(D->getNameInfo());
1094}
1095
1096bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1097 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001098 // Visit nested-name-specifier.
1099 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1100 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1101 return true;
1102
Douglas Gregor7e242562010-09-01 19:52:22 +00001103 return false;
1104}
1105
Douglas Gregor01829d32010-08-31 14:41:23 +00001106bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1107 switch (Name.getName().getNameKind()) {
1108 case clang::DeclarationName::Identifier:
1109 case clang::DeclarationName::CXXLiteralOperatorName:
1110 case clang::DeclarationName::CXXOperatorName:
1111 case clang::DeclarationName::CXXUsingDirective:
1112 return false;
1113
1114 case clang::DeclarationName::CXXConstructorName:
1115 case clang::DeclarationName::CXXDestructorName:
1116 case clang::DeclarationName::CXXConversionFunctionName:
1117 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1118 return Visit(TSInfo->getTypeLoc());
1119 return false;
1120
1121 case clang::DeclarationName::ObjCZeroArgSelector:
1122 case clang::DeclarationName::ObjCOneArgSelector:
1123 case clang::DeclarationName::ObjCMultiArgSelector:
1124 // FIXME: Per-identifier location info?
1125 return false;
1126 }
1127
1128 return false;
1129}
1130
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001131bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1132 SourceRange Range) {
1133 // FIXME: This whole routine is a hack to work around the lack of proper
1134 // source information in nested-name-specifiers (PR5791). Since we do have
1135 // a beginning source location, we can visit the first component of the
1136 // nested-name-specifier, if it's a single-token component.
1137 if (!NNS)
1138 return false;
1139
1140 // Get the first component in the nested-name-specifier.
1141 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1142 NNS = Prefix;
1143
1144 switch (NNS->getKind()) {
1145 case NestedNameSpecifier::Namespace:
1146 // FIXME: The token at this source location might actually have been a
1147 // namespace alias, but we don't model that. Lame!
1148 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1149 TU));
1150
1151 case NestedNameSpecifier::TypeSpec: {
1152 // If the type has a form where we know that the beginning of the source
1153 // range matches up with a reference cursor. Visit the appropriate reference
1154 // cursor.
1155 Type *T = NNS->getAsType();
1156 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1157 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1158 if (const TagType *Tag = dyn_cast<TagType>(T))
1159 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1160 if (const TemplateSpecializationType *TST
1161 = dyn_cast<TemplateSpecializationType>(T))
1162 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1163 break;
1164 }
1165
1166 case NestedNameSpecifier::TypeSpecWithTemplate:
1167 case NestedNameSpecifier::Global:
1168 case NestedNameSpecifier::Identifier:
1169 break;
1170 }
1171
1172 return false;
1173}
1174
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001175bool CursorVisitor::VisitTemplateParameters(
1176 const TemplateParameterList *Params) {
1177 if (!Params)
1178 return false;
1179
1180 for (TemplateParameterList::const_iterator P = Params->begin(),
1181 PEnd = Params->end();
1182 P != PEnd; ++P) {
1183 if (Visit(MakeCXCursor(*P, TU)))
1184 return true;
1185 }
1186
1187 return false;
1188}
1189
Douglas Gregor0b36e612010-08-31 20:37:03 +00001190bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1191 switch (Name.getKind()) {
1192 case TemplateName::Template:
1193 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1194
1195 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001196 // Visit the overloaded template set.
1197 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1198 return true;
1199
Douglas Gregor0b36e612010-08-31 20:37:03 +00001200 return false;
1201
1202 case TemplateName::DependentTemplate:
1203 // FIXME: Visit nested-name-specifier.
1204 return false;
1205
1206 case TemplateName::QualifiedTemplate:
1207 // FIXME: Visit nested-name-specifier.
1208 return Visit(MakeCursorTemplateRef(
1209 Name.getAsQualifiedTemplateName()->getDecl(),
1210 Loc, TU));
1211 }
1212
1213 return false;
1214}
1215
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001216bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1217 switch (TAL.getArgument().getKind()) {
1218 case TemplateArgument::Null:
1219 case TemplateArgument::Integral:
1220 return false;
1221
1222 case TemplateArgument::Pack:
1223 // FIXME: Implement when variadic templates come along.
1224 return false;
1225
1226 case TemplateArgument::Type:
1227 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1228 return Visit(TSInfo->getTypeLoc());
1229 return false;
1230
1231 case TemplateArgument::Declaration:
1232 if (Expr *E = TAL.getSourceDeclExpression())
1233 return Visit(MakeCXCursor(E, StmtParent, TU));
1234 return false;
1235
1236 case TemplateArgument::Expression:
1237 if (Expr *E = TAL.getSourceExpression())
1238 return Visit(MakeCXCursor(E, StmtParent, TU));
1239 return false;
1240
1241 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001242 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1243 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001244 }
1245
1246 return false;
1247}
1248
Ted Kremeneka0536d82010-05-07 01:04:29 +00001249bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1250 return VisitDeclContext(D);
1251}
1252
Douglas Gregor01829d32010-08-31 14:41:23 +00001253bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1254 return Visit(TL.getUnqualifiedLoc());
1255}
1256
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001257bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001258 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001259
1260 // Some builtin types (such as Objective-C's "id", "sel", and
1261 // "Class") have associated declarations. Create cursors for those.
1262 QualType VisitType;
1263 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001264 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001265 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001266 case BuiltinType::Char_U:
1267 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001268 case BuiltinType::Char16:
1269 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001270 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001271 case BuiltinType::UInt:
1272 case BuiltinType::ULong:
1273 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001274 case BuiltinType::UInt128:
1275 case BuiltinType::Char_S:
1276 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001277 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001278 case BuiltinType::Short:
1279 case BuiltinType::Int:
1280 case BuiltinType::Long:
1281 case BuiltinType::LongLong:
1282 case BuiltinType::Int128:
1283 case BuiltinType::Float:
1284 case BuiltinType::Double:
1285 case BuiltinType::LongDouble:
1286 case BuiltinType::NullPtr:
1287 case BuiltinType::Overload:
1288 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001289 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001290
1291 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001292 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001293
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001294 case BuiltinType::ObjCId:
1295 VisitType = Context.getObjCIdType();
1296 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001297
1298 case BuiltinType::ObjCClass:
1299 VisitType = Context.getObjCClassType();
1300 break;
1301
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001302 case BuiltinType::ObjCSel:
1303 VisitType = Context.getObjCSelType();
1304 break;
1305 }
1306
1307 if (!VisitType.isNull()) {
1308 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001309 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001310 TU));
1311 }
1312
1313 return false;
1314}
1315
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001316bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1317 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1318}
1319
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001320bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1321 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1322}
1323
1324bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1325 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1326}
1327
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001328bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001329 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001330 // no context information with which we can match up the depth/index in the
1331 // type to the appropriate
1332 return false;
1333}
1334
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1336 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1337 return true;
1338
John McCallc12c5bb2010-05-15 11:32:37 +00001339 return false;
1340}
1341
1342bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1343 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1344 return true;
1345
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001346 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1347 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1348 TU)))
1349 return true;
1350 }
1351
1352 return false;
1353}
1354
1355bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001356 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001357}
1358
1359bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1360 return Visit(TL.getPointeeLoc());
1361}
1362
1363bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1364 return Visit(TL.getPointeeLoc());
1365}
1366
1367bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1368 return Visit(TL.getPointeeLoc());
1369}
1370
1371bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001372 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001373}
1374
1375bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001376 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001377}
1378
Douglas Gregor01829d32010-08-31 14:41:23 +00001379bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1380 bool SkipResultType) {
1381 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001382 return true;
1383
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001385 if (Decl *D = TL.getArg(I))
1386 if (Visit(MakeCXCursor(D, TU)))
1387 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388
1389 return false;
1390}
1391
1392bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1393 if (Visit(TL.getElementLoc()))
1394 return true;
1395
1396 if (Expr *Size = TL.getSizeExpr())
1397 return Visit(MakeCXCursor(Size, StmtParent, TU));
1398
1399 return false;
1400}
1401
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001402bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1403 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001404 // Visit the template name.
1405 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1406 TL.getTemplateNameLoc()))
1407 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001408
1409 // Visit the template arguments.
1410 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1411 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1412 return true;
1413
1414 return false;
1415}
1416
Douglas Gregor2332c112010-01-21 20:48:56 +00001417bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1418 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1419}
1420
1421bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1422 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1423 return Visit(TSInfo->getTypeLoc());
1424
1425 return false;
1426}
1427
Douglas Gregora59e3902010-01-21 23:27:09 +00001428bool CursorVisitor::VisitStmt(Stmt *S) {
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001429 return VisitDataRecursive(S);
Douglas Gregora59e3902010-01-21 23:27:09 +00001430}
1431
Ted Kremenek3064ef92010-08-27 21:34:58 +00001432bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1433 if (D->isDefinition()) {
1434 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1435 E = D->bases_end(); I != E; ++I) {
1436 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1437 return true;
1438 }
1439 }
1440
1441 return VisitTagDecl(D);
1442}
1443
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001444bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001445 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001446 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1447 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001448
1449 // Visit the components of the offsetof expression.
1450 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1451 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1452 const OffsetOfNode &Node = E->getComponent(I);
1453 switch (Node.getKind()) {
1454 case OffsetOfNode::Array:
1455 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1456 StmtParent, TU)))
1457 return true;
1458 break;
1459
1460 case OffsetOfNode::Field:
1461 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1462 TU)))
1463 return true;
1464 break;
1465
1466 case OffsetOfNode::Identifier:
1467 case OffsetOfNode::Base:
1468 continue;
1469 }
1470 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001471
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001472 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001473}
1474
Douglas Gregor336fd812010-01-23 00:40:08 +00001475bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1476 if (E->isArgumentType()) {
1477 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1478 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001479
Douglas Gregor336fd812010-01-23 00:40:08 +00001480 return false;
1481 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001482
Douglas Gregor336fd812010-01-23 00:40:08 +00001483 return VisitExpr(E);
1484}
1485
Douglas Gregor36897b02010-09-10 00:22:18 +00001486bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1487 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1488}
1489
Douglas Gregor648220e2010-08-10 15:02:34 +00001490bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1491 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1492 return true;
1493
1494 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1495}
1496
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001497bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1498 // Visit the designators.
1499 typedef DesignatedInitExpr::Designator Designator;
1500 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1501 DEnd = E->designators_end();
1502 D != DEnd; ++D) {
1503 if (D->isFieldDesignator()) {
1504 if (FieldDecl *Field = D->getField())
1505 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1506 return true;
1507
1508 continue;
1509 }
1510
1511 if (D->isArrayDesignator()) {
1512 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1513 return true;
1514
1515 continue;
1516 }
1517
1518 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1519 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1520 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1521 return true;
1522 }
1523
1524 // Visit the initializer value itself.
1525 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1526}
1527
Douglas Gregor94802292010-09-02 21:20:16 +00001528bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1529 if (E->isTypeOperand()) {
1530 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1531 return Visit(TSInfo->getTypeLoc());
1532
1533 return false;
1534 }
1535
1536 return VisitExpr(E);
1537}
1538
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001539bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1540 if (E->isTypeOperand()) {
1541 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1542 return Visit(TSInfo->getTypeLoc());
1543
1544 return false;
1545 }
1546
1547 return VisitExpr(E);
1548}
1549
Douglas Gregorab6677e2010-09-08 00:15:04 +00001550bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1551 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1552 return Visit(TSInfo->getTypeLoc());
1553
1554 return false;
1555}
1556
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001557bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1558 // Visit base expression.
1559 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1560 return true;
1561
1562 // Visit the nested-name-specifier.
1563 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1564 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1565 return true;
1566
1567 // Visit the scope type that looks disturbingly like the nested-name-specifier
1568 // but isn't.
1569 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1570 if (Visit(TSInfo->getTypeLoc()))
1571 return true;
1572
1573 // Visit the name of the type being destroyed.
1574 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1575 if (Visit(TSInfo->getTypeLoc()))
1576 return true;
1577
1578 return false;
1579}
1580
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001581bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1582 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1583}
1584
Douglas Gregorbfebed22010-09-03 17:24:10 +00001585bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1586 DependentScopeDeclRefExpr *E) {
1587 // Visit the nested-name-specifier.
1588 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1589 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1590 return true;
1591
1592 // Visit the declaration name.
1593 if (VisitDeclarationNameInfo(E->getNameInfo()))
1594 return true;
1595
1596 // Visit the explicitly-specified template arguments.
1597 if (const ExplicitTemplateArgumentList *ArgList
1598 = E->getOptionalExplicitTemplateArgs()) {
1599 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1600 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1601 Arg != ArgEnd; ++Arg) {
1602 if (VisitTemplateArgumentLoc(*Arg))
1603 return true;
1604 }
1605 }
1606
1607 return false;
1608}
1609
Douglas Gregor25d63622010-09-03 17:35:34 +00001610bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1611 CXXDependentScopeMemberExpr *E) {
1612 // Visit the base expression, if there is one.
1613 if (!E->isImplicitAccess() &&
1614 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1615 return true;
1616
1617 // Visit the nested-name-specifier.
1618 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1619 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1620 return true;
1621
1622 // Visit the declaration name.
1623 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1624 return true;
1625
1626 // Visit the explicitly-specified template arguments.
1627 if (const ExplicitTemplateArgumentList *ArgList
1628 = E->getOptionalExplicitTemplateArgs()) {
1629 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1630 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1631 Arg != ArgEnd; ++Arg) {
1632 if (VisitTemplateArgumentLoc(*Arg))
1633 return true;
1634 }
1635 }
1636
1637 return false;
1638}
1639
Ted Kremenek09dfa372010-02-18 05:46:33 +00001640bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001641 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1642 i != e; ++i)
1643 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001644 return true;
1645
1646 return false;
1647}
1648
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001649//===----------------------------------------------------------------------===//
1650// Data-recursive visitor methods.
1651//===----------------------------------------------------------------------===//
1652
Ted Kremenek28a71942010-11-13 00:36:47 +00001653namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001654#define DEF_JOB(NAME, DATA, KIND)\
1655class NAME : public VisitorJob {\
1656public:\
1657 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1658 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1659 DATA *get() const { return static_cast<DATA*>(dataA); }\
1660};
1661
1662DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1663DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001664DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001665DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1666#undef DEF_JOB
1667
1668class DeclVisit : public VisitorJob {
1669public:
1670 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1671 VisitorJob(parent, VisitorJob::DeclVisitKind,
1672 d, isFirst ? (void*) 1 : (void*) 0) {}
1673 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001674 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001675 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001676 Decl *get() const { return static_cast<Decl*>(dataA); }
Ted Kremenek035dc412010-11-13 00:36:50 +00001677 bool isFirst() const { return dataB ? true : false; }
1678};
1679
1680class TypeLocVisit : public VisitorJob {
1681public:
1682 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1683 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1684 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1685
1686 static bool classof(const VisitorJob *VJ) {
1687 return VJ->getKind() == TypeLocVisitKind;
1688 }
1689
Ted Kremenek82f3c502010-11-15 22:23:26 +00001690 TypeLoc get() const {
Ted Kremenek035dc412010-11-13 00:36:50 +00001691 QualType T = QualType::getFromOpaquePtr(dataA);
1692 return TypeLoc(T, dataB);
1693 }
1694};
1695
Ted Kremenek28a71942010-11-13 00:36:47 +00001696class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1697 VisitorWorkList &WL;
1698 CXCursor Parent;
1699public:
1700 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1701 : WL(wl), Parent(parent) {}
1702
Ted Kremenek73d15c42010-11-13 01:09:29 +00001703 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001705 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001706 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1707 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001708 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001709 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001710 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001711 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001712 void VisitDeclStmt(DeclStmt *S);
Ted Kremenek28a71942010-11-13 00:36:47 +00001713 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1714 void VisitForStmt(ForStmt *FS);
1715 void VisitIfStmt(IfStmt *If);
1716 void VisitInitListExpr(InitListExpr *IE);
1717 void VisitMemberExpr(MemberExpr *M);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001718 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001719 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1720 void VisitOverloadExpr(OverloadExpr *E);
1721 void VisitStmt(Stmt *S);
1722 void VisitSwitchStmt(SwitchStmt *S);
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001723 void VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001724 void VisitWhileStmt(WhileStmt *W);
1725 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1726
1727private:
1728 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001729 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001730 void AddTypeLoc(TypeSourceInfo *TI);
1731 void EnqueueChildren(Stmt *S);
1732};
1733} // end anonyous namespace
1734
1735void EnqueueVisitor::AddStmt(Stmt *S) {
1736 if (S)
1737 WL.push_back(StmtVisit(S, Parent));
1738}
Ted Kremenek035dc412010-11-13 00:36:50 +00001739void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001740 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001741 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001742}
1743void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1744 if (TI)
1745 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1746 }
1747void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001748 unsigned size = WL.size();
1749 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1750 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001752 }
1753 if (size == WL.size())
1754 return;
1755 // Now reverse the entries we just added. This will match the DFS
1756 // ordering performed by the worklist.
1757 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1758 std::reverse(I, E);
1759}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001760void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1761 AddDecl(B->getBlockDecl());
1762}
Ted Kremenek28a71942010-11-13 00:36:47 +00001763void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1764 EnqueueChildren(E);
1765 AddTypeLoc(E->getTypeSourceInfo());
1766}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001767void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1768 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1769 E = S->body_rend(); I != E; ++I) {
1770 AddStmt(*I);
1771 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001772}
1773void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1774 // Enqueue the initializer or constructor arguments.
1775 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1776 AddStmt(E->getConstructorArg(I-1));
1777 // Enqueue the array size, if any.
1778 AddStmt(E->getArraySize());
1779 // Enqueue the allocated type.
1780 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1781 // Enqueue the placement arguments.
1782 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1783 AddStmt(E->getPlacementArg(I-1));
1784}
Ted Kremenek28a71942010-11-13 00:36:47 +00001785void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001786 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1787 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001788 AddStmt(CE->getCallee());
1789 AddStmt(CE->getArg(0));
1790}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001791void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1792 EnqueueChildren(E);
1793 AddTypeLoc(E->getTypeSourceInfo());
1794}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001795
1796void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1797 *E) {
1798 EnqueueChildren(E);
1799 AddTypeLoc(E->getTypeSourceInfo());
1800}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001801void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1802 WL.push_back(DeclRefExprParts(DR, Parent));
1803}
Ted Kremenek035dc412010-11-13 00:36:50 +00001804void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1805 unsigned size = WL.size();
1806 bool isFirst = true;
1807 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1808 D != DEnd; ++D) {
1809 AddDecl(*D, isFirst);
1810 isFirst = false;
1811 }
1812 if (size == WL.size())
1813 return;
1814 // Now reverse the entries we just added. This will match the DFS
1815 // ordering performed by the worklist.
1816 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1817 std::reverse(I, E);
1818}
Ted Kremenek28a71942010-11-13 00:36:47 +00001819void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1820 EnqueueChildren(E);
1821 AddTypeLoc(E->getTypeInfoAsWritten());
1822}
1823void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1824 AddStmt(FS->getBody());
1825 AddStmt(FS->getInc());
1826 AddStmt(FS->getCond());
1827 AddDecl(FS->getConditionVariable());
1828 AddStmt(FS->getInit());
1829}
1830void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1831 AddStmt(If->getElse());
1832 AddStmt(If->getThen());
1833 AddStmt(If->getCond());
1834 AddDecl(If->getConditionVariable());
1835}
1836void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1837 // We care about the syntactic form of the initializer list, only.
1838 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1839 IE = Syntactic;
1840 EnqueueChildren(IE);
1841}
1842void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1843 WL.push_back(MemberExprParts(M, Parent));
1844 AddStmt(M->getBase());
1845}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001846void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1847 AddTypeLoc(E->getEncodedTypeSourceInfo());
1848}
Ted Kremenek28a71942010-11-13 00:36:47 +00001849void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1850 EnqueueChildren(M);
1851 AddTypeLoc(M->getClassReceiverTypeInfo());
1852}
1853void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001854 WL.push_back(OverloadExprParts(E, Parent));
1855}
Ted Kremenek28a71942010-11-13 00:36:47 +00001856void EnqueueVisitor::VisitStmt(Stmt *S) {
1857 EnqueueChildren(S);
1858}
1859void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1860 AddStmt(S->getBody());
1861 AddStmt(S->getCond());
1862 AddDecl(S->getConditionVariable());
1863}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001864void EnqueueVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1865 AddTypeLoc(E->getArgTInfo2());
1866 AddTypeLoc(E->getArgTInfo1());
1867}
1868
Ted Kremenek28a71942010-11-13 00:36:47 +00001869void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1870 AddStmt(W->getBody());
1871 AddStmt(W->getCond());
1872 AddDecl(W->getConditionVariable());
1873}
1874void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1875 VisitOverloadExpr(U);
1876 if (!U->isImplicitAccess())
1877 AddStmt(U->getBase());
1878}
Ted Kremenek60458782010-11-12 21:34:16 +00001879
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001880void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001881 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001882}
1883
1884bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1885 if (RegionOfInterest.isValid()) {
1886 SourceRange Range = getRawCursorExtent(C);
1887 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1888 return false;
1889 }
1890 return true;
1891}
1892
1893bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1894 while (!WL.empty()) {
1895 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001896 VisitorJob LI = WL.back();
1897 WL.pop_back();
1898
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001899 // Set the Parent field, then back to its old value once we're done.
1900 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1901
1902 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001903 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001904 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00001905 if (!D)
1906 continue;
1907
1908 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001909 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00001910 return true;
1911
1912 continue;
1913 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001914 case VisitorJob::TypeLocVisitKind: {
1915 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001916 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001917 return true;
1918 continue;
1919 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001920 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001921 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001922 if (!S)
1923 continue;
1924
Ted Kremenekf1107452010-11-12 18:26:56 +00001925 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001926 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1927
1928 switch (S->getStmtClass()) {
Ted Kremenek1876bf62010-11-13 00:58:15 +00001929 case Stmt::GotoStmtClass: {
1930 GotoStmt *GS = cast<GotoStmt>(S);
1931 if (Visit(MakeCursorLabelRef(GS->getLabel(),
1932 GS->getLabelLoc(), TU))) {
1933 return true;
1934 }
1935 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001936 }
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001937 // Cases not yet handled by the data-recursion
1938 // algorithm.
1939 case Stmt::OffsetOfExprClass:
1940 case Stmt::SizeOfAlignOfExprClass:
1941 case Stmt::AddrLabelExprClass:
1942 case Stmt::TypesCompatibleExprClass:
1943 case Stmt::VAArgExprClass:
1944 case Stmt::DesignatedInitExprClass:
1945 case Stmt::CXXTypeidExprClass:
1946 case Stmt::CXXUuidofExprClass:
1947 case Stmt::CXXScalarValueInitExprClass:
1948 case Stmt::CXXPseudoDestructorExprClass:
1949 case Stmt::UnaryTypeTraitExprClass:
1950 case Stmt::DependentScopeDeclRefExprClass:
1951 case Stmt::CXXUnresolvedConstructExprClass:
1952 case Stmt::CXXDependentScopeMemberExprClass:
1953 if (Visit(Cursor))
1954 return true;
Ted Kremenek82f3c502010-11-15 22:23:26 +00001955 break;
Ted Kremenek2bd1e7c2010-11-14 05:45:47 +00001956 default:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001957 if (!IsInRegionOfInterest(Cursor))
1958 continue;
1959 switch (Visitor(Cursor, Parent, ClientData)) {
1960 case CXChildVisit_Break:
1961 return true;
1962 case CXChildVisit_Continue:
1963 break;
1964 case CXChildVisit_Recurse:
1965 EnqueueWorkList(WL, S);
1966 break;
1967 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001968 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001969 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00001970 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001971 }
1972 case VisitorJob::MemberExprPartsKind: {
1973 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00001974 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001975
1976 // Visit the nested-name-specifier
1977 if (NestedNameSpecifier *Qualifier = M->getQualifier())
1978 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
1979 return true;
1980
1981 // Visit the declaration name.
1982 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
1983 return true;
1984
1985 // Visit the explicitly-specified template arguments, if any.
1986 if (M->hasExplicitTemplateArgs()) {
1987 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
1988 *ArgEnd = Arg + M->getNumTemplateArgs();
1989 Arg != ArgEnd; ++Arg) {
1990 if (VisitTemplateArgumentLoc(*Arg))
1991 return true;
1992 }
1993 }
1994 continue;
1995 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001996 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001997 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001998 // Visit nested-name-specifier, if present.
1999 if (NestedNameSpecifier *Qualifier = DR->getQualifier())
2000 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange()))
2001 return true;
2002 // Visit declaration name.
2003 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2004 return true;
2005 // Visit explicitly-specified template arguments.
2006 if (DR->hasExplicitTemplateArgs()) {
2007 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs();
2008 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
2009 *ArgEnd = Arg + Args.NumTemplateArgs;
2010 Arg != ArgEnd; ++Arg)
2011 if (VisitTemplateArgumentLoc(*Arg))
2012 return true;
2013 }
2014 continue;
2015 }
Ted Kremenek60458782010-11-12 21:34:16 +00002016 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002017 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002018 // Visit the nested-name-specifier.
2019 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2020 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2021 return true;
2022 // Visit the declaration name.
2023 if (VisitDeclarationNameInfo(O->getNameInfo()))
2024 return true;
2025 // Visit the overloaded declaration reference.
2026 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2027 return true;
2028 // Visit the explicitly-specified template arguments.
2029 if (const ExplicitTemplateArgumentList *ArgList
2030 = O->getOptionalExplicitTemplateArgs()) {
2031 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2032 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2033 Arg != ArgEnd; ++Arg) {
2034 if (VisitTemplateArgumentLoc(*Arg))
2035 return true;
2036 }
2037 }
2038 continue;
2039 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002040 }
2041 }
2042 return false;
2043}
2044
2045bool CursorVisitor::VisitDataRecursive(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002046 VisitorWorkList *WL = 0;
2047 if (!WorkListFreeList.empty()) {
2048 WL = WorkListFreeList.back();
2049 WL->clear();
2050 WorkListFreeList.pop_back();
2051 }
2052 else {
2053 WL = new VisitorWorkList();
2054 WorkListCache.push_back(WL);
2055 }
2056 EnqueueWorkList(*WL, S);
2057 bool result = RunVisitorWorkList(*WL);
2058 WorkListFreeList.push_back(WL);
2059 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002060}
2061
2062//===----------------------------------------------------------------------===//
2063// Misc. API hooks.
2064//===----------------------------------------------------------------------===//
2065
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002066static llvm::sys::Mutex EnableMultithreadingMutex;
2067static bool EnabledMultithreading;
2068
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002069extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002070CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2071 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002072 // Disable pretty stack trace functionality, which will otherwise be a very
2073 // poor citizen of the world and set up all sorts of signal handlers.
2074 llvm::DisablePrettyStackTrace = true;
2075
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002076 // We use crash recovery to make some of our APIs more reliable, implicitly
2077 // enable it.
2078 llvm::CrashRecoveryContext::Enable();
2079
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002080 // Enable support for multithreading in LLVM.
2081 {
2082 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2083 if (!EnabledMultithreading) {
2084 llvm::llvm_start_multithreaded();
2085 EnabledMultithreading = true;
2086 }
2087 }
2088
Douglas Gregora030b7c2010-01-22 20:35:53 +00002089 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002090 if (excludeDeclarationsFromPCH)
2091 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002092 if (displayDiagnostics)
2093 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002094 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002095}
2096
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002097void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002098 if (CIdx)
2099 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002100}
2101
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002102CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002103 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002104 if (!CIdx)
2105 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002106
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002107 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002108 FileSystemOptions FileSystemOpts;
2109 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002110
Douglas Gregor28019772010-04-05 23:52:57 +00002111 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002112 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002113 CXXIdx->getOnlyLocalDecls(),
2114 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002115 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002116}
2117
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002118unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002119 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002120 CXTranslationUnit_CacheCompletionResults |
2121 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002122}
2123
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002124CXTranslationUnit
2125clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2126 const char *source_filename,
2127 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002128 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002129 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002130 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002131 return clang_parseTranslationUnit(CIdx, source_filename,
2132 command_line_args, num_command_line_args,
2133 unsaved_files, num_unsaved_files,
2134 CXTranslationUnit_DetailedPreprocessingRecord);
2135}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002136
2137struct ParseTranslationUnitInfo {
2138 CXIndex CIdx;
2139 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002140 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002141 int num_command_line_args;
2142 struct CXUnsavedFile *unsaved_files;
2143 unsigned num_unsaved_files;
2144 unsigned options;
2145 CXTranslationUnit result;
2146};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002147static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002148 ParseTranslationUnitInfo *PTUI =
2149 static_cast<ParseTranslationUnitInfo*>(UserData);
2150 CXIndex CIdx = PTUI->CIdx;
2151 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002152 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002153 int num_command_line_args = PTUI->num_command_line_args;
2154 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2155 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2156 unsigned options = PTUI->options;
2157 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002158
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002159 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002160 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002161
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002162 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2163
Douglas Gregor44c181a2010-07-23 00:33:23 +00002164 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002165 bool CompleteTranslationUnit
2166 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002167 bool CacheCodeCompetionResults
2168 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002169 bool CXXPrecompilePreamble
2170 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2171 bool CXXChainedPCH
2172 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002173
Douglas Gregor5352ac02010-01-28 00:27:43 +00002174 // Configure the diagnostics.
2175 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002176 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2177 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002178
Douglas Gregor4db64a42010-01-23 00:14:00 +00002179 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2180 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002181 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002182 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002183 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002184 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2185 Buffer));
2186 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002187
Douglas Gregorb10daed2010-10-11 16:52:23 +00002188 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002189
Ted Kremenek139ba862009-10-22 00:03:57 +00002190 // The 'source_filename' argument is optional. If the caller does not
2191 // specify it then it is assumed that the source file is specified
2192 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002193 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002194 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002195
2196 // Since the Clang C library is primarily used by batch tools dealing with
2197 // (often very broken) source code, where spell-checking can have a
2198 // significant negative impact on performance (particularly when
2199 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002200 // Only do this if we haven't found a spell-checking-related argument.
2201 bool FoundSpellCheckingArgument = false;
2202 for (int I = 0; I != num_command_line_args; ++I) {
2203 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2204 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2205 FoundSpellCheckingArgument = true;
2206 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002207 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002208 }
2209 if (!FoundSpellCheckingArgument)
2210 Args.push_back("-fno-spell-checking");
2211
2212 Args.insert(Args.end(), command_line_args,
2213 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002214
Douglas Gregor44c181a2010-07-23 00:33:23 +00002215 // Do we need the detailed preprocessing record?
2216 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002217 Args.push_back("-Xclang");
2218 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002219 }
2220
Douglas Gregorb10daed2010-10-11 16:52:23 +00002221 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002222 llvm::OwningPtr<ASTUnit> Unit(
2223 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2224 Diags,
2225 CXXIdx->getClangResourcesPath(),
2226 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002227 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002228 RemappedFiles.data(),
2229 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002230 PrecompilePreamble,
2231 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002232 CacheCodeCompetionResults,
2233 CXXPrecompilePreamble,
2234 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002235
Douglas Gregorb10daed2010-10-11 16:52:23 +00002236 if (NumErrors != Diags->getNumErrors()) {
2237 // Make sure to check that 'Unit' is non-NULL.
2238 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2239 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2240 DEnd = Unit->stored_diag_end();
2241 D != DEnd; ++D) {
2242 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2243 CXString Msg = clang_formatDiagnostic(&Diag,
2244 clang_defaultDiagnosticDisplayOptions());
2245 fprintf(stderr, "%s\n", clang_getCString(Msg));
2246 clang_disposeString(Msg);
2247 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002248#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002249 // On Windows, force a flush, since there may be multiple copies of
2250 // stderr and stdout in the file system, all with different buffers
2251 // but writing to the same device.
2252 fflush(stderr);
2253#endif
2254 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002255 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002256
Ted Kremeneka60ed472010-11-16 08:15:36 +00002257 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002258}
2259CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2260 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002261 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002262 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002263 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002264 unsigned num_unsaved_files,
2265 unsigned options) {
2266 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002267 num_command_line_args, unsaved_files,
2268 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002269 llvm::CrashRecoveryContext CRC;
2270
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002271 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002272 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2273 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2274 fprintf(stderr, " 'command_line_args' : [");
2275 for (int i = 0; i != num_command_line_args; ++i) {
2276 if (i)
2277 fprintf(stderr, ", ");
2278 fprintf(stderr, "'%s'", command_line_args[i]);
2279 }
2280 fprintf(stderr, "],\n");
2281 fprintf(stderr, " 'unsaved_files' : [");
2282 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2283 if (i)
2284 fprintf(stderr, ", ");
2285 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2286 unsaved_files[i].Length);
2287 }
2288 fprintf(stderr, "],\n");
2289 fprintf(stderr, " 'options' : %d,\n", options);
2290 fprintf(stderr, "}\n");
2291
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002292 return 0;
2293 }
2294
2295 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002296}
2297
Douglas Gregor19998442010-08-13 15:35:05 +00002298unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2299 return CXSaveTranslationUnit_None;
2300}
2301
2302int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2303 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002304 if (!TU)
2305 return 1;
2306
Ted Kremeneka60ed472010-11-16 08:15:36 +00002307 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002308}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002309
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002310void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002311 if (CTUnit) {
2312 // If the translation unit has been marked as unsafe to free, just discard
2313 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002314 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002315 return;
2316
Ted Kremeneka60ed472010-11-16 08:15:36 +00002317 delete static_cast<ASTUnit *>(CTUnit->TUData);
2318 disposeCXStringPool(CTUnit->StringPool);
2319 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002320 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002321}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002322
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002323unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2324 return CXReparse_None;
2325}
2326
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002327struct ReparseTranslationUnitInfo {
2328 CXTranslationUnit TU;
2329 unsigned num_unsaved_files;
2330 struct CXUnsavedFile *unsaved_files;
2331 unsigned options;
2332 int result;
2333};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002334
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002335static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002336 ReparseTranslationUnitInfo *RTUI =
2337 static_cast<ReparseTranslationUnitInfo*>(UserData);
2338 CXTranslationUnit TU = RTUI->TU;
2339 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2340 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2341 unsigned options = RTUI->options;
2342 (void) options;
2343 RTUI->result = 1;
2344
Douglas Gregorabc563f2010-07-19 21:46:24 +00002345 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002346 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002347
Ted Kremeneka60ed472010-11-16 08:15:36 +00002348 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002349 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002350
2351 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2352 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2353 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2354 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002355 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002356 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2357 Buffer));
2358 }
2359
Douglas Gregor593b0c12010-09-23 18:47:53 +00002360 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2361 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002362}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002363
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002364int clang_reparseTranslationUnit(CXTranslationUnit TU,
2365 unsigned num_unsaved_files,
2366 struct CXUnsavedFile *unsaved_files,
2367 unsigned options) {
2368 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2369 options, 0 };
2370 llvm::CrashRecoveryContext CRC;
2371
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002372 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002373 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002374 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002375 return 1;
2376 }
2377
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002378
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002379 return RTUI.result;
2380}
2381
Douglas Gregordf95a132010-08-09 20:45:32 +00002382
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002383CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002384 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002385 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002386
Ted Kremeneka60ed472010-11-16 08:15:36 +00002387 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002388 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002389}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002390
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002391CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002392 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002393 return Result;
2394}
2395
Ted Kremenekfb480492010-01-13 21:46:36 +00002396} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002397
Ted Kremenekfb480492010-01-13 21:46:36 +00002398//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002399// CXSourceLocation and CXSourceRange Operations.
2400//===----------------------------------------------------------------------===//
2401
Douglas Gregorb9790342010-01-22 21:44:22 +00002402extern "C" {
2403CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002404 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002405 return Result;
2406}
2407
2408unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002409 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2410 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2411 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002412}
2413
2414CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2415 CXFile file,
2416 unsigned line,
2417 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002418 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002419 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002420
Ted Kremeneka60ed472010-11-16 08:15:36 +00002421 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregorb9790342010-01-22 21:44:22 +00002422 SourceLocation SLoc
2423 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002424 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002425 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002426 if (SLoc.isInvalid()) return clang_getNullLocation();
2427
2428 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2429}
2430
2431CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2432 CXFile file,
2433 unsigned offset) {
2434 if (!tu || !file)
2435 return clang_getNullLocation();
2436
Ted Kremeneka60ed472010-11-16 08:15:36 +00002437 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002438 SourceLocation Start
2439 = CXXUnit->getSourceManager().getLocation(
2440 static_cast<const FileEntry *>(file),
2441 1, 1);
2442 if (Start.isInvalid()) return clang_getNullLocation();
2443
2444 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2445
2446 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002447
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002448 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002449}
2450
Douglas Gregor5352ac02010-01-28 00:27:43 +00002451CXSourceRange clang_getNullRange() {
2452 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2453 return Result;
2454}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002455
Douglas Gregor5352ac02010-01-28 00:27:43 +00002456CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2457 if (begin.ptr_data[0] != end.ptr_data[0] ||
2458 begin.ptr_data[1] != end.ptr_data[1])
2459 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002460
2461 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002462 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002463 return Result;
2464}
2465
Douglas Gregor46766dc2010-01-26 19:19:08 +00002466void clang_getInstantiationLocation(CXSourceLocation location,
2467 CXFile *file,
2468 unsigned *line,
2469 unsigned *column,
2470 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002471 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2472
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002473 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002474 if (file)
2475 *file = 0;
2476 if (line)
2477 *line = 0;
2478 if (column)
2479 *column = 0;
2480 if (offset)
2481 *offset = 0;
2482 return;
2483 }
2484
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002485 const SourceManager &SM =
2486 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002487 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002488
2489 if (file)
2490 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2491 if (line)
2492 *line = SM.getInstantiationLineNumber(InstLoc);
2493 if (column)
2494 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002495 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002496 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002497}
2498
Douglas Gregora9b06d42010-11-09 06:24:54 +00002499void clang_getSpellingLocation(CXSourceLocation location,
2500 CXFile *file,
2501 unsigned *line,
2502 unsigned *column,
2503 unsigned *offset) {
2504 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2505
2506 if (!location.ptr_data[0] || Loc.isInvalid()) {
2507 if (file)
2508 *file = 0;
2509 if (line)
2510 *line = 0;
2511 if (column)
2512 *column = 0;
2513 if (offset)
2514 *offset = 0;
2515 return;
2516 }
2517
2518 const SourceManager &SM =
2519 *static_cast<const SourceManager*>(location.ptr_data[0]);
2520 SourceLocation SpellLoc = Loc;
2521 if (SpellLoc.isMacroID()) {
2522 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2523 if (SimpleSpellingLoc.isFileID() &&
2524 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2525 SpellLoc = SimpleSpellingLoc;
2526 else
2527 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2528 }
2529
2530 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2531 FileID FID = LocInfo.first;
2532 unsigned FileOffset = LocInfo.second;
2533
2534 if (file)
2535 *file = (void *)SM.getFileEntryForID(FID);
2536 if (line)
2537 *line = SM.getLineNumber(FID, FileOffset);
2538 if (column)
2539 *column = SM.getColumnNumber(FID, FileOffset);
2540 if (offset)
2541 *offset = FileOffset;
2542}
2543
Douglas Gregor1db19de2010-01-19 21:36:55 +00002544CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002545 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002546 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002547 return Result;
2548}
2549
2550CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002551 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002552 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002553 return Result;
2554}
2555
Douglas Gregorb9790342010-01-22 21:44:22 +00002556} // end: extern "C"
2557
Douglas Gregor1db19de2010-01-19 21:36:55 +00002558//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002559// CXFile Operations.
2560//===----------------------------------------------------------------------===//
2561
2562extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002563CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002564 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002565 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002566
Steve Naroff88145032009-10-27 14:35:18 +00002567 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002568 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002569}
2570
2571time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002572 if (!SFile)
2573 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002574
Steve Naroff88145032009-10-27 14:35:18 +00002575 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2576 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002577}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002578
Douglas Gregorb9790342010-01-22 21:44:22 +00002579CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2580 if (!tu)
2581 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582
Ted Kremeneka60ed472010-11-16 08:15:36 +00002583 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002584
Douglas Gregorb9790342010-01-22 21:44:22 +00002585 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002586 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2587 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002588 return const_cast<FileEntry *>(File);
2589}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590
Ted Kremenekfb480492010-01-13 21:46:36 +00002591} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002592
Ted Kremenekfb480492010-01-13 21:46:36 +00002593//===----------------------------------------------------------------------===//
2594// CXCursor Operations.
2595//===----------------------------------------------------------------------===//
2596
Ted Kremenekfb480492010-01-13 21:46:36 +00002597static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002598 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2599 return getDeclFromExpr(CE->getSubExpr());
2600
Ted Kremenekfb480492010-01-13 21:46:36 +00002601 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2602 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002603 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2604 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002605 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2606 return ME->getMemberDecl();
2607 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2608 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002609 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2610 return PRE->getProperty();
2611
Ted Kremenekfb480492010-01-13 21:46:36 +00002612 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2613 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002614 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2615 if (!CE->isElidable())
2616 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002617 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2618 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002619
Douglas Gregordb1314e2010-10-01 21:11:22 +00002620 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2621 return PE->getProtocol();
2622
Ted Kremenekfb480492010-01-13 21:46:36 +00002623 return 0;
2624}
2625
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002626static SourceLocation getLocationFromExpr(Expr *E) {
2627 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2628 return /*FIXME:*/Msg->getLeftLoc();
2629 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2630 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002631 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2632 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002633 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2634 return Member->getMemberLoc();
2635 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2636 return Ivar->getLocation();
2637 return E->getLocStart();
2638}
2639
Ted Kremenekfb480492010-01-13 21:46:36 +00002640extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002641
2642unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002643 CXCursorVisitor visitor,
2644 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002645 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2646 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002647 return CursorVis.VisitChildren(parent);
2648}
2649
David Chisnall3387c652010-11-03 14:12:26 +00002650#ifndef __has_feature
2651#define __has_feature(x) 0
2652#endif
2653#if __has_feature(blocks)
2654typedef enum CXChildVisitResult
2655 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2656
2657static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2658 CXClientData client_data) {
2659 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2660 return block(cursor, parent);
2661}
2662#else
2663// If we are compiled with a compiler that doesn't have native blocks support,
2664// define and call the block manually, so the
2665typedef struct _CXChildVisitResult
2666{
2667 void *isa;
2668 int flags;
2669 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002670 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2671 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002672} *CXCursorVisitorBlock;
2673
2674static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2675 CXClientData client_data) {
2676 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2677 return block->invoke(block, cursor, parent);
2678}
2679#endif
2680
2681
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002682unsigned clang_visitChildrenWithBlock(CXCursor parent,
2683 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002684 return clang_visitChildren(parent, visitWithBlock, block);
2685}
2686
Douglas Gregor78205d42010-01-20 21:45:58 +00002687static CXString getDeclSpelling(Decl *D) {
2688 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002689 if (!ND) {
2690 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2691 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2692 return createCXString(Property->getIdentifier()->getName());
2693
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002694 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002695 }
2696
Douglas Gregor78205d42010-01-20 21:45:58 +00002697 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002698 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002699
Douglas Gregor78205d42010-01-20 21:45:58 +00002700 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2701 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2702 // and returns different names. NamedDecl returns the class name and
2703 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002704 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002705
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002706 if (isa<UsingDirectiveDecl>(D))
2707 return createCXString("");
2708
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002709 llvm::SmallString<1024> S;
2710 llvm::raw_svector_ostream os(S);
2711 ND->printName(os);
2712
2713 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002714}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002716CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002717 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002718 return clang_getTranslationUnitSpelling(
2719 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002720
Steve Narofff334b4e2009-09-02 18:26:48 +00002721 if (clang_isReference(C.kind)) {
2722 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002723 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002724 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002725 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002726 }
2727 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002728 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002729 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002730 }
2731 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002732 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002733 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002734 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002735 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002736 case CXCursor_CXXBaseSpecifier: {
2737 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2738 return createCXString(B->getType().getAsString());
2739 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002740 case CXCursor_TypeRef: {
2741 TypeDecl *Type = getCursorTypeRef(C).first;
2742 assert(Type && "Missing type decl");
2743
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002744 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2745 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002746 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002747 case CXCursor_TemplateRef: {
2748 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002749 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002750
2751 return createCXString(Template->getNameAsString());
2752 }
Douglas Gregor69319002010-08-31 23:48:11 +00002753
2754 case CXCursor_NamespaceRef: {
2755 NamedDecl *NS = getCursorNamespaceRef(C).first;
2756 assert(NS && "Missing namespace decl");
2757
2758 return createCXString(NS->getNameAsString());
2759 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002760
Douglas Gregora67e03f2010-09-09 21:42:20 +00002761 case CXCursor_MemberRef: {
2762 FieldDecl *Field = getCursorMemberRef(C).first;
2763 assert(Field && "Missing member decl");
2764
2765 return createCXString(Field->getNameAsString());
2766 }
2767
Douglas Gregor36897b02010-09-10 00:22:18 +00002768 case CXCursor_LabelRef: {
2769 LabelStmt *Label = getCursorLabelRef(C).first;
2770 assert(Label && "Missing label");
2771
2772 return createCXString(Label->getID()->getName());
2773 }
2774
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002775 case CXCursor_OverloadedDeclRef: {
2776 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2777 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2778 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2779 return createCXString(ND->getNameAsString());
2780 return createCXString("");
2781 }
2782 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2783 return createCXString(E->getName().getAsString());
2784 OverloadedTemplateStorage *Ovl
2785 = Storage.get<OverloadedTemplateStorage*>();
2786 if (Ovl->size() == 0)
2787 return createCXString("");
2788 return createCXString((*Ovl->begin())->getNameAsString());
2789 }
2790
Daniel Dunbaracca7252009-11-30 20:42:49 +00002791 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002792 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002793 }
2794 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002795
2796 if (clang_isExpression(C.kind)) {
2797 Decl *D = getDeclFromExpr(getCursorExpr(C));
2798 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002799 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002800 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002801 }
2802
Douglas Gregor36897b02010-09-10 00:22:18 +00002803 if (clang_isStatement(C.kind)) {
2804 Stmt *S = getCursorStmt(C);
2805 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2806 return createCXString(Label->getID()->getName());
2807
2808 return createCXString("");
2809 }
2810
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002811 if (C.kind == CXCursor_MacroInstantiation)
2812 return createCXString(getCursorMacroInstantiation(C)->getName()
2813 ->getNameStart());
2814
Douglas Gregor572feb22010-03-18 18:04:21 +00002815 if (C.kind == CXCursor_MacroDefinition)
2816 return createCXString(getCursorMacroDefinition(C)->getName()
2817 ->getNameStart());
2818
Douglas Gregorecdcb882010-10-20 22:00:55 +00002819 if (C.kind == CXCursor_InclusionDirective)
2820 return createCXString(getCursorInclusionDirective(C)->getFileName());
2821
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002822 if (clang_isDeclaration(C.kind))
2823 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002824
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002825 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002826}
2827
Douglas Gregor358559d2010-10-02 22:49:11 +00002828CXString clang_getCursorDisplayName(CXCursor C) {
2829 if (!clang_isDeclaration(C.kind))
2830 return clang_getCursorSpelling(C);
2831
2832 Decl *D = getCursorDecl(C);
2833 if (!D)
2834 return createCXString("");
2835
2836 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2837 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2838 D = FunTmpl->getTemplatedDecl();
2839
2840 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2841 llvm::SmallString<64> Str;
2842 llvm::raw_svector_ostream OS(Str);
2843 OS << Function->getNameAsString();
2844 if (Function->getPrimaryTemplate())
2845 OS << "<>";
2846 OS << "(";
2847 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2848 if (I)
2849 OS << ", ";
2850 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2851 }
2852
2853 if (Function->isVariadic()) {
2854 if (Function->getNumParams())
2855 OS << ", ";
2856 OS << "...";
2857 }
2858 OS << ")";
2859 return createCXString(OS.str());
2860 }
2861
2862 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2863 llvm::SmallString<64> Str;
2864 llvm::raw_svector_ostream OS(Str);
2865 OS << ClassTemplate->getNameAsString();
2866 OS << "<";
2867 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2868 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2869 if (I)
2870 OS << ", ";
2871
2872 NamedDecl *Param = Params->getParam(I);
2873 if (Param->getIdentifier()) {
2874 OS << Param->getIdentifier()->getName();
2875 continue;
2876 }
2877
2878 // There is no parameter name, which makes this tricky. Try to come up
2879 // with something useful that isn't too long.
2880 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2881 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2882 else if (NonTypeTemplateParmDecl *NTTP
2883 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2884 OS << NTTP->getType().getAsString(Policy);
2885 else
2886 OS << "template<...> class";
2887 }
2888
2889 OS << ">";
2890 return createCXString(OS.str());
2891 }
2892
2893 if (ClassTemplateSpecializationDecl *ClassSpec
2894 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2895 // If the type was explicitly written, use that.
2896 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2897 return createCXString(TSInfo->getType().getAsString(Policy));
2898
2899 llvm::SmallString<64> Str;
2900 llvm::raw_svector_ostream OS(Str);
2901 OS << ClassSpec->getNameAsString();
2902 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002903 ClassSpec->getTemplateArgs().data(),
2904 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002905 Policy);
2906 return createCXString(OS.str());
2907 }
2908
2909 return clang_getCursorSpelling(C);
2910}
2911
Ted Kremeneke68fff62010-02-17 00:41:32 +00002912CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002913 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002914 case CXCursor_FunctionDecl:
2915 return createCXString("FunctionDecl");
2916 case CXCursor_TypedefDecl:
2917 return createCXString("TypedefDecl");
2918 case CXCursor_EnumDecl:
2919 return createCXString("EnumDecl");
2920 case CXCursor_EnumConstantDecl:
2921 return createCXString("EnumConstantDecl");
2922 case CXCursor_StructDecl:
2923 return createCXString("StructDecl");
2924 case CXCursor_UnionDecl:
2925 return createCXString("UnionDecl");
2926 case CXCursor_ClassDecl:
2927 return createCXString("ClassDecl");
2928 case CXCursor_FieldDecl:
2929 return createCXString("FieldDecl");
2930 case CXCursor_VarDecl:
2931 return createCXString("VarDecl");
2932 case CXCursor_ParmDecl:
2933 return createCXString("ParmDecl");
2934 case CXCursor_ObjCInterfaceDecl:
2935 return createCXString("ObjCInterfaceDecl");
2936 case CXCursor_ObjCCategoryDecl:
2937 return createCXString("ObjCCategoryDecl");
2938 case CXCursor_ObjCProtocolDecl:
2939 return createCXString("ObjCProtocolDecl");
2940 case CXCursor_ObjCPropertyDecl:
2941 return createCXString("ObjCPropertyDecl");
2942 case CXCursor_ObjCIvarDecl:
2943 return createCXString("ObjCIvarDecl");
2944 case CXCursor_ObjCInstanceMethodDecl:
2945 return createCXString("ObjCInstanceMethodDecl");
2946 case CXCursor_ObjCClassMethodDecl:
2947 return createCXString("ObjCClassMethodDecl");
2948 case CXCursor_ObjCImplementationDecl:
2949 return createCXString("ObjCImplementationDecl");
2950 case CXCursor_ObjCCategoryImplDecl:
2951 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002952 case CXCursor_CXXMethod:
2953 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002954 case CXCursor_UnexposedDecl:
2955 return createCXString("UnexposedDecl");
2956 case CXCursor_ObjCSuperClassRef:
2957 return createCXString("ObjCSuperClassRef");
2958 case CXCursor_ObjCProtocolRef:
2959 return createCXString("ObjCProtocolRef");
2960 case CXCursor_ObjCClassRef:
2961 return createCXString("ObjCClassRef");
2962 case CXCursor_TypeRef:
2963 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002964 case CXCursor_TemplateRef:
2965 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002966 case CXCursor_NamespaceRef:
2967 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002968 case CXCursor_MemberRef:
2969 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002970 case CXCursor_LabelRef:
2971 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002972 case CXCursor_OverloadedDeclRef:
2973 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002974 case CXCursor_UnexposedExpr:
2975 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002976 case CXCursor_BlockExpr:
2977 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002978 case CXCursor_DeclRefExpr:
2979 return createCXString("DeclRefExpr");
2980 case CXCursor_MemberRefExpr:
2981 return createCXString("MemberRefExpr");
2982 case CXCursor_CallExpr:
2983 return createCXString("CallExpr");
2984 case CXCursor_ObjCMessageExpr:
2985 return createCXString("ObjCMessageExpr");
2986 case CXCursor_UnexposedStmt:
2987 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002988 case CXCursor_LabelStmt:
2989 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002990 case CXCursor_InvalidFile:
2991 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002992 case CXCursor_InvalidCode:
2993 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002994 case CXCursor_NoDeclFound:
2995 return createCXString("NoDeclFound");
2996 case CXCursor_NotImplemented:
2997 return createCXString("NotImplemented");
2998 case CXCursor_TranslationUnit:
2999 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003000 case CXCursor_UnexposedAttr:
3001 return createCXString("UnexposedAttr");
3002 case CXCursor_IBActionAttr:
3003 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003004 case CXCursor_IBOutletAttr:
3005 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003006 case CXCursor_IBOutletCollectionAttr:
3007 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003008 case CXCursor_PreprocessingDirective:
3009 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003010 case CXCursor_MacroDefinition:
3011 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003012 case CXCursor_MacroInstantiation:
3013 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003014 case CXCursor_InclusionDirective:
3015 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003016 case CXCursor_Namespace:
3017 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003018 case CXCursor_LinkageSpec:
3019 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003020 case CXCursor_CXXBaseSpecifier:
3021 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003022 case CXCursor_Constructor:
3023 return createCXString("CXXConstructor");
3024 case CXCursor_Destructor:
3025 return createCXString("CXXDestructor");
3026 case CXCursor_ConversionFunction:
3027 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003028 case CXCursor_TemplateTypeParameter:
3029 return createCXString("TemplateTypeParameter");
3030 case CXCursor_NonTypeTemplateParameter:
3031 return createCXString("NonTypeTemplateParameter");
3032 case CXCursor_TemplateTemplateParameter:
3033 return createCXString("TemplateTemplateParameter");
3034 case CXCursor_FunctionTemplate:
3035 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003036 case CXCursor_ClassTemplate:
3037 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003038 case CXCursor_ClassTemplatePartialSpecialization:
3039 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003040 case CXCursor_NamespaceAlias:
3041 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003042 case CXCursor_UsingDirective:
3043 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003044 case CXCursor_UsingDeclaration:
3045 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003046 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003047
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003048 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003049 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003050}
Steve Naroff89922f82009-08-31 00:59:03 +00003051
Ted Kremeneke68fff62010-02-17 00:41:32 +00003052enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3053 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003054 CXClientData client_data) {
3055 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003056
3057 // If our current best cursor is the construction of a temporary object,
3058 // don't replace that cursor with a type reference, because we want
3059 // clang_getCursor() to point at the constructor.
3060 if (clang_isExpression(BestCursor->kind) &&
3061 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3062 cursor.kind == CXCursor_TypeRef)
3063 return CXChildVisit_Recurse;
3064
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003065 *BestCursor = cursor;
3066 return CXChildVisit_Recurse;
3067}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003068
Douglas Gregorb9790342010-01-22 21:44:22 +00003069CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3070 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003071 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003072
Ted Kremeneka60ed472010-11-16 08:15:36 +00003073 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003074 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3075
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003076 // Translate the given source location to make it point at the beginning of
3077 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003078 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003079
3080 // Guard against an invalid SourceLocation, or we may assert in one
3081 // of the following calls.
3082 if (SLoc.isInvalid())
3083 return clang_getNullCursor();
3084
Douglas Gregor40749ee2010-11-03 00:35:38 +00003085 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003086 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3087 CXXUnit->getASTContext().getLangOptions());
3088
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003089 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3090 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003091 // FIXME: Would be great to have a "hint" cursor, then walk from that
3092 // hint cursor upward until we find a cursor whose source range encloses
3093 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003094 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3095 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003096 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003097 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003098 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003099
3100 if (Logging) {
3101 CXFile SearchFile;
3102 unsigned SearchLine, SearchColumn;
3103 CXFile ResultFile;
3104 unsigned ResultLine, ResultColumn;
3105 CXString SearchFileName, ResultFileName, KindSpelling;
3106 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3107
3108 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3109 0);
3110 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3111 &ResultColumn, 0);
3112 SearchFileName = clang_getFileName(SearchFile);
3113 ResultFileName = clang_getFileName(ResultFile);
3114 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3115 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3116 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3117 clang_getCString(KindSpelling),
3118 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3119 clang_disposeString(SearchFileName);
3120 clang_disposeString(ResultFileName);
3121 clang_disposeString(KindSpelling);
3122 }
3123
Ted Kremeneke68fff62010-02-17 00:41:32 +00003124 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003125}
3126
Ted Kremenek73885552009-11-17 19:28:59 +00003127CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003128 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003129}
3130
3131unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003132 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003133}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003134
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003135unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003136 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3137}
3138
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003139unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003140 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3141}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003142
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003143unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003144 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3145}
3146
Douglas Gregor97b98722010-01-19 23:20:36 +00003147unsigned clang_isExpression(enum CXCursorKind K) {
3148 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3149}
3150
3151unsigned clang_isStatement(enum CXCursorKind K) {
3152 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3153}
3154
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003155unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3156 return K == CXCursor_TranslationUnit;
3157}
3158
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003159unsigned clang_isPreprocessing(enum CXCursorKind K) {
3160 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3161}
3162
Ted Kremenekad6eff62010-03-08 21:17:29 +00003163unsigned clang_isUnexposed(enum CXCursorKind K) {
3164 switch (K) {
3165 case CXCursor_UnexposedDecl:
3166 case CXCursor_UnexposedExpr:
3167 case CXCursor_UnexposedStmt:
3168 case CXCursor_UnexposedAttr:
3169 return true;
3170 default:
3171 return false;
3172 }
3173}
3174
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003175CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003176 return C.kind;
3177}
3178
Douglas Gregor98258af2010-01-18 22:46:11 +00003179CXSourceLocation clang_getCursorLocation(CXCursor C) {
3180 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003181 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003182 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003183 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3184 = getCursorObjCSuperClassRef(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_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003189 std::pair<ObjCProtocolDecl *, SourceLocation> P
3190 = getCursorObjCProtocolRef(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 }
3193
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003194 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003195 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3196 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003197 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003198 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003199
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003200 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003201 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003202 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003203 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003204
3205 case CXCursor_TemplateRef: {
3206 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3207 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3208 }
3209
Douglas Gregor69319002010-08-31 23:48:11 +00003210 case CXCursor_NamespaceRef: {
3211 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3212 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3213 }
3214
Douglas Gregora67e03f2010-09-09 21:42:20 +00003215 case CXCursor_MemberRef: {
3216 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3217 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3218 }
3219
Ted Kremenek3064ef92010-08-27 21:34:58 +00003220 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003221 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3222 if (!BaseSpec)
3223 return clang_getNullLocation();
3224
3225 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3226 return cxloc::translateSourceLocation(getCursorContext(C),
3227 TSInfo->getTypeLoc().getBeginLoc());
3228
3229 return cxloc::translateSourceLocation(getCursorContext(C),
3230 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003231 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003232
Douglas Gregor36897b02010-09-10 00:22:18 +00003233 case CXCursor_LabelRef: {
3234 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3235 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3236 }
3237
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003238 case CXCursor_OverloadedDeclRef:
3239 return cxloc::translateSourceLocation(getCursorContext(C),
3240 getCursorOverloadedDeclRef(C).second);
3241
Douglas Gregorf46034a2010-01-18 23:41:10 +00003242 default:
3243 // FIXME: Need a way to enumerate all non-reference cases.
3244 llvm_unreachable("Missed a reference kind");
3245 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003246 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003247
3248 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003249 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003250 getLocationFromExpr(getCursorExpr(C)));
3251
Douglas Gregor36897b02010-09-10 00:22:18 +00003252 if (clang_isStatement(C.kind))
3253 return cxloc::translateSourceLocation(getCursorContext(C),
3254 getCursorStmt(C)->getLocStart());
3255
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003256 if (C.kind == CXCursor_PreprocessingDirective) {
3257 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3258 return cxloc::translateSourceLocation(getCursorContext(C), L);
3259 }
Douglas Gregor48072312010-03-18 15:23:44 +00003260
3261 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003262 SourceLocation L
3263 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003264 return cxloc::translateSourceLocation(getCursorContext(C), L);
3265 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003266
3267 if (C.kind == CXCursor_MacroDefinition) {
3268 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3269 return cxloc::translateSourceLocation(getCursorContext(C), L);
3270 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003271
3272 if (C.kind == CXCursor_InclusionDirective) {
3273 SourceLocation L
3274 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3275 return cxloc::translateSourceLocation(getCursorContext(C), L);
3276 }
3277
Ted Kremenek9a700d22010-05-12 06:16:13 +00003278 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003279 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003280
Douglas Gregorf46034a2010-01-18 23:41:10 +00003281 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003282 SourceLocation Loc = D->getLocation();
3283 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3284 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003285 // FIXME: Multiple variables declared in a single declaration
3286 // currently lack the information needed to correctly determine their
3287 // ranges when accounting for the type-specifier. We use context
3288 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3289 // and if so, whether it is the first decl.
3290 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3291 if (!cxcursor::isFirstInDeclGroup(C))
3292 Loc = VD->getLocation();
3293 }
3294
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003295 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003296}
Douglas Gregora7bde202010-01-19 00:34:46 +00003297
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003298} // end extern "C"
3299
3300static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003301 if (clang_isReference(C.kind)) {
3302 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003303 case CXCursor_ObjCSuperClassRef:
3304 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003305
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003306 case CXCursor_ObjCProtocolRef:
3307 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003308
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003309 case CXCursor_ObjCClassRef:
3310 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003311
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003312 case CXCursor_TypeRef:
3313 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003314
3315 case CXCursor_TemplateRef:
3316 return getCursorTemplateRef(C).second;
3317
Douglas Gregor69319002010-08-31 23:48:11 +00003318 case CXCursor_NamespaceRef:
3319 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003320
3321 case CXCursor_MemberRef:
3322 return getCursorMemberRef(C).second;
3323
Ted Kremenek3064ef92010-08-27 21:34:58 +00003324 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003325 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003326
Douglas Gregor36897b02010-09-10 00:22:18 +00003327 case CXCursor_LabelRef:
3328 return getCursorLabelRef(C).second;
3329
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003330 case CXCursor_OverloadedDeclRef:
3331 return getCursorOverloadedDeclRef(C).second;
3332
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003333 default:
3334 // FIXME: Need a way to enumerate all non-reference cases.
3335 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003336 }
3337 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003338
3339 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003340 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003341
3342 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003343 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003344
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003345 if (C.kind == CXCursor_PreprocessingDirective)
3346 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003347
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003348 if (C.kind == CXCursor_MacroInstantiation)
3349 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003350
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003351 if (C.kind == CXCursor_MacroDefinition)
3352 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003353
3354 if (C.kind == CXCursor_InclusionDirective)
3355 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3356
Ted Kremenek007a7c92010-11-01 23:26:51 +00003357 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3358 Decl *D = cxcursor::getCursorDecl(C);
3359 SourceRange R = D->getSourceRange();
3360 // FIXME: Multiple variables declared in a single declaration
3361 // currently lack the information needed to correctly determine their
3362 // ranges when accounting for the type-specifier. We use context
3363 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3364 // and if so, whether it is the first decl.
3365 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3366 if (!cxcursor::isFirstInDeclGroup(C))
3367 R.setBegin(VD->getLocation());
3368 }
3369 return R;
3370 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003371 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003372
3373extern "C" {
3374
3375CXSourceRange clang_getCursorExtent(CXCursor C) {
3376 SourceRange R = getRawCursorExtent(C);
3377 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003378 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003379
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003380 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003381}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003382
3383CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003384 if (clang_isInvalid(C.kind))
3385 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003386
Ted Kremeneka60ed472010-11-16 08:15:36 +00003387 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003388 if (clang_isDeclaration(C.kind)) {
3389 Decl *D = getCursorDecl(C);
3390 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003391 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003392 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003393 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003394 if (ObjCForwardProtocolDecl *Protocols
3395 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003396 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003397 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3398 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3399 return MakeCXCursor(Property, tu);
3400
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003401 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003402 }
3403
Douglas Gregor97b98722010-01-19 23:20:36 +00003404 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003405 Expr *E = getCursorExpr(C);
3406 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003407 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003408 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003409
3410 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003411 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003412
Douglas Gregor97b98722010-01-19 23:20:36 +00003413 return clang_getNullCursor();
3414 }
3415
Douglas Gregor36897b02010-09-10 00:22:18 +00003416 if (clang_isStatement(C.kind)) {
3417 Stmt *S = getCursorStmt(C);
3418 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003419 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003420
3421 return clang_getNullCursor();
3422 }
3423
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003424 if (C.kind == CXCursor_MacroInstantiation) {
3425 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003426 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003427 }
3428
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003429 if (!clang_isReference(C.kind))
3430 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003431
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003432 switch (C.kind) {
3433 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003434 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003435
3436 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003437 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438
3439 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003440 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003441
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003442 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003443 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003444
3445 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003446 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003447
Douglas Gregor69319002010-08-31 23:48:11 +00003448 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003449 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003450
Douglas Gregora67e03f2010-09-09 21:42:20 +00003451 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003452 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003453
Ted Kremenek3064ef92010-08-27 21:34:58 +00003454 case CXCursor_CXXBaseSpecifier: {
3455 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3456 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003457 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003458 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003459
Douglas Gregor36897b02010-09-10 00:22:18 +00003460 case CXCursor_LabelRef:
3461 // FIXME: We end up faking the "parent" declaration here because we
3462 // don't want to make CXCursor larger.
3463 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003464 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3465 .getTranslationUnitDecl(),
3466 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003467
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003468 case CXCursor_OverloadedDeclRef:
3469 return C;
3470
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003471 default:
3472 // We would prefer to enumerate all non-reference cursor kinds here.
3473 llvm_unreachable("Unhandled reference cursor kind");
3474 break;
3475 }
3476 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003477
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003478 return clang_getNullCursor();
3479}
3480
Douglas Gregorb6998662010-01-19 19:34:47 +00003481CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003482 if (clang_isInvalid(C.kind))
3483 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003484
Ted Kremeneka60ed472010-11-16 08:15:36 +00003485 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003486
Douglas Gregorb6998662010-01-19 19:34:47 +00003487 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003488 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003489 C = clang_getCursorReferenced(C);
3490 WasReference = true;
3491 }
3492
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003493 if (C.kind == CXCursor_MacroInstantiation)
3494 return clang_getCursorReferenced(C);
3495
Douglas Gregorb6998662010-01-19 19:34:47 +00003496 if (!clang_isDeclaration(C.kind))
3497 return clang_getNullCursor();
3498
3499 Decl *D = getCursorDecl(C);
3500 if (!D)
3501 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003502
Douglas Gregorb6998662010-01-19 19:34:47 +00003503 switch (D->getKind()) {
3504 // Declaration kinds that don't really separate the notions of
3505 // declaration and definition.
3506 case Decl::Namespace:
3507 case Decl::Typedef:
3508 case Decl::TemplateTypeParm:
3509 case Decl::EnumConstant:
3510 case Decl::Field:
3511 case Decl::ObjCIvar:
3512 case Decl::ObjCAtDefsField:
3513 case Decl::ImplicitParam:
3514 case Decl::ParmVar:
3515 case Decl::NonTypeTemplateParm:
3516 case Decl::TemplateTemplateParm:
3517 case Decl::ObjCCategoryImpl:
3518 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003519 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003520 case Decl::LinkageSpec:
3521 case Decl::ObjCPropertyImpl:
3522 case Decl::FileScopeAsm:
3523 case Decl::StaticAssert:
3524 case Decl::Block:
3525 return C;
3526
3527 // Declaration kinds that don't make any sense here, but are
3528 // nonetheless harmless.
3529 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003530 break;
3531
3532 // Declaration kinds for which the definition is not resolvable.
3533 case Decl::UnresolvedUsingTypename:
3534 case Decl::UnresolvedUsingValue:
3535 break;
3536
3537 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003538 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003539 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003540
3541 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003542 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003543
3544 case Decl::Enum:
3545 case Decl::Record:
3546 case Decl::CXXRecord:
3547 case Decl::ClassTemplateSpecialization:
3548 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003549 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003550 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003551 return clang_getNullCursor();
3552
3553 case Decl::Function:
3554 case Decl::CXXMethod:
3555 case Decl::CXXConstructor:
3556 case Decl::CXXDestructor:
3557 case Decl::CXXConversion: {
3558 const FunctionDecl *Def = 0;
3559 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003560 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003561 return clang_getNullCursor();
3562 }
3563
3564 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003565 // Ask the variable if it has a definition.
3566 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003567 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003568 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003569 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003570
Douglas Gregorb6998662010-01-19 19:34:47 +00003571 case Decl::FunctionTemplate: {
3572 const FunctionDecl *Def = 0;
3573 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003574 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003575 return clang_getNullCursor();
3576 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003577
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 case Decl::ClassTemplate: {
3579 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003580 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003581 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003582 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003583 return clang_getNullCursor();
3584 }
3585
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003586 case Decl::Using:
3587 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003588 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003589
3590 case Decl::UsingShadow:
3591 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003592 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003593 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003594
3595 case Decl::ObjCMethod: {
3596 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3597 if (Method->isThisDeclarationADefinition())
3598 return C;
3599
3600 // Dig out the method definition in the associated
3601 // @implementation, if we have it.
3602 // FIXME: The ASTs should make finding the definition easier.
3603 if (ObjCInterfaceDecl *Class
3604 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3605 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3606 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3607 Method->isInstanceMethod()))
3608 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003609 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003610
3611 return clang_getNullCursor();
3612 }
3613
3614 case Decl::ObjCCategory:
3615 if (ObjCCategoryImplDecl *Impl
3616 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003617 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003618 return clang_getNullCursor();
3619
3620 case Decl::ObjCProtocol:
3621 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3622 return C;
3623 return clang_getNullCursor();
3624
3625 case Decl::ObjCInterface:
3626 // There are two notions of a "definition" for an Objective-C
3627 // class: the interface and its implementation. When we resolved a
3628 // reference to an Objective-C class, produce the @interface as
3629 // the definition; when we were provided with the interface,
3630 // produce the @implementation as the definition.
3631 if (WasReference) {
3632 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3633 return C;
3634 } else if (ObjCImplementationDecl *Impl
3635 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003636 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003637 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003638
Douglas Gregorb6998662010-01-19 19:34:47 +00003639 case Decl::ObjCProperty:
3640 // FIXME: We don't really know where to find the
3641 // ObjCPropertyImplDecls that implement this property.
3642 return clang_getNullCursor();
3643
3644 case Decl::ObjCCompatibleAlias:
3645 if (ObjCInterfaceDecl *Class
3646 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3647 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003648 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003649
Douglas Gregorb6998662010-01-19 19:34:47 +00003650 return clang_getNullCursor();
3651
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003652 case Decl::ObjCForwardProtocol:
3653 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003654 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003655
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003656 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003657 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003658 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003659
3660 case Decl::Friend:
3661 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003662 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003663 return clang_getNullCursor();
3664
3665 case Decl::FriendTemplate:
3666 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003667 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003668 return clang_getNullCursor();
3669 }
3670
3671 return clang_getNullCursor();
3672}
3673
3674unsigned clang_isCursorDefinition(CXCursor C) {
3675 if (!clang_isDeclaration(C.kind))
3676 return 0;
3677
3678 return clang_getCursorDefinition(C) == C;
3679}
3680
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003681unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003682 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003683 return 0;
3684
3685 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3686 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3687 return E->getNumDecls();
3688
3689 if (OverloadedTemplateStorage *S
3690 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3691 return S->size();
3692
3693 Decl *D = Storage.get<Decl*>();
3694 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003695 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003696 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3697 return Classes->size();
3698 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3699 return Protocols->protocol_size();
3700
3701 return 0;
3702}
3703
3704CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003705 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003706 return clang_getNullCursor();
3707
3708 if (index >= clang_getNumOverloadedDecls(cursor))
3709 return clang_getNullCursor();
3710
Ted Kremeneka60ed472010-11-16 08:15:36 +00003711 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003712 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3713 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003714 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003715
3716 if (OverloadedTemplateStorage *S
3717 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003718 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003719
3720 Decl *D = Storage.get<Decl*>();
3721 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3722 // FIXME: This is, unfortunately, linear time.
3723 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3724 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003725 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003726 }
3727
3728 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003729 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003730
3731 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003732 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003733
3734 return clang_getNullCursor();
3735}
3736
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003737void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003738 const char **startBuf,
3739 const char **endBuf,
3740 unsigned *startLine,
3741 unsigned *startColumn,
3742 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003743 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003744 assert(getCursorDecl(C) && "CXCursor has null decl");
3745 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003746 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3747 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003748
Steve Naroff4ade6d62009-09-23 17:52:52 +00003749 SourceManager &SM = FD->getASTContext().getSourceManager();
3750 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3751 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3752 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3753 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3754 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3755 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3756}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003757
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003758void clang_enableStackTraces(void) {
3759 llvm::sys::PrintStackTraceOnErrorSignal();
3760}
3761
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003762void clang_executeOnThread(void (*fn)(void*), void *user_data,
3763 unsigned stack_size) {
3764 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3765}
3766
Ted Kremenekfb480492010-01-13 21:46:36 +00003767} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003768
Ted Kremenekfb480492010-01-13 21:46:36 +00003769//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003770// Token-based Operations.
3771//===----------------------------------------------------------------------===//
3772
3773/* CXToken layout:
3774 * int_data[0]: a CXTokenKind
3775 * int_data[1]: starting token location
3776 * int_data[2]: token length
3777 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003778 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003779 * otherwise unused.
3780 */
3781extern "C" {
3782
3783CXTokenKind clang_getTokenKind(CXToken CXTok) {
3784 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3785}
3786
3787CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3788 switch (clang_getTokenKind(CXTok)) {
3789 case CXToken_Identifier:
3790 case CXToken_Keyword:
3791 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003792 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3793 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003794
3795 case CXToken_Literal: {
3796 // We have stashed the starting pointer in the ptr_data field. Use it.
3797 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003798 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003799 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003800
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003801 case CXToken_Punctuation:
3802 case CXToken_Comment:
3803 break;
3804 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003805
3806 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003808 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003809 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003810 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003811
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003812 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3813 std::pair<FileID, unsigned> LocInfo
3814 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003815 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003816 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003817 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3818 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003819 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003821 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003822}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003823
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003824CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003825 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003826 if (!CXXUnit)
3827 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003828
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003829 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3830 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3831}
3832
3833CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003834 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003835 if (!CXXUnit)
3836 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003837
3838 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003839 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3840}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003841
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003842void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3843 CXToken **Tokens, unsigned *NumTokens) {
3844 if (Tokens)
3845 *Tokens = 0;
3846 if (NumTokens)
3847 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003848
Ted Kremeneka60ed472010-11-16 08:15:36 +00003849 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003850 if (!CXXUnit || !Tokens || !NumTokens)
3851 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003852
Douglas Gregorbdf60622010-03-05 21:16:25 +00003853 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3854
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003855 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003856 if (R.isInvalid())
3857 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003858
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3860 std::pair<FileID, unsigned> BeginLocInfo
3861 = SourceMgr.getDecomposedLoc(R.getBegin());
3862 std::pair<FileID, unsigned> EndLocInfo
3863 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003864
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003865 // Cannot tokenize across files.
3866 if (BeginLocInfo.first != EndLocInfo.first)
3867 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003868
3869 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003870 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003871 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003872 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003873 if (Invalid)
3874 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003875
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003876 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3877 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003878 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003879 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003880
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003881 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003882 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003883 llvm::SmallVector<CXToken, 32> CXTokens;
3884 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003885 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003886 do {
3887 // Lex the next token
3888 Lex.LexFromRawLexer(Tok);
3889 if (Tok.is(tok::eof))
3890 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003891
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003892 // Initialize the CXToken.
3893 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895 // - Common fields
3896 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3897 CXTok.int_data[2] = Tok.getLength();
3898 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003899
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003900 // - Kind-specific fields
3901 if (Tok.isLiteral()) {
3902 CXTok.int_data[0] = CXToken_Literal;
3903 CXTok.ptr_data = (void *)Tok.getLiteralData();
3904 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003905 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003906 std::pair<FileID, unsigned> LocInfo
3907 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003908 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003909 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003910 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3911 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003912 return;
3913
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003914 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003915 IdentifierInfo *II
3916 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003917
David Chisnall096428b2010-10-13 21:44:48 +00003918 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003919 CXTok.int_data[0] = CXToken_Keyword;
3920 }
3921 else {
3922 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3923 CXToken_Identifier
3924 : CXToken_Keyword;
3925 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003926 CXTok.ptr_data = II;
3927 } else if (Tok.is(tok::comment)) {
3928 CXTok.int_data[0] = CXToken_Comment;
3929 CXTok.ptr_data = 0;
3930 } else {
3931 CXTok.int_data[0] = CXToken_Punctuation;
3932 CXTok.ptr_data = 0;
3933 }
3934 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003935 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003936 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003937
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003938 if (CXTokens.empty())
3939 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003940
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003941 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3942 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3943 *NumTokens = CXTokens.size();
3944}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003945
Ted Kremenek6db61092010-05-05 00:55:15 +00003946void clang_disposeTokens(CXTranslationUnit TU,
3947 CXToken *Tokens, unsigned NumTokens) {
3948 free(Tokens);
3949}
3950
3951} // end: extern "C"
3952
3953//===----------------------------------------------------------------------===//
3954// Token annotation APIs.
3955//===----------------------------------------------------------------------===//
3956
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003957typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003958static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3959 CXCursor parent,
3960 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003961namespace {
3962class AnnotateTokensWorker {
3963 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003964 CXToken *Tokens;
3965 CXCursor *Cursors;
3966 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003967 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003968 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003969 CursorVisitor AnnotateVis;
3970 SourceManager &SrcMgr;
3971
3972 bool MoreTokens() const { return TokIdx < NumTokens; }
3973 unsigned NextToken() const { return TokIdx; }
3974 void AdvanceToken() { ++TokIdx; }
3975 SourceLocation GetTokenLoc(unsigned tokI) {
3976 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3977 }
3978
Ted Kremenek6db61092010-05-05 00:55:15 +00003979public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003980 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003981 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003982 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003983 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003984 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003985 AnnotateVis(tu,
3986 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003987 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003988 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003989
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003990 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003991 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003992 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003993 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003994 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00003995 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003996};
3997}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003998
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003999void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4000 // Walk the AST within the region of interest, annotating tokens
4001 // along the way.
4002 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004003
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4005 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004006 if (Pos != Annotated.end() &&
4007 (clang_isInvalid(Cursors[I].kind) ||
4008 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004009 Cursors[I] = Pos->second;
4010 }
4011
4012 // Finish up annotating any tokens left.
4013 if (!MoreTokens())
4014 return;
4015
4016 const CXCursor &C = clang_getNullCursor();
4017 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4018 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4019 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004020 }
4021}
4022
Ted Kremenek6db61092010-05-05 00:55:15 +00004023enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004024AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004025 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004026 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004027 if (cursorRange.isInvalid())
4028 return CXChildVisit_Recurse;
4029
Douglas Gregor4419b672010-10-21 06:10:04 +00004030 if (clang_isPreprocessing(cursor.kind)) {
4031 // For macro instantiations, just note where the beginning of the macro
4032 // instantiation occurs.
4033 if (cursor.kind == CXCursor_MacroInstantiation) {
4034 Annotated[Loc.int_data] = cursor;
4035 return CXChildVisit_Recurse;
4036 }
4037
Douglas Gregor4419b672010-10-21 06:10:04 +00004038 // Items in the preprocessing record are kept separate from items in
4039 // declarations, so we keep a separate token index.
4040 unsigned SavedTokIdx = TokIdx;
4041 TokIdx = PreprocessingTokIdx;
4042
4043 // Skip tokens up until we catch up to the beginning of the preprocessing
4044 // entry.
4045 while (MoreTokens()) {
4046 const unsigned I = NextToken();
4047 SourceLocation TokLoc = GetTokenLoc(I);
4048 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4049 case RangeBefore:
4050 AdvanceToken();
4051 continue;
4052 case RangeAfter:
4053 case RangeOverlap:
4054 break;
4055 }
4056 break;
4057 }
4058
4059 // Look at all of the tokens within this range.
4060 while (MoreTokens()) {
4061 const unsigned I = NextToken();
4062 SourceLocation TokLoc = GetTokenLoc(I);
4063 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4064 case RangeBefore:
4065 assert(0 && "Infeasible");
4066 case RangeAfter:
4067 break;
4068 case RangeOverlap:
4069 Cursors[I] = cursor;
4070 AdvanceToken();
4071 continue;
4072 }
4073 break;
4074 }
4075
4076 // Save the preprocessing token index; restore the non-preprocessing
4077 // token index.
4078 PreprocessingTokIdx = TokIdx;
4079 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004080 return CXChildVisit_Recurse;
4081 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004082
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004083 if (cursorRange.isInvalid())
4084 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004085
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004086 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4087
Ted Kremeneka333c662010-05-12 05:29:33 +00004088 // Adjust the annotated range based specific declarations.
4089 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4090 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004091 Decl *D = cxcursor::getCursorDecl(cursor);
4092 // Don't visit synthesized ObjC methods, since they have no syntatic
4093 // representation in the source.
4094 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4095 if (MD->isSynthesized())
4096 return CXChildVisit_Continue;
4097 }
4098 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004099 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4100 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004101 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004102 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004103 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004104 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004105 }
4106 }
4107 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004108
Ted Kremenek3f404602010-08-14 01:14:06 +00004109 // If the location of the cursor occurs within a macro instantiation, record
4110 // the spelling location of the cursor in our annotation map. We can then
4111 // paper over the token labelings during a post-processing step to try and
4112 // get cursor mappings for tokens that are the *arguments* of a macro
4113 // instantiation.
4114 if (L.isMacroID()) {
4115 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4116 // Only invalidate the old annotation if it isn't part of a preprocessing
4117 // directive. Here we assume that the default construction of CXCursor
4118 // results in CXCursor.kind being an initialized value (i.e., 0). If
4119 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004120
Ted Kremenek3f404602010-08-14 01:14:06 +00004121 CXCursor &oldC = Annotated[rawEncoding];
4122 if (!clang_isPreprocessing(oldC.kind))
4123 oldC = cursor;
4124 }
4125
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004126 const enum CXCursorKind K = clang_getCursorKind(parent);
4127 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004128 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4129 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004130
4131 while (MoreTokens()) {
4132 const unsigned I = NextToken();
4133 SourceLocation TokLoc = GetTokenLoc(I);
4134 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4135 case RangeBefore:
4136 Cursors[I] = updateC;
4137 AdvanceToken();
4138 continue;
4139 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004140 case RangeOverlap:
4141 break;
4142 }
4143 break;
4144 }
4145
4146 // Visit children to get their cursor information.
4147 const unsigned BeforeChildren = NextToken();
4148 VisitChildren(cursor);
4149 const unsigned AfterChildren = NextToken();
4150
4151 // Adjust 'Last' to the last token within the extent of the cursor.
4152 while (MoreTokens()) {
4153 const unsigned I = NextToken();
4154 SourceLocation TokLoc = GetTokenLoc(I);
4155 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4156 case RangeBefore:
4157 assert(0 && "Infeasible");
4158 case RangeAfter:
4159 break;
4160 case RangeOverlap:
4161 Cursors[I] = updateC;
4162 AdvanceToken();
4163 continue;
4164 }
4165 break;
4166 }
4167 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004168
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004169 // Scan the tokens that are at the beginning of the cursor, but are not
4170 // capture by the child cursors.
4171
4172 // For AST elements within macros, rely on a post-annotate pass to
4173 // to correctly annotate the tokens with cursors. Otherwise we can
4174 // get confusing results of having tokens that map to cursors that really
4175 // are expanded by an instantiation.
4176 if (L.isMacroID())
4177 cursor = clang_getNullCursor();
4178
4179 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4180 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4181 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004182
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004183 Cursors[I] = cursor;
4184 }
4185 // Scan the tokens that are at the end of the cursor, but are not captured
4186 // but the child cursors.
4187 for (unsigned I = AfterChildren; I != Last; ++I)
4188 Cursors[I] = cursor;
4189
4190 TokIdx = Last;
4191 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004192}
4193
Ted Kremenek6db61092010-05-05 00:55:15 +00004194static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4195 CXCursor parent,
4196 CXClientData client_data) {
4197 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4198}
4199
Ted Kremenekab979612010-11-11 08:05:23 +00004200// This gets run a separate thread to avoid stack blowout.
4201static void runAnnotateTokensWorker(void *UserData) {
4202 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4203}
4204
Ted Kremenek6db61092010-05-05 00:55:15 +00004205extern "C" {
4206
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004207void clang_annotateTokens(CXTranslationUnit TU,
4208 CXToken *Tokens, unsigned NumTokens,
4209 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004210
4211 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004212 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004213
Douglas Gregor4419b672010-10-21 06:10:04 +00004214 // Any token we don't specifically annotate will have a NULL cursor.
4215 CXCursor C = clang_getNullCursor();
4216 for (unsigned I = 0; I != NumTokens; ++I)
4217 Cursors[I] = C;
4218
Ted Kremeneka60ed472010-11-16 08:15:36 +00004219 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004220 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004221 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004222
Douglas Gregorbdf60622010-03-05 21:16:25 +00004223 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004224
Douglas Gregor0396f462010-03-19 05:22:59 +00004225 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004226 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4228 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004229 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4230 clang_getTokenLocation(TU,
4231 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232
Douglas Gregor0396f462010-03-19 05:22:59 +00004233 // A mapping from the source locations found when re-lexing or traversing the
4234 // region of interest to the corresponding cursors.
4235 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004236
4237 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004238 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004239 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4240 std::pair<FileID, unsigned> BeginLocInfo
4241 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4242 std::pair<FileID, unsigned> EndLocInfo
4243 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004244
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004245 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004246 bool Invalid = false;
4247 if (BeginLocInfo.first == EndLocInfo.first &&
4248 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4249 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004250 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4251 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004253 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004254 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004255
4256 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004257 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004258 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004259 Token Tok;
4260 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004261
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004262 reprocess:
4263 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4264 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004265 // don't see it while preprocessing these tokens later, but keep track
4266 // of all of the token locations inside this preprocessing directive so
4267 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004268 //
4269 // FIXME: Some simple tests here could identify macro definitions and
4270 // #undefs, to provide specific cursor kinds for those.
4271 std::vector<SourceLocation> Locations;
4272 do {
4273 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004274 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004275 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004276
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004277 using namespace cxcursor;
4278 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4280 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004281 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004282 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4283 Annotated[Locations[I].getRawEncoding()] = Cursor;
4284 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004286 if (Tok.isAtStartOfLine())
4287 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004288
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004289 continue;
4290 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004291
Douglas Gregor48072312010-03-18 15:23:44 +00004292 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004293 break;
4294 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004295 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004296
Douglas Gregor0396f462010-03-19 05:22:59 +00004297 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004298 // a specific cursor.
4299 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004300 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004301
4302 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004303 // FIXME: We use a ridiculous stack size here because the data-recursion
4304 // algorithm uses a large stack frame than the non-data recursive version,
4305 // and AnnotationTokensWorker currently transforms the data-recursion
4306 // algorithm back into a traditional recursion by explicitly calling
4307 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004308 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004309 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4310 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004311 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4312 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004313}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004314} // end: extern "C"
4315
4316//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004317// Operations for querying linkage of a cursor.
4318//===----------------------------------------------------------------------===//
4319
4320extern "C" {
4321CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004322 if (!clang_isDeclaration(cursor.kind))
4323 return CXLinkage_Invalid;
4324
Ted Kremenek16b42592010-03-03 06:36:57 +00004325 Decl *D = cxcursor::getCursorDecl(cursor);
4326 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4327 switch (ND->getLinkage()) {
4328 case NoLinkage: return CXLinkage_NoLinkage;
4329 case InternalLinkage: return CXLinkage_Internal;
4330 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4331 case ExternalLinkage: return CXLinkage_External;
4332 };
4333
4334 return CXLinkage_Invalid;
4335}
4336} // end: extern "C"
4337
4338//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004339// Operations for querying language of a cursor.
4340//===----------------------------------------------------------------------===//
4341
4342static CXLanguageKind getDeclLanguage(const Decl *D) {
4343 switch (D->getKind()) {
4344 default:
4345 break;
4346 case Decl::ImplicitParam:
4347 case Decl::ObjCAtDefsField:
4348 case Decl::ObjCCategory:
4349 case Decl::ObjCCategoryImpl:
4350 case Decl::ObjCClass:
4351 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004352 case Decl::ObjCForwardProtocol:
4353 case Decl::ObjCImplementation:
4354 case Decl::ObjCInterface:
4355 case Decl::ObjCIvar:
4356 case Decl::ObjCMethod:
4357 case Decl::ObjCProperty:
4358 case Decl::ObjCPropertyImpl:
4359 case Decl::ObjCProtocol:
4360 return CXLanguage_ObjC;
4361 case Decl::CXXConstructor:
4362 case Decl::CXXConversion:
4363 case Decl::CXXDestructor:
4364 case Decl::CXXMethod:
4365 case Decl::CXXRecord:
4366 case Decl::ClassTemplate:
4367 case Decl::ClassTemplatePartialSpecialization:
4368 case Decl::ClassTemplateSpecialization:
4369 case Decl::Friend:
4370 case Decl::FriendTemplate:
4371 case Decl::FunctionTemplate:
4372 case Decl::LinkageSpec:
4373 case Decl::Namespace:
4374 case Decl::NamespaceAlias:
4375 case Decl::NonTypeTemplateParm:
4376 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004377 case Decl::TemplateTemplateParm:
4378 case Decl::TemplateTypeParm:
4379 case Decl::UnresolvedUsingTypename:
4380 case Decl::UnresolvedUsingValue:
4381 case Decl::Using:
4382 case Decl::UsingDirective:
4383 case Decl::UsingShadow:
4384 return CXLanguage_CPlusPlus;
4385 }
4386
4387 return CXLanguage_C;
4388}
4389
4390extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004391
4392enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4393 if (clang_isDeclaration(cursor.kind))
4394 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4395 if (D->hasAttr<UnavailableAttr>() ||
4396 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4397 return CXAvailability_Available;
4398
4399 if (D->hasAttr<DeprecatedAttr>())
4400 return CXAvailability_Deprecated;
4401 }
4402
4403 return CXAvailability_Available;
4404}
4405
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004406CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4407 if (clang_isDeclaration(cursor.kind))
4408 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4409
4410 return CXLanguage_Invalid;
4411}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004412
4413CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4414 if (clang_isDeclaration(cursor.kind)) {
4415 if (Decl *D = getCursorDecl(cursor)) {
4416 DeclContext *DC = D->getDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004417 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004418 }
4419 }
4420
4421 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4422 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004423 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004424 }
4425
4426 return clang_getNullCursor();
4427}
4428
4429CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4430 if (clang_isDeclaration(cursor.kind)) {
4431 if (Decl *D = getCursorDecl(cursor)) {
4432 DeclContext *DC = D->getLexicalDeclContext();
Ted Kremeneka60ed472010-11-16 08:15:36 +00004433 return MakeCXCursor(cast<Decl>(DC), getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004434 }
4435 }
4436
4437 // FIXME: Note that we can't easily compute the lexical context of a
4438 // statement or expression, so we return nothing.
4439 return clang_getNullCursor();
4440}
4441
Douglas Gregor9f592342010-10-01 20:25:15 +00004442static void CollectOverriddenMethods(DeclContext *Ctx,
4443 ObjCMethodDecl *Method,
4444 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4445 if (!Ctx)
4446 return;
4447
4448 // If we have a class or category implementation, jump straight to the
4449 // interface.
4450 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4451 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4452
4453 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4454 if (!Container)
4455 return;
4456
4457 // Check whether we have a matching method at this level.
4458 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4459 Method->isInstanceMethod()))
4460 if (Method != Overridden) {
4461 // We found an override at this level; there is no need to look
4462 // into other protocols or categories.
4463 Methods.push_back(Overridden);
4464 return;
4465 }
4466
4467 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4468 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4469 PEnd = Protocol->protocol_end();
4470 P != PEnd; ++P)
4471 CollectOverriddenMethods(*P, Method, Methods);
4472 }
4473
4474 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4475 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4476 PEnd = Category->protocol_end();
4477 P != PEnd; ++P)
4478 CollectOverriddenMethods(*P, Method, Methods);
4479 }
4480
4481 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4482 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4483 PEnd = Interface->protocol_end();
4484 P != PEnd; ++P)
4485 CollectOverriddenMethods(*P, Method, Methods);
4486
4487 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4488 Category; Category = Category->getNextClassCategory())
4489 CollectOverriddenMethods(Category, Method, Methods);
4490
4491 // We only look into the superclass if we haven't found anything yet.
4492 if (Methods.empty())
4493 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4494 return CollectOverriddenMethods(Super, Method, Methods);
4495 }
4496}
4497
4498void clang_getOverriddenCursors(CXCursor cursor,
4499 CXCursor **overridden,
4500 unsigned *num_overridden) {
4501 if (overridden)
4502 *overridden = 0;
4503 if (num_overridden)
4504 *num_overridden = 0;
4505 if (!overridden || !num_overridden)
4506 return;
4507
4508 if (!clang_isDeclaration(cursor.kind))
4509 return;
4510
4511 Decl *D = getCursorDecl(cursor);
4512 if (!D)
4513 return;
4514
4515 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004516 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004517 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4518 *num_overridden = CXXMethod->size_overridden_methods();
4519 if (!*num_overridden)
4520 return;
4521
4522 *overridden = new CXCursor [*num_overridden];
4523 unsigned I = 0;
4524 for (CXXMethodDecl::method_iterator
4525 M = CXXMethod->begin_overridden_methods(),
4526 MEnd = CXXMethod->end_overridden_methods();
4527 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004528 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004529 return;
4530 }
4531
4532 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4533 if (!Method)
4534 return;
4535
4536 // Handle Objective-C methods.
4537 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4538 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4539
4540 if (Methods.empty())
4541 return;
4542
4543 *num_overridden = Methods.size();
4544 *overridden = new CXCursor [Methods.size()];
4545 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004546 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004547}
4548
4549void clang_disposeOverriddenCursors(CXCursor *overridden) {
4550 delete [] overridden;
4551}
4552
Douglas Gregorecdcb882010-10-20 22:00:55 +00004553CXFile clang_getIncludedFile(CXCursor cursor) {
4554 if (cursor.kind != CXCursor_InclusionDirective)
4555 return 0;
4556
4557 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4558 return (void *)ID->getFile();
4559}
4560
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004561} // end: extern "C"
4562
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004563
4564//===----------------------------------------------------------------------===//
4565// C++ AST instrospection.
4566//===----------------------------------------------------------------------===//
4567
4568extern "C" {
4569unsigned clang_CXXMethod_isStatic(CXCursor C) {
4570 if (!clang_isDeclaration(C.kind))
4571 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004572
4573 CXXMethodDecl *Method = 0;
4574 Decl *D = cxcursor::getCursorDecl(C);
4575 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4576 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4577 else
4578 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4579 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004580}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004581
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004582} // end: extern "C"
4583
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004584//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004585// Attribute introspection.
4586//===----------------------------------------------------------------------===//
4587
4588extern "C" {
4589CXType clang_getIBOutletCollectionType(CXCursor C) {
4590 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004591 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004592
4593 IBOutletCollectionAttr *A =
4594 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4595
Ted Kremeneka60ed472010-11-16 08:15:36 +00004596 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004597}
4598} // end: extern "C"
4599
4600//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004601// Misc. utility functions.
4602//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004603
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004604/// Default to using an 8 MB stack size on "safety" threads.
4605static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004606
4607namespace clang {
4608
4609bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004610 void (*Fn)(void*), void *UserData,
4611 unsigned Size) {
4612 if (!Size)
4613 Size = GetSafetyThreadStackSize();
4614 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004615 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4616 return CRC.RunSafely(Fn, UserData);
4617}
4618
4619unsigned GetSafetyThreadStackSize() {
4620 return SafetyStackThreadSize;
4621}
4622
4623void SetSafetyThreadStackSize(unsigned Value) {
4624 SafetyStackThreadSize = Value;
4625}
4626
4627}
4628
Ted Kremenek04bb7162010-01-22 22:44:15 +00004629extern "C" {
4630
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004631CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004632 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004633}
4634
4635} // end: extern "C"