blob: 72d930ef9e247cd7b30d7806ff54d31376fce129 [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 Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000033#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000034#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000036#include "llvm/ADT/Optional.h"
37#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000038#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000039#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000040#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000042#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000043#include "llvm/Support/Mutex.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000047#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000048
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Ted Kremeneka60ed472010-11-16 08:15:36 +000053static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
54 if (!TU)
55 return 0;
56 CXTranslationUnit D = new CXTranslationUnitImpl();
57 D->TUData = TU;
58 D->StringPool = createCXStringPool();
59 return D;
60}
61
Douglas Gregor33e9abd2010-01-22 19:49:59 +000062/// \brief The result of comparing two source ranges.
63enum RangeComparisonResult {
64 /// \brief Either the ranges overlap or one of the ranges is invalid.
65 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000066
Douglas Gregor33e9abd2010-01-22 19:49:59 +000067 /// \brief The first range ends before the second range starts.
68 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000069
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070 /// \brief The first range starts after the second range ends.
71 RangeAfter
72};
73
Ted Kremenekf0e23e82010-02-17 00:41:40 +000074/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000075/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076static RangeComparisonResult RangeCompare(SourceManager &SM,
77 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078 SourceRange R2) {
79 assert(R1.isValid() && "First range is invalid?");
80 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000081 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000082 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000083 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000085 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 return RangeAfter;
87 return RangeOverlap;
88}
89
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000090/// \brief Determine if a source location falls within, before, or after a
91/// a given source range.
92static RangeComparisonResult LocationCompare(SourceManager &SM,
93 SourceLocation L, SourceRange R) {
94 assert(R.isValid() && "First range is invalid?");
95 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000096 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000097 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
99 return RangeBefore;
100 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
101 return RangeAfter;
102 return RangeOverlap;
103}
104
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105/// \brief Translate a Clang source range into a CIndex source range.
106///
107/// Clang internally represents ranges where the end location points to the
108/// start of the token at the end. However, for external clients it is more
109/// useful to have a CXSourceRange be a proper half-open interval. This routine
110/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000111CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000113 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000115 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000117 if (EndLoc.isValid() && EndLoc.isMacroID())
118 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000119 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000120 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000121 EndLoc = EndLoc.getFileLocWithOffset(Length);
122 }
123
124 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
125 R.getBegin().getRawEncoding(),
126 EndLoc.getRawEncoding() };
127 return Result;
128}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000129
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
133
Steve Naroff89922f82009-08-31 00:59:03 +0000134namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000135
136class VisitorJob {
137public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000138 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000139 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000140 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000141 ExplicitTemplateArgsVisitKind,
142 NestedNameSpecifierVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000143 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000144 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000145 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000146protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000147 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000148 CXCursor parent;
149 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000150 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
151 : parent(C), K(k) {
152 data[0] = d1;
153 data[1] = d2;
154 data[2] = d3;
155 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000156public:
157 Kind getKind() const { return K; }
158 const CXCursor &getParent() const { return parent; }
159 static bool classof(VisitorJob *VJ) { return true; }
160};
161
162typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
163
Douglas Gregorb1373d02010-01-20 20:59:29 +0000164// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000165class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000166 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000167{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000169 CXTranslationUnit TU;
170 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000171
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The declaration that serves at the parent of any statement or
176 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000177 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000178
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000179 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000180 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000181
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000183 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000184
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000185 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
186 // to the visitor. Declarations with a PCH level greater than this value will
187 // be suppressed.
188 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000189
190 /// \brief When valid, a source range to which the cursor should restrict
191 /// its search.
192 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000194 // FIXME: Eventually remove. This part of a hack to support proper
195 // iteration over all Decls contained lexically within an ObjC container.
196 DeclContext::decl_iterator *DI_current;
197 DeclContext::decl_iterator DE_current;
198
Ted Kremenekd1ded662010-11-15 23:31:32 +0000199 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
200 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
201 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
206 /// \brief Determine whether this particular source range comes before, comes
207 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000209 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
211
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000212 class SetParentRAII {
213 CXCursor &Parent;
214 Decl *&StmtParent;
215 CXCursor OldParent;
216
217 public:
218 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
219 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
220 {
221 Parent = NewParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225
226 ~SetParentRAII() {
227 Parent = OldParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231 };
232
Steve Naroff89922f82009-08-31 00:59:03 +0000233public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000234 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
235 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000238 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
239 Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000240 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
241 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 {
243 Parent.kind = CXCursor_NoDeclFound;
244 Parent.data[0] = 0;
245 Parent.data[1] = 0;
246 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000249
Ted Kremenekd1ded662010-11-15 23:31:32 +0000250 ~CursorVisitor() {
251 // Free the pre-allocated worklists for data-recursion.
252 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
253 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
254 delete *I;
255 }
256 }
257
Ted Kremeneka60ed472010-11-16 08:15:36 +0000258 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
259 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000260
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000261 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000262
263 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
264 getPreprocessedEntities();
265
Douglas Gregorb1373d02010-01-20 20:59:29 +0000266 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000267
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000268 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000269 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000270 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000271 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000272 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000274 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
275 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000276 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000277 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000278 bool VisitClassTemplatePartialSpecializationDecl(
279 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000280 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000281 bool VisitEnumConstantDecl(EnumConstantDecl *D);
282 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
283 bool VisitFunctionDecl(FunctionDecl *ND);
284 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000285 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000286 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000287 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000288 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000289 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000290 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
291 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
292 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
293 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000294 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000295 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
296 bool VisitObjCImplDecl(ObjCImplDecl *D);
297 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
298 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000299 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
300 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
301 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000302 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000303 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000304 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000305 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000306 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000307 bool VisitUsingDecl(UsingDecl *D);
308 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
309 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000310
Douglas Gregor01829d32010-08-31 14:41:23 +0000311 // Name visitor
312 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000313 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000314 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000315
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000316 // Template visitors
317 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000318 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000319 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
320
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000321 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000322 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000324 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000325 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
326 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000327 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000329 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000331 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000332 bool VisitPointerTypeLoc(PointerTypeLoc TL);
333 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
334 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
335 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
336 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000337 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000339 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000340 // FIXME: Implement visitors here when the unimplemented TypeLocs get
341 // implemented
342 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000343 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000344 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000345 bool VisitDependentNameTypeLoc(DependentNameTypeLoc TL);
346
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000347 // Data-recursive visitor functions.
348 bool IsInRegionOfInterest(CXCursor C);
349 bool RunVisitorWorkList(VisitorWorkList &WL);
350 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000351 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000352};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000353
Ted Kremenekab188932010-01-05 19:32:54 +0000354} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000355
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000356static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000357static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
358
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000359
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000360RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000361 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362}
363
Douglas Gregorb1373d02010-01-20 20:59:29 +0000364/// \brief Visit the given cursor and, if requested by the visitor,
365/// its children.
366///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367/// \param Cursor the cursor to visit.
368///
369/// \param CheckRegionOfInterest if true, then the caller already checked that
370/// this cursor is within the region of interest.
371///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372/// \returns true if the visitation should be aborted, false if it
373/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375 if (clang_isInvalid(Cursor.kind))
376 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000377
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378 if (clang_isDeclaration(Cursor.kind)) {
379 Decl *D = getCursorDecl(Cursor);
380 assert(D && "Invalid declaration cursor");
381 if (D->getPCHLevel() > MaxPCHLevel)
382 return false;
383
384 if (D->isImplicit())
385 return false;
386 }
387
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388 // If we have a range of interest, and this cursor doesn't intersect with it,
389 // we're done.
390 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000391 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000392 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 return false;
394 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000395
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 switch (Visitor(Cursor, Parent, ClientData)) {
397 case CXChildVisit_Break:
398 return true;
399
400 case CXChildVisit_Continue:
401 return false;
402
403 case CXChildVisit_Recurse:
404 return VisitChildren(Cursor);
405 }
406
Douglas Gregorfd643772010-01-25 16:45:46 +0000407 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408}
409
Douglas Gregor788f5a12010-03-20 00:41:21 +0000410std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
411CursorVisitor::getPreprocessedEntities() {
412 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000413 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000414
415 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000416 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
417
418 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
419 // If we would only look at local declarations but we have a region of
420 // interest, check whether that region of interest is in the main file.
421 // If not, we should traverse all declarations.
422 // FIXME: My kingdom for a proper binary search approach to finding
423 // cursors!
424 std::pair<FileID, unsigned> Location
425 = AU->getSourceManager().getDecomposedInstantiationLoc(
426 RegionOfInterest.getBegin());
427 if (Location.first != AU->getSourceManager().getMainFileID())
428 OnlyLocalDecls = false;
429 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000430
Douglas Gregor89d99802010-11-30 06:16:57 +0000431 PreprocessingRecord::iterator StartEntity, EndEntity;
432 if (OnlyLocalDecls) {
433 StartEntity = AU->pp_entity_begin();
434 EndEntity = AU->pp_entity_end();
435 } else {
436 StartEntity = PPRec.begin();
437 EndEntity = PPRec.end();
438 }
439
Douglas Gregor788f5a12010-03-20 00:41:21 +0000440 // There is no region of interest; we have to walk everything.
441 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000442 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000443
444 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000445 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000446 std::pair<FileID, unsigned> Begin
447 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
448 std::pair<FileID, unsigned> End
449 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
450
451 // The region of interest spans files; we have to walk everything.
452 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000453 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000454
455 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000456 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000457 if (ByFileMap.empty()) {
458 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000459 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000460 std::pair<FileID, unsigned> P
461 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000462
Douglas Gregor788f5a12010-03-20 00:41:21 +0000463 ByFileMap[P.first].push_back(*E);
464 }
465 }
466
467 return std::make_pair(ByFileMap[Begin.first].begin(),
468 ByFileMap[Begin.first].end());
469}
470
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000472///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473/// \returns true if the visitation should be aborted, false if it
474/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000475bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000476 if (clang_isReference(Cursor.kind)) {
477 // By definition, references have no children.
478 return false;
479 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000480
481 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000483 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000484
Douglas Gregorb1373d02010-01-20 20:59:29 +0000485 if (clang_isDeclaration(Cursor.kind)) {
486 Decl *D = getCursorDecl(Cursor);
487 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000488 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000490
Douglas Gregora59e3902010-01-21 23:27:09 +0000491 if (clang_isStatement(Cursor.kind))
492 return Visit(getCursorStmt(Cursor));
493 if (clang_isExpression(Cursor.kind))
494 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000497 CXTranslationUnit tu = getCursorTU(Cursor);
498 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000499 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
500 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000501 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
502 TLEnd = CXXUnit->top_level_end();
503 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000504 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000505 return true;
506 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 } else if (VisitDeclContext(
508 CXXUnit->getASTContext().getTranslationUnitDecl()))
509 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000510
Douglas Gregor0396f462010-03-19 05:22:59 +0000511 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000512 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000513 // FIXME: Once we have the ability to deserialize a preprocessing record,
514 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000515 PreprocessingRecord::iterator E, EEnd;
516 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000518 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000519 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000520
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 continue;
522 }
523
524 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000525 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000526 return true;
527
528 continue;
529 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000530
531 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000532 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000533 return true;
534
535 continue;
536 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000537 }
538 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000539 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000541
Douglas Gregorb1373d02010-01-20 20:59:29 +0000542 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000543 return false;
544}
545
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000546bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000547 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
548 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000549
Ted Kremenek664cffd2010-07-22 11:30:19 +0000550 if (Stmt *Body = B->getBody())
551 return Visit(MakeCXCursor(Body, StmtParent, TU));
552
553 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000554}
555
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000556llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
557 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000558 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000559 if (Range.isInvalid())
560 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000561
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000562 switch (CompareRegionOfInterest(Range)) {
563 case RangeBefore:
564 // This declaration comes before the region of interest; skip it.
565 return llvm::Optional<bool>();
566
567 case RangeAfter:
568 // This declaration comes after the region of interest; we're done.
569 return false;
570
571 case RangeOverlap:
572 // This declaration overlaps the region of interest; visit it.
573 break;
574 }
575 }
576 return true;
577}
578
579bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
580 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
581
582 // FIXME: Eventually remove. This part of a hack to support proper
583 // iteration over all Decls contained lexically within an ObjC container.
584 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
585 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
586
587 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000588 Decl *D = *I;
589 if (D->getLexicalDeclContext() != DC)
590 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000591 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000592 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
593 if (!V.hasValue())
594 continue;
595 if (!V.getValue())
596 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000597 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000598 return true;
599 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000600 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000601}
602
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000603bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
604 llvm_unreachable("Translation units are visited directly by Visit()");
605 return false;
606}
607
608bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
609 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
610 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000611
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000612 return false;
613}
614
615bool CursorVisitor::VisitTagDecl(TagDecl *D) {
616 return VisitDeclContext(D);
617}
618
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000619bool CursorVisitor::VisitClassTemplateSpecializationDecl(
620 ClassTemplateSpecializationDecl *D) {
621 bool ShouldVisitBody = false;
622 switch (D->getSpecializationKind()) {
623 case TSK_Undeclared:
624 case TSK_ImplicitInstantiation:
625 // Nothing to visit
626 return false;
627
628 case TSK_ExplicitInstantiationDeclaration:
629 case TSK_ExplicitInstantiationDefinition:
630 break;
631
632 case TSK_ExplicitSpecialization:
633 ShouldVisitBody = true;
634 break;
635 }
636
637 // Visit the template arguments used in the specialization.
638 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
639 TypeLoc TL = SpecType->getTypeLoc();
640 if (TemplateSpecializationTypeLoc *TSTLoc
641 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
642 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
643 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
644 return true;
645 }
646 }
647
648 if (ShouldVisitBody && VisitCXXRecordDecl(D))
649 return true;
650
651 return false;
652}
653
Douglas Gregor74dbe642010-08-31 19:31:58 +0000654bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
655 ClassTemplatePartialSpecializationDecl *D) {
656 // FIXME: Visit the "outer" template parameter lists on the TagDecl
657 // before visiting these template parameters.
658 if (VisitTemplateParameters(D->getTemplateParameters()))
659 return true;
660
661 // Visit the partial specialization arguments.
662 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
663 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
664 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
665 return true;
666
667 return VisitCXXRecordDecl(D);
668}
669
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000670bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000671 // Visit the default argument.
672 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
673 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
674 if (Visit(DefArg->getTypeLoc()))
675 return true;
676
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000677 return false;
678}
679
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000680bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
681 if (Expr *Init = D->getInitExpr())
682 return Visit(MakeCXCursor(Init, StmtParent, TU));
683 return false;
684}
685
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000686bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
687 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
688 if (Visit(TSInfo->getTypeLoc()))
689 return true;
690
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000691 // Visit the nested-name-specifier, if present.
692 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
693 if (VisitNestedNameSpecifierLoc(QualifierLoc))
694 return true;
695
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000696 return false;
697}
698
Douglas Gregora67e03f2010-09-09 21:42:20 +0000699/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000700static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
701 CXXCtorInitializer const * const *X
702 = static_cast<CXXCtorInitializer const * const *>(Xp);
703 CXXCtorInitializer const * const *Y
704 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000705
706 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
707 return -1;
708 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
709 return 1;
710 else
711 return 0;
712}
713
Douglas Gregorb1373d02010-01-20 20:59:29 +0000714bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000715 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
716 // Visit the function declaration's syntactic components in the order
717 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000718 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000719 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
720
721 // If we have a function declared directly (without the use of a typedef),
722 // visit just the return type. Otherwise, just visit the function's type
723 // now.
724 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
725 (!FTL && Visit(TL)))
726 return true;
727
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000728 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000729 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
730 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000731 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000732
733 // Visit the declaration name.
734 if (VisitDeclarationNameInfo(ND->getNameInfo()))
735 return true;
736
737 // FIXME: Visit explicitly-specified template arguments!
738
739 // Visit the function parameters, if we have a function type.
740 if (FTL && VisitFunctionTypeLoc(*FTL, true))
741 return true;
742
743 // FIXME: Attributes?
744 }
745
Douglas Gregora67e03f2010-09-09 21:42:20 +0000746 if (ND->isThisDeclarationADefinition()) {
747 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
748 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000749 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000750 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
751 IEnd = Constructor->init_end();
752 I != IEnd; ++I) {
753 if (!(*I)->isWritten())
754 continue;
755
756 WrittenInits.push_back(*I);
757 }
758
759 // Sort the initializers in source order
760 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000761 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000762
763 // Visit the initializers in source order
764 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000765 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000766 if (Init->isAnyMemberInitializer()) {
767 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000768 Init->getMemberLocation(), TU)))
769 return true;
770 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
771 if (Visit(BaseInfo->getTypeLoc()))
772 return true;
773 }
774
775 // Visit the initializer value.
776 if (Expr *Initializer = Init->getInit())
777 if (Visit(MakeCXCursor(Initializer, ND, TU)))
778 return true;
779 }
780 }
781
782 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
783 return true;
784 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregorb1373d02010-01-20 20:59:29 +0000786 return false;
787}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000788
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000789bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
790 if (VisitDeclaratorDecl(D))
791 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000792
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000793 if (Expr *BitWidth = D->getBitWidth())
794 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000795
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796 return false;
797}
798
799bool CursorVisitor::VisitVarDecl(VarDecl *D) {
800 if (VisitDeclaratorDecl(D))
801 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000803 if (Expr *Init = D->getInit())
804 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000806 return false;
807}
808
Douglas Gregor84b51d72010-09-01 20:16:53 +0000809bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
810 if (VisitDeclaratorDecl(D))
811 return true;
812
813 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
814 if (Expr *DefArg = D->getDefaultArgument())
815 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
816
817 return false;
818}
819
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000820bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
821 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
822 // before visiting these template parameters.
823 if (VisitTemplateParameters(D->getTemplateParameters()))
824 return true;
825
826 return VisitFunctionDecl(D->getTemplatedDecl());
827}
828
Douglas Gregor39d6f072010-08-31 19:02:00 +0000829bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
830 // FIXME: Visit the "outer" template parameter lists on the TagDecl
831 // before visiting these template parameters.
832 if (VisitTemplateParameters(D->getTemplateParameters()))
833 return true;
834
835 return VisitCXXRecordDecl(D->getTemplatedDecl());
836}
837
Douglas Gregor84b51d72010-09-01 20:16:53 +0000838bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
839 if (VisitTemplateParameters(D->getTemplateParameters()))
840 return true;
841
842 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
843 VisitTemplateArgumentLoc(D->getDefaultArgument()))
844 return true;
845
846 return false;
847}
848
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000850 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
851 if (Visit(TSInfo->getTypeLoc()))
852 return true;
853
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000854 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855 PEnd = ND->param_end();
856 P != PEnd; ++P) {
857 if (Visit(MakeCXCursor(*P, TU)))
858 return true;
859 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000860
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000861 if (ND->isThisDeclarationADefinition() &&
862 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
863 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000864
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000865 return false;
866}
867
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000868namespace {
869 struct ContainerDeclsSort {
870 SourceManager &SM;
871 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
872 bool operator()(Decl *A, Decl *B) {
873 SourceLocation L_A = A->getLocStart();
874 SourceLocation L_B = B->getLocStart();
875 assert(L_A.isValid() && L_B.isValid());
876 return SM.isBeforeInTranslationUnit(L_A, L_B);
877 }
878 };
879}
880
Douglas Gregora59e3902010-01-21 23:27:09 +0000881bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000882 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
883 // an @implementation can lexically contain Decls that are not properly
884 // nested in the AST. When we identify such cases, we need to retrofit
885 // this nesting here.
886 if (!DI_current)
887 return VisitDeclContext(D);
888
889 // Scan the Decls that immediately come after the container
890 // in the current DeclContext. If any fall within the
891 // container's lexical region, stash them into a vector
892 // for later processing.
893 llvm::SmallVector<Decl *, 24> DeclsInContainer;
894 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000895 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000896 if (EndLoc.isValid()) {
897 DeclContext::decl_iterator next = *DI_current;
898 while (++next != DE_current) {
899 Decl *D_next = *next;
900 if (!D_next)
901 break;
902 SourceLocation L = D_next->getLocStart();
903 if (!L.isValid())
904 break;
905 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
906 *DI_current = next;
907 DeclsInContainer.push_back(D_next);
908 continue;
909 }
910 break;
911 }
912 }
913
914 // The common case.
915 if (DeclsInContainer.empty())
916 return VisitDeclContext(D);
917
918 // Get all the Decls in the DeclContext, and sort them with the
919 // additional ones we've collected. Then visit them.
920 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
921 I!=E; ++I) {
922 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000923 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
924 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000925 continue;
926 DeclsInContainer.push_back(subDecl);
927 }
928
929 // Now sort the Decls so that they appear in lexical order.
930 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
931 ContainerDeclsSort(SM));
932
933 // Now visit the decls.
934 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
935 E = DeclsInContainer.end(); I != E; ++I) {
936 CXCursor Cursor = MakeCXCursor(*I, TU);
937 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
938 if (!V.hasValue())
939 continue;
940 if (!V.getValue())
941 return false;
942 if (Visit(Cursor, true))
943 return true;
944 }
945 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000946}
947
Douglas Gregorb1373d02010-01-20 20:59:29 +0000948bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000949 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
950 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000951 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000952
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000953 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
954 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
955 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000956 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000957 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000958
Douglas Gregora59e3902010-01-21 23:27:09 +0000959 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000960}
961
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000962bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
963 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
964 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
965 E = PID->protocol_end(); I != E; ++I, ++PL)
966 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
967 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000968
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000969 return VisitObjCContainerDecl(PID);
970}
971
Ted Kremenek23173d72010-05-18 21:09:07 +0000972bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000973 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000974 return true;
975
Ted Kremenek23173d72010-05-18 21:09:07 +0000976 // FIXME: This implements a workaround with @property declarations also being
977 // installed in the DeclContext for the @interface. Eventually this code
978 // should be removed.
979 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
980 if (!CDecl || !CDecl->IsClassExtension())
981 return false;
982
983 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
984 if (!ID)
985 return false;
986
987 IdentifierInfo *PropertyId = PD->getIdentifier();
988 ObjCPropertyDecl *prevDecl =
989 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
990
991 if (!prevDecl)
992 return false;
993
994 // Visit synthesized methods since they will be skipped when visiting
995 // the @interface.
996 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000997 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000998 if (Visit(MakeCXCursor(MD, TU)))
999 return true;
1000
1001 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001002 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001003 if (Visit(MakeCXCursor(MD, TU)))
1004 return true;
1005
1006 return false;
1007}
1008
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001010 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001011 if (D->getSuperClass() &&
1012 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001014 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001017 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1018 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1019 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001020 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001021 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001022
Douglas Gregora59e3902010-01-21 23:27:09 +00001023 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001024}
1025
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1027 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001028}
1029
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001030bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001031 // 'ID' could be null when dealing with invalid code.
1032 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1033 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1034 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001035
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001036 return VisitObjCImplDecl(D);
1037}
1038
1039bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1040#if 0
1041 // Issue callbacks for super class.
1042 // FIXME: No source location information!
1043 if (D->getSuperClass() &&
1044 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001045 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001046 TU)))
1047 return true;
1048#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001049
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001050 return VisitObjCImplDecl(D);
1051}
1052
1053bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1054 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1055 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1056 E = D->protocol_end();
1057 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001058 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001059 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
1061 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001062}
1063
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001064bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1065 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1066 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1067 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001068
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001069 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001070}
1071
Douglas Gregora4ffd852010-11-17 01:03:52 +00001072bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1073 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1074 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1075
1076 return false;
1077}
1078
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001079bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1080 return VisitDeclContext(D);
1081}
1082
Douglas Gregor69319002010-08-31 23:48:11 +00001083bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001084 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001085 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1086 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001088
1089 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1090 D->getTargetNameLoc(), TU));
1091}
1092
Douglas Gregor7e242562010-09-01 19:52:22 +00001093bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001094 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001095 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1096 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001097 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001098 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001099
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001100 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1101 return true;
1102
Douglas Gregor7e242562010-09-01 19:52:22 +00001103 return VisitDeclarationNameInfo(D->getNameInfo());
1104}
1105
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001106bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001107 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001108 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1109 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001111
1112 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1113 D->getIdentLocation(), TU));
1114}
1115
Douglas Gregor7e242562010-09-01 19:52:22 +00001116bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001117 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001118 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1119 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001121 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001122
Douglas Gregor7e242562010-09-01 19:52:22 +00001123 return VisitDeclarationNameInfo(D->getNameInfo());
1124}
1125
1126bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1127 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001128 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001129 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1130 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001131 return true;
1132
Douglas Gregor7e242562010-09-01 19:52:22 +00001133 return false;
1134}
1135
Douglas Gregor01829d32010-08-31 14:41:23 +00001136bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1137 switch (Name.getName().getNameKind()) {
1138 case clang::DeclarationName::Identifier:
1139 case clang::DeclarationName::CXXLiteralOperatorName:
1140 case clang::DeclarationName::CXXOperatorName:
1141 case clang::DeclarationName::CXXUsingDirective:
1142 return false;
1143
1144 case clang::DeclarationName::CXXConstructorName:
1145 case clang::DeclarationName::CXXDestructorName:
1146 case clang::DeclarationName::CXXConversionFunctionName:
1147 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1148 return Visit(TSInfo->getTypeLoc());
1149 return false;
1150
1151 case clang::DeclarationName::ObjCZeroArgSelector:
1152 case clang::DeclarationName::ObjCOneArgSelector:
1153 case clang::DeclarationName::ObjCMultiArgSelector:
1154 // FIXME: Per-identifier location info?
1155 return false;
1156 }
1157
1158 return false;
1159}
1160
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001161bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1162 SourceRange Range) {
1163 // FIXME: This whole routine is a hack to work around the lack of proper
1164 // source information in nested-name-specifiers (PR5791). Since we do have
1165 // a beginning source location, we can visit the first component of the
1166 // nested-name-specifier, if it's a single-token component.
1167 if (!NNS)
1168 return false;
1169
1170 // Get the first component in the nested-name-specifier.
1171 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1172 NNS = Prefix;
1173
1174 switch (NNS->getKind()) {
1175 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001176 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1177 TU));
1178
Douglas Gregor14aba762011-02-24 02:36:08 +00001179 case NestedNameSpecifier::NamespaceAlias:
1180 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1181 Range.getBegin(), TU));
1182
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001183 case NestedNameSpecifier::TypeSpec: {
1184 // If the type has a form where we know that the beginning of the source
1185 // range matches up with a reference cursor. Visit the appropriate reference
1186 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001187 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001188 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1189 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1190 if (const TagType *Tag = dyn_cast<TagType>(T))
1191 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1192 if (const TemplateSpecializationType *TST
1193 = dyn_cast<TemplateSpecializationType>(T))
1194 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1195 break;
1196 }
1197
1198 case NestedNameSpecifier::TypeSpecWithTemplate:
1199 case NestedNameSpecifier::Global:
1200 case NestedNameSpecifier::Identifier:
1201 break;
1202 }
1203
1204 return false;
1205}
1206
Douglas Gregordc355712011-02-25 00:36:19 +00001207bool
1208CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1209 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1210 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1211 Qualifiers.push_back(Qualifier);
1212
1213 while (!Qualifiers.empty()) {
1214 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1215 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1216 switch (NNS->getKind()) {
1217 case NestedNameSpecifier::Namespace:
1218 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001219 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001220 TU)))
1221 return true;
1222
1223 break;
1224
1225 case NestedNameSpecifier::NamespaceAlias:
1226 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001227 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001228 TU)))
1229 return true;
1230
1231 break;
1232
1233 case NestedNameSpecifier::TypeSpec:
1234 case NestedNameSpecifier::TypeSpecWithTemplate:
1235 if (Visit(Q.getTypeLoc()))
1236 return true;
1237
1238 break;
1239
1240 case NestedNameSpecifier::Global:
1241 case NestedNameSpecifier::Identifier:
1242 break;
1243 }
1244 }
1245
1246 return false;
1247}
1248
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001249bool CursorVisitor::VisitTemplateParameters(
1250 const TemplateParameterList *Params) {
1251 if (!Params)
1252 return false;
1253
1254 for (TemplateParameterList::const_iterator P = Params->begin(),
1255 PEnd = Params->end();
1256 P != PEnd; ++P) {
1257 if (Visit(MakeCXCursor(*P, TU)))
1258 return true;
1259 }
1260
1261 return false;
1262}
1263
Douglas Gregor0b36e612010-08-31 20:37:03 +00001264bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1265 switch (Name.getKind()) {
1266 case TemplateName::Template:
1267 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1268
1269 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001270 // Visit the overloaded template set.
1271 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1272 return true;
1273
Douglas Gregor0b36e612010-08-31 20:37:03 +00001274 return false;
1275
1276 case TemplateName::DependentTemplate:
1277 // FIXME: Visit nested-name-specifier.
1278 return false;
1279
1280 case TemplateName::QualifiedTemplate:
1281 // FIXME: Visit nested-name-specifier.
1282 return Visit(MakeCursorTemplateRef(
1283 Name.getAsQualifiedTemplateName()->getDecl(),
1284 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001285
1286 case TemplateName::SubstTemplateTemplateParmPack:
1287 return Visit(MakeCursorTemplateRef(
1288 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1289 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001290 }
1291
1292 return false;
1293}
1294
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001295bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1296 switch (TAL.getArgument().getKind()) {
1297 case TemplateArgument::Null:
1298 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001299 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300 return false;
1301
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001302 case TemplateArgument::Type:
1303 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1304 return Visit(TSInfo->getTypeLoc());
1305 return false;
1306
1307 case TemplateArgument::Declaration:
1308 if (Expr *E = TAL.getSourceDeclExpression())
1309 return Visit(MakeCXCursor(E, StmtParent, TU));
1310 return false;
1311
1312 case TemplateArgument::Expression:
1313 if (Expr *E = TAL.getSourceExpression())
1314 return Visit(MakeCXCursor(E, StmtParent, TU));
1315 return false;
1316
1317 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001318 case TemplateArgument::TemplateExpansion:
1319 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001320 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001321 }
1322
1323 return false;
1324}
1325
Ted Kremeneka0536d82010-05-07 01:04:29 +00001326bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1327 return VisitDeclContext(D);
1328}
1329
Douglas Gregor01829d32010-08-31 14:41:23 +00001330bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1331 return Visit(TL.getUnqualifiedLoc());
1332}
1333
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001335 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001336
1337 // Some builtin types (such as Objective-C's "id", "sel", and
1338 // "Class") have associated declarations. Create cursors for those.
1339 QualType VisitType;
1340 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001341 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001342 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001343 case BuiltinType::Char_U:
1344 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001345 case BuiltinType::Char16:
1346 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001347 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348 case BuiltinType::UInt:
1349 case BuiltinType::ULong:
1350 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001351 case BuiltinType::UInt128:
1352 case BuiltinType::Char_S:
1353 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001354 case BuiltinType::WChar_U:
1355 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001356 case BuiltinType::Short:
1357 case BuiltinType::Int:
1358 case BuiltinType::Long:
1359 case BuiltinType::LongLong:
1360 case BuiltinType::Int128:
1361 case BuiltinType::Float:
1362 case BuiltinType::Double:
1363 case BuiltinType::LongDouble:
1364 case BuiltinType::NullPtr:
1365 case BuiltinType::Overload:
1366 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001368
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001369 case BuiltinType::ObjCId:
1370 VisitType = Context.getObjCIdType();
1371 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001372
1373 case BuiltinType::ObjCClass:
1374 VisitType = Context.getObjCClassType();
1375 break;
1376
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001377 case BuiltinType::ObjCSel:
1378 VisitType = Context.getObjCSelType();
1379 break;
1380 }
1381
1382 if (!VisitType.isNull()) {
1383 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385 TU));
1386 }
1387
1388 return false;
1389}
1390
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001391bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1392 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1393}
1394
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001395bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1396 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1397}
1398
1399bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1400 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1401}
1402
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001403bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001404 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001405 // no context information with which we can match up the depth/index in the
1406 // type to the appropriate
1407 return false;
1408}
1409
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001410bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1411 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1412 return true;
1413
John McCallc12c5bb2010-05-15 11:32:37 +00001414 return false;
1415}
1416
1417bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1418 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1419 return true;
1420
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001421 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1422 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1423 TU)))
1424 return true;
1425 }
1426
1427 return false;
1428}
1429
1430bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001431 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001432}
1433
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001434bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1435 return Visit(TL.getInnerLoc());
1436}
1437
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001438bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1439 return Visit(TL.getPointeeLoc());
1440}
1441
1442bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1443 return Visit(TL.getPointeeLoc());
1444}
1445
1446bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1447 return Visit(TL.getPointeeLoc());
1448}
1449
1450bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001451 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001452}
1453
1454bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001455 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001456}
1457
Douglas Gregor01829d32010-08-31 14:41:23 +00001458bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1459 bool SkipResultType) {
1460 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001461 return true;
1462
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001463 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001464 if (Decl *D = TL.getArg(I))
1465 if (Visit(MakeCXCursor(D, TU)))
1466 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001467
1468 return false;
1469}
1470
1471bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1472 if (Visit(TL.getElementLoc()))
1473 return true;
1474
1475 if (Expr *Size = TL.getSizeExpr())
1476 return Visit(MakeCXCursor(Size, StmtParent, TU));
1477
1478 return false;
1479}
1480
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001481bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1482 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001483 // Visit the template name.
1484 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1485 TL.getTemplateNameLoc()))
1486 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001487
1488 // Visit the template arguments.
1489 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1490 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1491 return true;
1492
1493 return false;
1494}
1495
Douglas Gregor2332c112010-01-21 20:48:56 +00001496bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1497 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1498}
1499
1500bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1501 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1502 return Visit(TSInfo->getTypeLoc());
1503
1504 return false;
1505}
1506
Douglas Gregor2494dd02011-03-01 01:34:45 +00001507bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1508 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1509 return true;
1510
1511 return false;
1512}
1513
Douglas Gregor7536dd52010-12-20 02:24:11 +00001514bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1515 return Visit(TL.getPatternLoc());
1516}
1517
Ted Kremenek3064ef92010-08-27 21:34:58 +00001518bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001519 // Visit the nested-name-specifier, if present.
1520 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1521 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1522 return true;
1523
Ted Kremenek3064ef92010-08-27 21:34:58 +00001524 if (D->isDefinition()) {
1525 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1526 E = D->bases_end(); I != E; ++I) {
1527 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1528 return true;
1529 }
1530 }
1531
1532 return VisitTagDecl(D);
1533}
1534
Ted Kremenek09dfa372010-02-18 05:46:33 +00001535bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001536 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1537 i != e; ++i)
1538 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001539 return true;
1540
1541 return false;
1542}
1543
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001544//===----------------------------------------------------------------------===//
1545// Data-recursive visitor methods.
1546//===----------------------------------------------------------------------===//
1547
Ted Kremenek28a71942010-11-13 00:36:47 +00001548namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001549#define DEF_JOB(NAME, DATA, KIND)\
1550class NAME : public VisitorJob {\
1551public:\
1552 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1553 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001554 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001555};
1556
1557DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1558DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001559DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001560DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001561DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1562 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001563DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001564#undef DEF_JOB
1565
1566class DeclVisit : public VisitorJob {
1567public:
1568 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1569 VisitorJob(parent, VisitorJob::DeclVisitKind,
1570 d, isFirst ? (void*) 1 : (void*) 0) {}
1571 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001572 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001573 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001574 Decl *get() const { return static_cast<Decl*>(data[0]); }
1575 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001576};
Ted Kremenek035dc412010-11-13 00:36:50 +00001577class TypeLocVisit : public VisitorJob {
1578public:
1579 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1580 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1581 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1582
1583 static bool classof(const VisitorJob *VJ) {
1584 return VJ->getKind() == TypeLocVisitKind;
1585 }
1586
Ted Kremenek82f3c502010-11-15 22:23:26 +00001587 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001588 QualType T = QualType::getFromOpaquePtr(data[0]);
1589 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001590 }
1591};
1592
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001593class LabelRefVisit : public VisitorJob {
1594public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001595 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1596 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001597 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001598
1599 static bool classof(const VisitorJob *VJ) {
1600 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1601 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001602 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001603 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001604 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001605};
1606class NestedNameSpecifierVisit : public VisitorJob {
1607public:
1608 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1609 CXCursor parent)
1610 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001611 NS, R.getBegin().getPtrEncoding(),
1612 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001613 static bool classof(const VisitorJob *VJ) {
1614 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1615 }
1616 NestedNameSpecifier *get() const {
1617 return static_cast<NestedNameSpecifier*>(data[0]);
1618 }
1619 SourceRange getSourceRange() const {
1620 SourceLocation A =
1621 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1622 SourceLocation B =
1623 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1624 return SourceRange(A, B);
1625 }
1626};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001627
1628class NestedNameSpecifierLocVisit : public VisitorJob {
1629public:
1630 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1631 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1632 Qualifier.getNestedNameSpecifier(),
1633 Qualifier.getOpaqueData()) { }
1634
1635 static bool classof(const VisitorJob *VJ) {
1636 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1637 }
1638
1639 NestedNameSpecifierLoc get() const {
1640 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1641 data[1]);
1642 }
1643};
1644
Ted Kremenekf64d8032010-11-18 00:02:32 +00001645class DeclarationNameInfoVisit : public VisitorJob {
1646public:
1647 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1648 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1649 static bool classof(const VisitorJob *VJ) {
1650 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1651 }
1652 DeclarationNameInfo get() const {
1653 Stmt *S = static_cast<Stmt*>(data[0]);
1654 switch (S->getStmtClass()) {
1655 default:
1656 llvm_unreachable("Unhandled Stmt");
1657 case Stmt::CXXDependentScopeMemberExprClass:
1658 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1659 case Stmt::DependentScopeDeclRefExprClass:
1660 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1661 }
1662 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001663};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001664class MemberRefVisit : public VisitorJob {
1665public:
1666 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1667 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001668 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001669 static bool classof(const VisitorJob *VJ) {
1670 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1671 }
1672 FieldDecl *get() const {
1673 return static_cast<FieldDecl*>(data[0]);
1674 }
1675 SourceLocation getLoc() const {
1676 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1677 }
1678};
Ted Kremenek28a71942010-11-13 00:36:47 +00001679class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1680 VisitorWorkList &WL;
1681 CXCursor Parent;
1682public:
1683 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1684 : WL(wl), Parent(parent) {}
1685
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001686 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001687 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001688 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001689 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001690 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001691 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001692 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001693 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001694 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001695 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001696 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001697 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001698 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001699 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001700 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001701 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001702 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001703 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1705 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001706 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001707 void VisitIfStmt(IfStmt *If);
1708 void VisitInitListExpr(InitListExpr *IE);
1709 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001710 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001711 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001712 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1713 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001714 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001715 void VisitStmt(Stmt *S);
1716 void VisitSwitchStmt(SwitchStmt *S);
1717 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001718 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001719 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001720 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001721 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001722 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001723
Ted Kremenek28a71942010-11-13 00:36:47 +00001724private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001725 void AddDeclarationNameInfo(Stmt *S);
1726 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001727 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001728 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001729 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001730 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001731 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001732 void AddTypeLoc(TypeSourceInfo *TI);
1733 void EnqueueChildren(Stmt *S);
1734};
1735} // end anonyous namespace
1736
Ted Kremenekf64d8032010-11-18 00:02:32 +00001737void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1738 // 'S' should always be non-null, since it comes from the
1739 // statement we are visiting.
1740 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1741}
1742void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1743 SourceRange R) {
1744 if (N)
1745 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1746}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001747
1748void
1749EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1750 if (Qualifier)
1751 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1752}
1753
Ted Kremenek28a71942010-11-13 00:36:47 +00001754void EnqueueVisitor::AddStmt(Stmt *S) {
1755 if (S)
1756 WL.push_back(StmtVisit(S, Parent));
1757}
Ted Kremenek035dc412010-11-13 00:36:50 +00001758void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001759 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001760 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001761}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001762void EnqueueVisitor::
1763 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1764 if (A)
1765 WL.push_back(ExplicitTemplateArgsVisit(
1766 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1767}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001768void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1769 if (D)
1770 WL.push_back(MemberRefVisit(D, L, Parent));
1771}
Ted Kremenek28a71942010-11-13 00:36:47 +00001772void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1773 if (TI)
1774 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1775 }
1776void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001777 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001778 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001779 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001780 }
1781 if (size == WL.size())
1782 return;
1783 // Now reverse the entries we just added. This will match the DFS
1784 // ordering performed by the worklist.
1785 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1786 std::reverse(I, E);
1787}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001788void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1789 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1790}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001791void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1792 AddDecl(B->getBlockDecl());
1793}
Ted Kremenek28a71942010-11-13 00:36:47 +00001794void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1795 EnqueueChildren(E);
1796 AddTypeLoc(E->getTypeSourceInfo());
1797}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001798void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1799 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1800 E = S->body_rend(); I != E; ++I) {
1801 AddStmt(*I);
1802 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001803}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001804void EnqueueVisitor::
1805VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1806 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1807 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001808 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1809 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001810 if (!E->isImplicitAccess())
1811 AddStmt(E->getBase());
1812}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001813void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1814 // Enqueue the initializer or constructor arguments.
1815 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1816 AddStmt(E->getConstructorArg(I-1));
1817 // Enqueue the array size, if any.
1818 AddStmt(E->getArraySize());
1819 // Enqueue the allocated type.
1820 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1821 // Enqueue the placement arguments.
1822 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1823 AddStmt(E->getPlacementArg(I-1));
1824}
Ted Kremenek28a71942010-11-13 00:36:47 +00001825void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001826 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1827 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001828 AddStmt(CE->getCallee());
1829 AddStmt(CE->getArg(0));
1830}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001831void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1832 // Visit the name of the type being destroyed.
1833 AddTypeLoc(E->getDestroyedTypeInfo());
1834 // Visit the scope type that looks disturbingly like the nested-name-specifier
1835 // but isn't.
1836 AddTypeLoc(E->getScopeTypeInfo());
1837 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001838 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1839 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001840 // Visit base expression.
1841 AddStmt(E->getBase());
1842}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001843void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1844 AddTypeLoc(E->getTypeSourceInfo());
1845}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001846void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1847 EnqueueChildren(E);
1848 AddTypeLoc(E->getTypeSourceInfo());
1849}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001850void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1851 EnqueueChildren(E);
1852 if (E->isTypeOperand())
1853 AddTypeLoc(E->getTypeOperandSourceInfo());
1854}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001855
1856void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1857 *E) {
1858 EnqueueChildren(E);
1859 AddTypeLoc(E->getTypeSourceInfo());
1860}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001861void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1862 EnqueueChildren(E);
1863 if (E->isTypeOperand())
1864 AddTypeLoc(E->getTypeOperandSourceInfo());
1865}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001866void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001867 if (DR->hasExplicitTemplateArgs()) {
1868 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1869 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001870 WL.push_back(DeclRefExprParts(DR, Parent));
1871}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001872void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1873 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1874 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001875 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001876}
Ted Kremenek035dc412010-11-13 00:36:50 +00001877void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1878 unsigned size = WL.size();
1879 bool isFirst = true;
1880 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1881 D != DEnd; ++D) {
1882 AddDecl(*D, isFirst);
1883 isFirst = false;
1884 }
1885 if (size == WL.size())
1886 return;
1887 // Now reverse the entries we just added. This will match the DFS
1888 // ordering performed by the worklist.
1889 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1890 std::reverse(I, E);
1891}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001892void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1893 AddStmt(E->getInit());
1894 typedef DesignatedInitExpr::Designator Designator;
1895 for (DesignatedInitExpr::reverse_designators_iterator
1896 D = E->designators_rbegin(), DEnd = E->designators_rend();
1897 D != DEnd; ++D) {
1898 if (D->isFieldDesignator()) {
1899 if (FieldDecl *Field = D->getField())
1900 AddMemberRef(Field, D->getFieldLoc());
1901 continue;
1902 }
1903 if (D->isArrayDesignator()) {
1904 AddStmt(E->getArrayIndex(*D));
1905 continue;
1906 }
1907 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1908 AddStmt(E->getArrayRangeEnd(*D));
1909 AddStmt(E->getArrayRangeStart(*D));
1910 }
1911}
Ted Kremenek28a71942010-11-13 00:36:47 +00001912void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1913 EnqueueChildren(E);
1914 AddTypeLoc(E->getTypeInfoAsWritten());
1915}
1916void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1917 AddStmt(FS->getBody());
1918 AddStmt(FS->getInc());
1919 AddStmt(FS->getCond());
1920 AddDecl(FS->getConditionVariable());
1921 AddStmt(FS->getInit());
1922}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001923void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1924 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1925}
Ted Kremenek28a71942010-11-13 00:36:47 +00001926void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1927 AddStmt(If->getElse());
1928 AddStmt(If->getThen());
1929 AddStmt(If->getCond());
1930 AddDecl(If->getConditionVariable());
1931}
1932void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1933 // We care about the syntactic form of the initializer list, only.
1934 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1935 IE = Syntactic;
1936 EnqueueChildren(IE);
1937}
1938void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001939 WL.push_back(MemberExprParts(M, Parent));
1940
1941 // If the base of the member access expression is an implicit 'this', don't
1942 // visit it.
1943 // FIXME: If we ever want to show these implicit accesses, this will be
1944 // unfortunate. However, clang_getCursor() relies on this behavior.
1945 if (CXXThisExpr *This
1946 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1947 if (This->isImplicit())
1948 return;
1949
Ted Kremenek28a71942010-11-13 00:36:47 +00001950 AddStmt(M->getBase());
1951}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001952void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1953 AddTypeLoc(E->getEncodedTypeSourceInfo());
1954}
Ted Kremenek28a71942010-11-13 00:36:47 +00001955void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1956 EnqueueChildren(M);
1957 AddTypeLoc(M->getClassReceiverTypeInfo());
1958}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001959void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1960 // Visit the components of the offsetof expression.
1961 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1962 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1963 const OffsetOfNode &Node = E->getComponent(I-1);
1964 switch (Node.getKind()) {
1965 case OffsetOfNode::Array:
1966 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1967 break;
1968 case OffsetOfNode::Field:
1969 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1970 break;
1971 case OffsetOfNode::Identifier:
1972 case OffsetOfNode::Base:
1973 continue;
1974 }
1975 }
1976 // Visit the type into which we're computing the offset.
1977 AddTypeLoc(E->getTypeSourceInfo());
1978}
Ted Kremenek28a71942010-11-13 00:36:47 +00001979void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001980 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001981 WL.push_back(OverloadExprParts(E, Parent));
1982}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001983void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1984 EnqueueChildren(E);
1985 if (E->isArgumentType())
1986 AddTypeLoc(E->getArgumentTypeInfo());
1987}
Ted Kremenek28a71942010-11-13 00:36:47 +00001988void EnqueueVisitor::VisitStmt(Stmt *S) {
1989 EnqueueChildren(S);
1990}
1991void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1992 AddStmt(S->getBody());
1993 AddStmt(S->getCond());
1994 AddDecl(S->getConditionVariable());
1995}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001996
Ted Kremenek28a71942010-11-13 00:36:47 +00001997void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1998 AddStmt(W->getBody());
1999 AddStmt(W->getCond());
2000 AddDecl(W->getConditionVariable());
2001}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002002void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2003 AddTypeLoc(E->getQueriedTypeSourceInfo());
2004}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002005
2006void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002007 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002008 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002009}
2010
Ted Kremenek28a71942010-11-13 00:36:47 +00002011void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2012 VisitOverloadExpr(U);
2013 if (!U->isImplicitAccess())
2014 AddStmt(U->getBase());
2015}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002016void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2017 AddStmt(E->getSubExpr());
2018 AddTypeLoc(E->getWrittenTypeInfo());
2019}
Douglas Gregor94d96292011-01-19 20:34:17 +00002020void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2021 WL.push_back(SizeOfPackExprParts(E, Parent));
2022}
Ted Kremenek60458782010-11-12 21:34:16 +00002023
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002024void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002025 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002026}
2027
2028bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2029 if (RegionOfInterest.isValid()) {
2030 SourceRange Range = getRawCursorExtent(C);
2031 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2032 return false;
2033 }
2034 return true;
2035}
2036
2037bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2038 while (!WL.empty()) {
2039 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002040 VisitorJob LI = WL.back();
2041 WL.pop_back();
2042
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002043 // Set the Parent field, then back to its old value once we're done.
2044 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2045
2046 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002047 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002048 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002049 if (!D)
2050 continue;
2051
2052 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002053 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002054 return true;
2055
2056 continue;
2057 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002058 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2059 const ExplicitTemplateArgumentList *ArgList =
2060 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2061 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2062 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2063 Arg != ArgEnd; ++Arg) {
2064 if (VisitTemplateArgumentLoc(*Arg))
2065 return true;
2066 }
2067 continue;
2068 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002069 case VisitorJob::TypeLocVisitKind: {
2070 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002071 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002072 return true;
2073 continue;
2074 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002075 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002076 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002077 if (LabelStmt *stmt = LS->getStmt()) {
2078 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2079 TU))) {
2080 return true;
2081 }
2082 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002083 continue;
2084 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002085
Ted Kremenekf64d8032010-11-18 00:02:32 +00002086 case VisitorJob::NestedNameSpecifierVisitKind: {
2087 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2088 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2089 return true;
2090 continue;
2091 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002092
2093 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2094 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2095 if (VisitNestedNameSpecifierLoc(V->get()))
2096 return true;
2097 continue;
2098 }
2099
Ted Kremenekf64d8032010-11-18 00:02:32 +00002100 case VisitorJob::DeclarationNameInfoVisitKind: {
2101 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2102 ->get()))
2103 return true;
2104 continue;
2105 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002106 case VisitorJob::MemberRefVisitKind: {
2107 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2108 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2109 return true;
2110 continue;
2111 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002112 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002113 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002114 if (!S)
2115 continue;
2116
Ted Kremenekf1107452010-11-12 18:26:56 +00002117 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002118 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002119 if (!IsInRegionOfInterest(Cursor))
2120 continue;
2121 switch (Visitor(Cursor, Parent, ClientData)) {
2122 case CXChildVisit_Break: return true;
2123 case CXChildVisit_Continue: break;
2124 case CXChildVisit_Recurse:
2125 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002126 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002127 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002128 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002129 }
2130 case VisitorJob::MemberExprPartsKind: {
2131 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002132 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002133
2134 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002135 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2136 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002137 return true;
2138
2139 // Visit the declaration name.
2140 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2141 return true;
2142
2143 // Visit the explicitly-specified template arguments, if any.
2144 if (M->hasExplicitTemplateArgs()) {
2145 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2146 *ArgEnd = Arg + M->getNumTemplateArgs();
2147 Arg != ArgEnd; ++Arg) {
2148 if (VisitTemplateArgumentLoc(*Arg))
2149 return true;
2150 }
2151 }
2152 continue;
2153 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002154 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002155 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002156 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002157 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2158 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002159 return true;
2160 // Visit declaration name.
2161 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2162 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002163 continue;
2164 }
Ted Kremenek60458782010-11-12 21:34:16 +00002165 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002166 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002167 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002168 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2169 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002170 return true;
2171 // Visit the declaration name.
2172 if (VisitDeclarationNameInfo(O->getNameInfo()))
2173 return true;
2174 // Visit the overloaded declaration reference.
2175 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2176 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002177 continue;
2178 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002179 case VisitorJob::SizeOfPackExprPartsKind: {
2180 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2181 NamedDecl *Pack = E->getPack();
2182 if (isa<TemplateTypeParmDecl>(Pack)) {
2183 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2184 E->getPackLoc(), TU)))
2185 return true;
2186
2187 continue;
2188 }
2189
2190 if (isa<TemplateTemplateParmDecl>(Pack)) {
2191 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2192 E->getPackLoc(), TU)))
2193 return true;
2194
2195 continue;
2196 }
2197
2198 // Non-type template parameter packs and function parameter packs are
2199 // treated like DeclRefExpr cursors.
2200 continue;
2201 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002202 }
2203 }
2204 return false;
2205}
2206
Ted Kremenekcdba6592010-11-18 00:42:18 +00002207bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002208 VisitorWorkList *WL = 0;
2209 if (!WorkListFreeList.empty()) {
2210 WL = WorkListFreeList.back();
2211 WL->clear();
2212 WorkListFreeList.pop_back();
2213 }
2214 else {
2215 WL = new VisitorWorkList();
2216 WorkListCache.push_back(WL);
2217 }
2218 EnqueueWorkList(*WL, S);
2219 bool result = RunVisitorWorkList(*WL);
2220 WorkListFreeList.push_back(WL);
2221 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002222}
2223
2224//===----------------------------------------------------------------------===//
2225// Misc. API hooks.
2226//===----------------------------------------------------------------------===//
2227
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002228static llvm::sys::Mutex EnableMultithreadingMutex;
2229static bool EnabledMultithreading;
2230
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002231extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002232CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2233 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002234 // Disable pretty stack trace functionality, which will otherwise be a very
2235 // poor citizen of the world and set up all sorts of signal handlers.
2236 llvm::DisablePrettyStackTrace = true;
2237
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002238 // We use crash recovery to make some of our APIs more reliable, implicitly
2239 // enable it.
2240 llvm::CrashRecoveryContext::Enable();
2241
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002242 // Enable support for multithreading in LLVM.
2243 {
2244 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2245 if (!EnabledMultithreading) {
2246 llvm::llvm_start_multithreaded();
2247 EnabledMultithreading = true;
2248 }
2249 }
2250
Douglas Gregora030b7c2010-01-22 20:35:53 +00002251 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002252 if (excludeDeclarationsFromPCH)
2253 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002254 if (displayDiagnostics)
2255 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002256 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002257}
2258
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002259void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002260 if (CIdx)
2261 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002262}
2263
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002264CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002265 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002266 if (!CIdx)
2267 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002268
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002269 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002270 FileSystemOptions FileSystemOpts;
2271 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002272
Douglas Gregor28019772010-04-05 23:52:57 +00002273 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002274 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002275 CXXIdx->getOnlyLocalDecls(),
2276 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002277 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002278}
2279
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002280unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002281 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002282 CXTranslationUnit_CacheCompletionResults |
2283 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002284}
2285
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002286CXTranslationUnit
2287clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2288 const char *source_filename,
2289 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002290 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002291 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002292 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002293 return clang_parseTranslationUnit(CIdx, source_filename,
2294 command_line_args, num_command_line_args,
2295 unsaved_files, num_unsaved_files,
2296 CXTranslationUnit_DetailedPreprocessingRecord);
2297}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002298
2299struct ParseTranslationUnitInfo {
2300 CXIndex CIdx;
2301 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002302 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002303 int num_command_line_args;
2304 struct CXUnsavedFile *unsaved_files;
2305 unsigned num_unsaved_files;
2306 unsigned options;
2307 CXTranslationUnit result;
2308};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002309static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002310 ParseTranslationUnitInfo *PTUI =
2311 static_cast<ParseTranslationUnitInfo*>(UserData);
2312 CXIndex CIdx = PTUI->CIdx;
2313 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002314 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002315 int num_command_line_args = PTUI->num_command_line_args;
2316 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2317 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2318 unsigned options = PTUI->options;
2319 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002320
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002321 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002322 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002323
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002324 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2325
Douglas Gregor44c181a2010-07-23 00:33:23 +00002326 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002327 bool CompleteTranslationUnit
2328 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002329 bool CacheCodeCompetionResults
2330 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002331 bool CXXPrecompilePreamble
2332 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2333 bool CXXChainedPCH
2334 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002335
Douglas Gregor5352ac02010-01-28 00:27:43 +00002336 // Configure the diagnostics.
2337 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002338 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002339 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2340 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002341
Douglas Gregor4db64a42010-01-23 00:14:00 +00002342 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2343 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002344 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002345 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002346 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002347 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2348 Buffer));
2349 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002350
Douglas Gregorb10daed2010-10-11 16:52:23 +00002351 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002352
Ted Kremenek139ba862009-10-22 00:03:57 +00002353 // The 'source_filename' argument is optional. If the caller does not
2354 // specify it then it is assumed that the source file is specified
2355 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002356 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002357 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002358
2359 // Since the Clang C library is primarily used by batch tools dealing with
2360 // (often very broken) source code, where spell-checking can have a
2361 // significant negative impact on performance (particularly when
2362 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002363 // Only do this if we haven't found a spell-checking-related argument.
2364 bool FoundSpellCheckingArgument = false;
2365 for (int I = 0; I != num_command_line_args; ++I) {
2366 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2367 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2368 FoundSpellCheckingArgument = true;
2369 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002370 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002371 }
2372 if (!FoundSpellCheckingArgument)
2373 Args.push_back("-fno-spell-checking");
2374
2375 Args.insert(Args.end(), command_line_args,
2376 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002377
Douglas Gregor44c181a2010-07-23 00:33:23 +00002378 // Do we need the detailed preprocessing record?
2379 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002380 Args.push_back("-Xclang");
2381 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002382 }
2383
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002384 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002385 llvm::OwningPtr<ASTUnit> Unit(
2386 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2387 Diags,
2388 CXXIdx->getClangResourcesPath(),
2389 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002390 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002391 RemappedFiles.data(),
2392 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002393 PrecompilePreamble,
2394 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002395 CacheCodeCompetionResults,
2396 CXXPrecompilePreamble,
2397 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002398
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002399 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002400 // Make sure to check that 'Unit' is non-NULL.
2401 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2402 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2403 DEnd = Unit->stored_diag_end();
2404 D != DEnd; ++D) {
2405 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2406 CXString Msg = clang_formatDiagnostic(&Diag,
2407 clang_defaultDiagnosticDisplayOptions());
2408 fprintf(stderr, "%s\n", clang_getCString(Msg));
2409 clang_disposeString(Msg);
2410 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002411#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002412 // On Windows, force a flush, since there may be multiple copies of
2413 // stderr and stdout in the file system, all with different buffers
2414 // but writing to the same device.
2415 fflush(stderr);
2416#endif
2417 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002418 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002419
Ted Kremeneka60ed472010-11-16 08:15:36 +00002420 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002421}
2422CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2423 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002424 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002425 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002426 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002427 unsigned num_unsaved_files,
2428 unsigned options) {
2429 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002430 num_command_line_args, unsaved_files,
2431 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002432 llvm::CrashRecoveryContext CRC;
2433
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002434 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002435 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2436 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2437 fprintf(stderr, " 'command_line_args' : [");
2438 for (int i = 0; i != num_command_line_args; ++i) {
2439 if (i)
2440 fprintf(stderr, ", ");
2441 fprintf(stderr, "'%s'", command_line_args[i]);
2442 }
2443 fprintf(stderr, "],\n");
2444 fprintf(stderr, " 'unsaved_files' : [");
2445 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2446 if (i)
2447 fprintf(stderr, ", ");
2448 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2449 unsaved_files[i].Length);
2450 }
2451 fprintf(stderr, "],\n");
2452 fprintf(stderr, " 'options' : %d,\n", options);
2453 fprintf(stderr, "}\n");
2454
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002455 return 0;
2456 }
2457
2458 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002459}
2460
Douglas Gregor19998442010-08-13 15:35:05 +00002461unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2462 return CXSaveTranslationUnit_None;
2463}
2464
2465int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2466 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002467 if (!TU)
2468 return 1;
2469
Ted Kremeneka60ed472010-11-16 08:15:36 +00002470 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002471}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002472
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002473void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002474 if (CTUnit) {
2475 // If the translation unit has been marked as unsafe to free, just discard
2476 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002477 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002478 return;
2479
Ted Kremeneka60ed472010-11-16 08:15:36 +00002480 delete static_cast<ASTUnit *>(CTUnit->TUData);
2481 disposeCXStringPool(CTUnit->StringPool);
2482 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002483 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002484}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002485
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002486unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2487 return CXReparse_None;
2488}
2489
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002490struct ReparseTranslationUnitInfo {
2491 CXTranslationUnit TU;
2492 unsigned num_unsaved_files;
2493 struct CXUnsavedFile *unsaved_files;
2494 unsigned options;
2495 int result;
2496};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002497
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002498static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002499 ReparseTranslationUnitInfo *RTUI =
2500 static_cast<ReparseTranslationUnitInfo*>(UserData);
2501 CXTranslationUnit TU = RTUI->TU;
2502 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2503 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2504 unsigned options = RTUI->options;
2505 (void) options;
2506 RTUI->result = 1;
2507
Douglas Gregorabc563f2010-07-19 21:46:24 +00002508 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002509 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002510
Ted Kremeneka60ed472010-11-16 08:15:36 +00002511 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002512 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002513
2514 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2515 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2516 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2517 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002518 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002519 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2520 Buffer));
2521 }
2522
Douglas Gregor593b0c12010-09-23 18:47:53 +00002523 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2524 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002525}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002526
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002527int clang_reparseTranslationUnit(CXTranslationUnit TU,
2528 unsigned num_unsaved_files,
2529 struct CXUnsavedFile *unsaved_files,
2530 unsigned options) {
2531 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2532 options, 0 };
2533 llvm::CrashRecoveryContext CRC;
2534
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002535 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002536 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002537 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002538 return 1;
2539 }
2540
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002541
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002542 return RTUI.result;
2543}
2544
Douglas Gregordf95a132010-08-09 20:45:32 +00002545
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002546CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002547 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002548 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002549
Ted Kremeneka60ed472010-11-16 08:15:36 +00002550 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002551 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002552}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002553
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002554CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002555 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002556 return Result;
2557}
2558
Ted Kremenekfb480492010-01-13 21:46:36 +00002559} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002560
Ted Kremenekfb480492010-01-13 21:46:36 +00002561//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002562// CXSourceLocation and CXSourceRange Operations.
2563//===----------------------------------------------------------------------===//
2564
Douglas Gregorb9790342010-01-22 21:44:22 +00002565extern "C" {
2566CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002567 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002568 return Result;
2569}
2570
2571unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002572 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2573 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2574 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002575}
2576
2577CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2578 CXFile file,
2579 unsigned line,
2580 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002581 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002582 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002583
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002584 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002585 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002586 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002587 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002588 = CXXUnit->getSourceManager().getLocation(File, line, column);
2589 if (SLoc.isInvalid()) {
2590 if (Logging)
2591 llvm::errs() << "clang_getLocation(\"" << File->getName()
2592 << "\", " << line << ", " << column << ") = invalid\n";
2593 return clang_getNullLocation();
2594 }
2595
2596 if (Logging)
2597 llvm::errs() << "clang_getLocation(\"" << File->getName()
2598 << "\", " << line << ", " << column << ") = "
2599 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002600
2601 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2602}
2603
2604CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2605 CXFile file,
2606 unsigned offset) {
2607 if (!tu || !file)
2608 return clang_getNullLocation();
2609
Ted Kremeneka60ed472010-11-16 08:15:36 +00002610 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002611 SourceLocation Start
2612 = CXXUnit->getSourceManager().getLocation(
2613 static_cast<const FileEntry *>(file),
2614 1, 1);
2615 if (Start.isInvalid()) return clang_getNullLocation();
2616
2617 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2618
2619 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002620
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002621 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002622}
2623
Douglas Gregor5352ac02010-01-28 00:27:43 +00002624CXSourceRange clang_getNullRange() {
2625 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2626 return Result;
2627}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002628
Douglas Gregor5352ac02010-01-28 00:27:43 +00002629CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2630 if (begin.ptr_data[0] != end.ptr_data[0] ||
2631 begin.ptr_data[1] != end.ptr_data[1])
2632 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002633
2634 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002635 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002636 return Result;
2637}
2638
Douglas Gregor46766dc2010-01-26 19:19:08 +00002639void clang_getInstantiationLocation(CXSourceLocation location,
2640 CXFile *file,
2641 unsigned *line,
2642 unsigned *column,
2643 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002644 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2645
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002646 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002647 if (file)
2648 *file = 0;
2649 if (line)
2650 *line = 0;
2651 if (column)
2652 *column = 0;
2653 if (offset)
2654 *offset = 0;
2655 return;
2656 }
2657
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002658 const SourceManager &SM =
2659 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002660 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002661
2662 if (file)
2663 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2664 if (line)
2665 *line = SM.getInstantiationLineNumber(InstLoc);
2666 if (column)
2667 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002668 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002669 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002670}
2671
Douglas Gregora9b06d42010-11-09 06:24:54 +00002672void clang_getSpellingLocation(CXSourceLocation location,
2673 CXFile *file,
2674 unsigned *line,
2675 unsigned *column,
2676 unsigned *offset) {
2677 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2678
2679 if (!location.ptr_data[0] || Loc.isInvalid()) {
2680 if (file)
2681 *file = 0;
2682 if (line)
2683 *line = 0;
2684 if (column)
2685 *column = 0;
2686 if (offset)
2687 *offset = 0;
2688 return;
2689 }
2690
2691 const SourceManager &SM =
2692 *static_cast<const SourceManager*>(location.ptr_data[0]);
2693 SourceLocation SpellLoc = Loc;
2694 if (SpellLoc.isMacroID()) {
2695 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2696 if (SimpleSpellingLoc.isFileID() &&
2697 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2698 SpellLoc = SimpleSpellingLoc;
2699 else
2700 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2701 }
2702
2703 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2704 FileID FID = LocInfo.first;
2705 unsigned FileOffset = LocInfo.second;
2706
2707 if (file)
2708 *file = (void *)SM.getFileEntryForID(FID);
2709 if (line)
2710 *line = SM.getLineNumber(FID, FileOffset);
2711 if (column)
2712 *column = SM.getColumnNumber(FID, FileOffset);
2713 if (offset)
2714 *offset = FileOffset;
2715}
2716
Douglas Gregor1db19de2010-01-19 21:36:55 +00002717CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002718 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002719 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002720 return Result;
2721}
2722
2723CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002724 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002725 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002726 return Result;
2727}
2728
Douglas Gregorb9790342010-01-22 21:44:22 +00002729} // end: extern "C"
2730
Douglas Gregor1db19de2010-01-19 21:36:55 +00002731//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002732// CXFile Operations.
2733//===----------------------------------------------------------------------===//
2734
2735extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002736CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002737 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002738 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002739
Steve Naroff88145032009-10-27 14:35:18 +00002740 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002741 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002742}
2743
2744time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002745 if (!SFile)
2746 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002747
Steve Naroff88145032009-10-27 14:35:18 +00002748 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2749 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002750}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002751
Douglas Gregorb9790342010-01-22 21:44:22 +00002752CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2753 if (!tu)
2754 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002755
Ted Kremeneka60ed472010-11-16 08:15:36 +00002756 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002757
Douglas Gregorb9790342010-01-22 21:44:22 +00002758 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002759 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002760}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002761
Ted Kremenekfb480492010-01-13 21:46:36 +00002762} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002763
Ted Kremenekfb480492010-01-13 21:46:36 +00002764//===----------------------------------------------------------------------===//
2765// CXCursor Operations.
2766//===----------------------------------------------------------------------===//
2767
Ted Kremenekfb480492010-01-13 21:46:36 +00002768static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002769 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2770 return getDeclFromExpr(CE->getSubExpr());
2771
Ted Kremenekfb480492010-01-13 21:46:36 +00002772 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2773 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002774 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2775 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002776 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2777 return ME->getMemberDecl();
2778 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2779 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002780 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002781 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002782
Ted Kremenekfb480492010-01-13 21:46:36 +00002783 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2784 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002785 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2786 if (!CE->isElidable())
2787 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002788 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2789 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002790
Douglas Gregordb1314e2010-10-01 21:11:22 +00002791 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2792 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002793 if (SubstNonTypeTemplateParmPackExpr *NTTP
2794 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2795 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002796 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2797 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2798 isa<ParmVarDecl>(SizeOfPack->getPack()))
2799 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002800
Ted Kremenekfb480492010-01-13 21:46:36 +00002801 return 0;
2802}
2803
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002804static SourceLocation getLocationFromExpr(Expr *E) {
2805 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2806 return /*FIXME:*/Msg->getLeftLoc();
2807 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2808 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002809 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2810 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002811 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2812 return Member->getMemberLoc();
2813 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2814 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002815 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2816 return SizeOfPack->getPackLoc();
2817
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002818 return E->getLocStart();
2819}
2820
Ted Kremenekfb480492010-01-13 21:46:36 +00002821extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002822
2823unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002824 CXCursorVisitor visitor,
2825 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002826 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2827 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002828 return CursorVis.VisitChildren(parent);
2829}
2830
David Chisnall3387c652010-11-03 14:12:26 +00002831#ifndef __has_feature
2832#define __has_feature(x) 0
2833#endif
2834#if __has_feature(blocks)
2835typedef enum CXChildVisitResult
2836 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2837
2838static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2839 CXClientData client_data) {
2840 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2841 return block(cursor, parent);
2842}
2843#else
2844// If we are compiled with a compiler that doesn't have native blocks support,
2845// define and call the block manually, so the
2846typedef struct _CXChildVisitResult
2847{
2848 void *isa;
2849 int flags;
2850 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002851 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2852 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002853} *CXCursorVisitorBlock;
2854
2855static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2856 CXClientData client_data) {
2857 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2858 return block->invoke(block, cursor, parent);
2859}
2860#endif
2861
2862
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002863unsigned clang_visitChildrenWithBlock(CXCursor parent,
2864 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002865 return clang_visitChildren(parent, visitWithBlock, block);
2866}
2867
Douglas Gregor78205d42010-01-20 21:45:58 +00002868static CXString getDeclSpelling(Decl *D) {
2869 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002870 if (!ND) {
2871 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2872 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2873 return createCXString(Property->getIdentifier()->getName());
2874
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002875 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002876 }
2877
Douglas Gregor78205d42010-01-20 21:45:58 +00002878 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002879 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002880
Douglas Gregor78205d42010-01-20 21:45:58 +00002881 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2882 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2883 // and returns different names. NamedDecl returns the class name and
2884 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002885 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002886
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002887 if (isa<UsingDirectiveDecl>(D))
2888 return createCXString("");
2889
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002890 llvm::SmallString<1024> S;
2891 llvm::raw_svector_ostream os(S);
2892 ND->printName(os);
2893
2894 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002895}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002896
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002897CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002898 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002899 return clang_getTranslationUnitSpelling(
2900 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002901
Steve Narofff334b4e2009-09-02 18:26:48 +00002902 if (clang_isReference(C.kind)) {
2903 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002904 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002905 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002906 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002907 }
2908 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002909 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002910 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002911 }
2912 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002913 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002914 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002915 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002916 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002917 case CXCursor_CXXBaseSpecifier: {
2918 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2919 return createCXString(B->getType().getAsString());
2920 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002921 case CXCursor_TypeRef: {
2922 TypeDecl *Type = getCursorTypeRef(C).first;
2923 assert(Type && "Missing type decl");
2924
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002925 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2926 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002927 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002928 case CXCursor_TemplateRef: {
2929 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002930 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002931
2932 return createCXString(Template->getNameAsString());
2933 }
Douglas Gregor69319002010-08-31 23:48:11 +00002934
2935 case CXCursor_NamespaceRef: {
2936 NamedDecl *NS = getCursorNamespaceRef(C).first;
2937 assert(NS && "Missing namespace decl");
2938
2939 return createCXString(NS->getNameAsString());
2940 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002941
Douglas Gregora67e03f2010-09-09 21:42:20 +00002942 case CXCursor_MemberRef: {
2943 FieldDecl *Field = getCursorMemberRef(C).first;
2944 assert(Field && "Missing member decl");
2945
2946 return createCXString(Field->getNameAsString());
2947 }
2948
Douglas Gregor36897b02010-09-10 00:22:18 +00002949 case CXCursor_LabelRef: {
2950 LabelStmt *Label = getCursorLabelRef(C).first;
2951 assert(Label && "Missing label");
2952
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002953 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002954 }
2955
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002956 case CXCursor_OverloadedDeclRef: {
2957 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2958 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2959 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2960 return createCXString(ND->getNameAsString());
2961 return createCXString("");
2962 }
2963 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2964 return createCXString(E->getName().getAsString());
2965 OverloadedTemplateStorage *Ovl
2966 = Storage.get<OverloadedTemplateStorage*>();
2967 if (Ovl->size() == 0)
2968 return createCXString("");
2969 return createCXString((*Ovl->begin())->getNameAsString());
2970 }
2971
Daniel Dunbaracca7252009-11-30 20:42:49 +00002972 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002973 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002974 }
2975 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002976
2977 if (clang_isExpression(C.kind)) {
2978 Decl *D = getDeclFromExpr(getCursorExpr(C));
2979 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002980 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002981 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002982 }
2983
Douglas Gregor36897b02010-09-10 00:22:18 +00002984 if (clang_isStatement(C.kind)) {
2985 Stmt *S = getCursorStmt(C);
2986 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002987 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002988
2989 return createCXString("");
2990 }
2991
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002992 if (C.kind == CXCursor_MacroInstantiation)
2993 return createCXString(getCursorMacroInstantiation(C)->getName()
2994 ->getNameStart());
2995
Douglas Gregor572feb22010-03-18 18:04:21 +00002996 if (C.kind == CXCursor_MacroDefinition)
2997 return createCXString(getCursorMacroDefinition(C)->getName()
2998 ->getNameStart());
2999
Douglas Gregorecdcb882010-10-20 22:00:55 +00003000 if (C.kind == CXCursor_InclusionDirective)
3001 return createCXString(getCursorInclusionDirective(C)->getFileName());
3002
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003003 if (clang_isDeclaration(C.kind))
3004 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003005
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003006 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003007}
3008
Douglas Gregor358559d2010-10-02 22:49:11 +00003009CXString clang_getCursorDisplayName(CXCursor C) {
3010 if (!clang_isDeclaration(C.kind))
3011 return clang_getCursorSpelling(C);
3012
3013 Decl *D = getCursorDecl(C);
3014 if (!D)
3015 return createCXString("");
3016
3017 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3018 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3019 D = FunTmpl->getTemplatedDecl();
3020
3021 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3022 llvm::SmallString<64> Str;
3023 llvm::raw_svector_ostream OS(Str);
3024 OS << Function->getNameAsString();
3025 if (Function->getPrimaryTemplate())
3026 OS << "<>";
3027 OS << "(";
3028 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3029 if (I)
3030 OS << ", ";
3031 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3032 }
3033
3034 if (Function->isVariadic()) {
3035 if (Function->getNumParams())
3036 OS << ", ";
3037 OS << "...";
3038 }
3039 OS << ")";
3040 return createCXString(OS.str());
3041 }
3042
3043 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3044 llvm::SmallString<64> Str;
3045 llvm::raw_svector_ostream OS(Str);
3046 OS << ClassTemplate->getNameAsString();
3047 OS << "<";
3048 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3049 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3050 if (I)
3051 OS << ", ";
3052
3053 NamedDecl *Param = Params->getParam(I);
3054 if (Param->getIdentifier()) {
3055 OS << Param->getIdentifier()->getName();
3056 continue;
3057 }
3058
3059 // There is no parameter name, which makes this tricky. Try to come up
3060 // with something useful that isn't too long.
3061 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3062 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3063 else if (NonTypeTemplateParmDecl *NTTP
3064 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3065 OS << NTTP->getType().getAsString(Policy);
3066 else
3067 OS << "template<...> class";
3068 }
3069
3070 OS << ">";
3071 return createCXString(OS.str());
3072 }
3073
3074 if (ClassTemplateSpecializationDecl *ClassSpec
3075 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3076 // If the type was explicitly written, use that.
3077 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3078 return createCXString(TSInfo->getType().getAsString(Policy));
3079
3080 llvm::SmallString<64> Str;
3081 llvm::raw_svector_ostream OS(Str);
3082 OS << ClassSpec->getNameAsString();
3083 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003084 ClassSpec->getTemplateArgs().data(),
3085 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003086 Policy);
3087 return createCXString(OS.str());
3088 }
3089
3090 return clang_getCursorSpelling(C);
3091}
3092
Ted Kremeneke68fff62010-02-17 00:41:32 +00003093CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003094 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003095 case CXCursor_FunctionDecl:
3096 return createCXString("FunctionDecl");
3097 case CXCursor_TypedefDecl:
3098 return createCXString("TypedefDecl");
3099 case CXCursor_EnumDecl:
3100 return createCXString("EnumDecl");
3101 case CXCursor_EnumConstantDecl:
3102 return createCXString("EnumConstantDecl");
3103 case CXCursor_StructDecl:
3104 return createCXString("StructDecl");
3105 case CXCursor_UnionDecl:
3106 return createCXString("UnionDecl");
3107 case CXCursor_ClassDecl:
3108 return createCXString("ClassDecl");
3109 case CXCursor_FieldDecl:
3110 return createCXString("FieldDecl");
3111 case CXCursor_VarDecl:
3112 return createCXString("VarDecl");
3113 case CXCursor_ParmDecl:
3114 return createCXString("ParmDecl");
3115 case CXCursor_ObjCInterfaceDecl:
3116 return createCXString("ObjCInterfaceDecl");
3117 case CXCursor_ObjCCategoryDecl:
3118 return createCXString("ObjCCategoryDecl");
3119 case CXCursor_ObjCProtocolDecl:
3120 return createCXString("ObjCProtocolDecl");
3121 case CXCursor_ObjCPropertyDecl:
3122 return createCXString("ObjCPropertyDecl");
3123 case CXCursor_ObjCIvarDecl:
3124 return createCXString("ObjCIvarDecl");
3125 case CXCursor_ObjCInstanceMethodDecl:
3126 return createCXString("ObjCInstanceMethodDecl");
3127 case CXCursor_ObjCClassMethodDecl:
3128 return createCXString("ObjCClassMethodDecl");
3129 case CXCursor_ObjCImplementationDecl:
3130 return createCXString("ObjCImplementationDecl");
3131 case CXCursor_ObjCCategoryImplDecl:
3132 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003133 case CXCursor_CXXMethod:
3134 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003135 case CXCursor_UnexposedDecl:
3136 return createCXString("UnexposedDecl");
3137 case CXCursor_ObjCSuperClassRef:
3138 return createCXString("ObjCSuperClassRef");
3139 case CXCursor_ObjCProtocolRef:
3140 return createCXString("ObjCProtocolRef");
3141 case CXCursor_ObjCClassRef:
3142 return createCXString("ObjCClassRef");
3143 case CXCursor_TypeRef:
3144 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003145 case CXCursor_TemplateRef:
3146 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003147 case CXCursor_NamespaceRef:
3148 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003149 case CXCursor_MemberRef:
3150 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003151 case CXCursor_LabelRef:
3152 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003153 case CXCursor_OverloadedDeclRef:
3154 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003155 case CXCursor_UnexposedExpr:
3156 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003157 case CXCursor_BlockExpr:
3158 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003159 case CXCursor_DeclRefExpr:
3160 return createCXString("DeclRefExpr");
3161 case CXCursor_MemberRefExpr:
3162 return createCXString("MemberRefExpr");
3163 case CXCursor_CallExpr:
3164 return createCXString("CallExpr");
3165 case CXCursor_ObjCMessageExpr:
3166 return createCXString("ObjCMessageExpr");
3167 case CXCursor_UnexposedStmt:
3168 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003169 case CXCursor_LabelStmt:
3170 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003171 case CXCursor_InvalidFile:
3172 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003173 case CXCursor_InvalidCode:
3174 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003175 case CXCursor_NoDeclFound:
3176 return createCXString("NoDeclFound");
3177 case CXCursor_NotImplemented:
3178 return createCXString("NotImplemented");
3179 case CXCursor_TranslationUnit:
3180 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003181 case CXCursor_UnexposedAttr:
3182 return createCXString("UnexposedAttr");
3183 case CXCursor_IBActionAttr:
3184 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003185 case CXCursor_IBOutletAttr:
3186 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003187 case CXCursor_IBOutletCollectionAttr:
3188 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003189 case CXCursor_PreprocessingDirective:
3190 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003191 case CXCursor_MacroDefinition:
3192 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003193 case CXCursor_MacroInstantiation:
3194 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003195 case CXCursor_InclusionDirective:
3196 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003197 case CXCursor_Namespace:
3198 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003199 case CXCursor_LinkageSpec:
3200 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003201 case CXCursor_CXXBaseSpecifier:
3202 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003203 case CXCursor_Constructor:
3204 return createCXString("CXXConstructor");
3205 case CXCursor_Destructor:
3206 return createCXString("CXXDestructor");
3207 case CXCursor_ConversionFunction:
3208 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003209 case CXCursor_TemplateTypeParameter:
3210 return createCXString("TemplateTypeParameter");
3211 case CXCursor_NonTypeTemplateParameter:
3212 return createCXString("NonTypeTemplateParameter");
3213 case CXCursor_TemplateTemplateParameter:
3214 return createCXString("TemplateTemplateParameter");
3215 case CXCursor_FunctionTemplate:
3216 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003217 case CXCursor_ClassTemplate:
3218 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003219 case CXCursor_ClassTemplatePartialSpecialization:
3220 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003221 case CXCursor_NamespaceAlias:
3222 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003223 case CXCursor_UsingDirective:
3224 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003225 case CXCursor_UsingDeclaration:
3226 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003227 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003228
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003229 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003230 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003231}
Steve Naroff89922f82009-08-31 00:59:03 +00003232
Ted Kremeneke68fff62010-02-17 00:41:32 +00003233enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3234 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003235 CXClientData client_data) {
3236 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003237
3238 // If our current best cursor is the construction of a temporary object,
3239 // don't replace that cursor with a type reference, because we want
3240 // clang_getCursor() to point at the constructor.
3241 if (clang_isExpression(BestCursor->kind) &&
3242 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3243 cursor.kind == CXCursor_TypeRef)
3244 return CXChildVisit_Recurse;
3245
Douglas Gregor85fe1562010-12-10 07:23:11 +00003246 // Don't override a preprocessing cursor with another preprocessing
3247 // cursor; we want the outermost preprocessing cursor.
3248 if (clang_isPreprocessing(cursor.kind) &&
3249 clang_isPreprocessing(BestCursor->kind))
3250 return CXChildVisit_Recurse;
3251
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003252 *BestCursor = cursor;
3253 return CXChildVisit_Recurse;
3254}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003255
Douglas Gregorb9790342010-01-22 21:44:22 +00003256CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3257 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003258 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003259
Ted Kremeneka60ed472010-11-16 08:15:36 +00003260 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003261 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3262
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003263 // Translate the given source location to make it point at the beginning of
3264 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003265 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003266
3267 // Guard against an invalid SourceLocation, or we may assert in one
3268 // of the following calls.
3269 if (SLoc.isInvalid())
3270 return clang_getNullCursor();
3271
Douglas Gregor40749ee2010-11-03 00:35:38 +00003272 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003273 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3274 CXXUnit->getASTContext().getLangOptions());
3275
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003276 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3277 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003278 // FIXME: Would be great to have a "hint" cursor, then walk from that
3279 // hint cursor upward until we find a cursor whose source range encloses
3280 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003281 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3282 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003283 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003284 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003285 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003286
3287 if (Logging) {
3288 CXFile SearchFile;
3289 unsigned SearchLine, SearchColumn;
3290 CXFile ResultFile;
3291 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003292 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3293 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003294 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3295
3296 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3297 0);
3298 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3299 &ResultColumn, 0);
3300 SearchFileName = clang_getFileName(SearchFile);
3301 ResultFileName = clang_getFileName(ResultFile);
3302 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003303 USR = clang_getCursorUSR(Result);
3304 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003305 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3306 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003307 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3308 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003309 clang_disposeString(SearchFileName);
3310 clang_disposeString(ResultFileName);
3311 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003312 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003313
3314 CXCursor Definition = clang_getCursorDefinition(Result);
3315 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3316 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3317 CXString DefinitionKindSpelling
3318 = clang_getCursorKindSpelling(Definition.kind);
3319 CXFile DefinitionFile;
3320 unsigned DefinitionLine, DefinitionColumn;
3321 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3322 &DefinitionLine, &DefinitionColumn, 0);
3323 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3324 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3325 clang_getCString(DefinitionKindSpelling),
3326 clang_getCString(DefinitionFileName),
3327 DefinitionLine, DefinitionColumn);
3328 clang_disposeString(DefinitionFileName);
3329 clang_disposeString(DefinitionKindSpelling);
3330 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003331 }
3332
Ted Kremeneke68fff62010-02-17 00:41:32 +00003333 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003334}
3335
Ted Kremenek73885552009-11-17 19:28:59 +00003336CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003337 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003338}
3339
3340unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003341 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003342}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003343
Douglas Gregor9ce55842010-11-20 00:09:34 +00003344unsigned clang_hashCursor(CXCursor C) {
3345 unsigned Index = 0;
3346 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3347 Index = 1;
3348
3349 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3350 std::make_pair(C.kind, C.data[Index]));
3351}
3352
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003353unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003354 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3355}
3356
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003357unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003358 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3359}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003360
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003361unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003362 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3363}
3364
Douglas Gregor97b98722010-01-19 23:20:36 +00003365unsigned clang_isExpression(enum CXCursorKind K) {
3366 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3367}
3368
3369unsigned clang_isStatement(enum CXCursorKind K) {
3370 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3371}
3372
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003373unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3374 return K == CXCursor_TranslationUnit;
3375}
3376
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003377unsigned clang_isPreprocessing(enum CXCursorKind K) {
3378 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3379}
3380
Ted Kremenekad6eff62010-03-08 21:17:29 +00003381unsigned clang_isUnexposed(enum CXCursorKind K) {
3382 switch (K) {
3383 case CXCursor_UnexposedDecl:
3384 case CXCursor_UnexposedExpr:
3385 case CXCursor_UnexposedStmt:
3386 case CXCursor_UnexposedAttr:
3387 return true;
3388 default:
3389 return false;
3390 }
3391}
3392
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003393CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003394 return C.kind;
3395}
3396
Douglas Gregor98258af2010-01-18 22:46:11 +00003397CXSourceLocation clang_getCursorLocation(CXCursor C) {
3398 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003399 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003400 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003401 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3402 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003403 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003404 }
3405
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003406 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003407 std::pair<ObjCProtocolDecl *, SourceLocation> P
3408 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003409 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003410 }
3411
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003412 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003413 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3414 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003415 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003416 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003417
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003418 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003419 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003420 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003421 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003422
3423 case CXCursor_TemplateRef: {
3424 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3425 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3426 }
3427
Douglas Gregor69319002010-08-31 23:48:11 +00003428 case CXCursor_NamespaceRef: {
3429 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3430 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3431 }
3432
Douglas Gregora67e03f2010-09-09 21:42:20 +00003433 case CXCursor_MemberRef: {
3434 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3435 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3436 }
3437
Ted Kremenek3064ef92010-08-27 21:34:58 +00003438 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003439 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3440 if (!BaseSpec)
3441 return clang_getNullLocation();
3442
3443 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3444 return cxloc::translateSourceLocation(getCursorContext(C),
3445 TSInfo->getTypeLoc().getBeginLoc());
3446
3447 return cxloc::translateSourceLocation(getCursorContext(C),
3448 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003449 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003450
Douglas Gregor36897b02010-09-10 00:22:18 +00003451 case CXCursor_LabelRef: {
3452 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3453 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3454 }
3455
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003456 case CXCursor_OverloadedDeclRef:
3457 return cxloc::translateSourceLocation(getCursorContext(C),
3458 getCursorOverloadedDeclRef(C).second);
3459
Douglas Gregorf46034a2010-01-18 23:41:10 +00003460 default:
3461 // FIXME: Need a way to enumerate all non-reference cases.
3462 llvm_unreachable("Missed a reference kind");
3463 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003464 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003465
3466 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003467 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003468 getLocationFromExpr(getCursorExpr(C)));
3469
Douglas Gregor36897b02010-09-10 00:22:18 +00003470 if (clang_isStatement(C.kind))
3471 return cxloc::translateSourceLocation(getCursorContext(C),
3472 getCursorStmt(C)->getLocStart());
3473
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003474 if (C.kind == CXCursor_PreprocessingDirective) {
3475 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3476 return cxloc::translateSourceLocation(getCursorContext(C), L);
3477 }
Douglas Gregor48072312010-03-18 15:23:44 +00003478
3479 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003480 SourceLocation L
3481 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003482 return cxloc::translateSourceLocation(getCursorContext(C), L);
3483 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003484
3485 if (C.kind == CXCursor_MacroDefinition) {
3486 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3487 return cxloc::translateSourceLocation(getCursorContext(C), L);
3488 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003489
3490 if (C.kind == CXCursor_InclusionDirective) {
3491 SourceLocation L
3492 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3493 return cxloc::translateSourceLocation(getCursorContext(C), L);
3494 }
3495
Ted Kremenek9a700d22010-05-12 06:16:13 +00003496 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003497 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003498
Douglas Gregorf46034a2010-01-18 23:41:10 +00003499 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003500 SourceLocation Loc = D->getLocation();
3501 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3502 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003503 // FIXME: Multiple variables declared in a single declaration
3504 // currently lack the information needed to correctly determine their
3505 // ranges when accounting for the type-specifier. We use context
3506 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3507 // and if so, whether it is the first decl.
3508 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3509 if (!cxcursor::isFirstInDeclGroup(C))
3510 Loc = VD->getLocation();
3511 }
3512
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003513 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003514}
Douglas Gregora7bde202010-01-19 00:34:46 +00003515
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003516} // end extern "C"
3517
3518static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003519 if (clang_isReference(C.kind)) {
3520 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003521 case CXCursor_ObjCSuperClassRef:
3522 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003523
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003524 case CXCursor_ObjCProtocolRef:
3525 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003526
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003527 case CXCursor_ObjCClassRef:
3528 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003529
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003530 case CXCursor_TypeRef:
3531 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003532
3533 case CXCursor_TemplateRef:
3534 return getCursorTemplateRef(C).second;
3535
Douglas Gregor69319002010-08-31 23:48:11 +00003536 case CXCursor_NamespaceRef:
3537 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003538
3539 case CXCursor_MemberRef:
3540 return getCursorMemberRef(C).second;
3541
Ted Kremenek3064ef92010-08-27 21:34:58 +00003542 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003543 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003544
Douglas Gregor36897b02010-09-10 00:22:18 +00003545 case CXCursor_LabelRef:
3546 return getCursorLabelRef(C).second;
3547
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003548 case CXCursor_OverloadedDeclRef:
3549 return getCursorOverloadedDeclRef(C).second;
3550
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003551 default:
3552 // FIXME: Need a way to enumerate all non-reference cases.
3553 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003554 }
3555 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003556
3557 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003558 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003559
3560 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003561 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003562
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003563 if (C.kind == CXCursor_PreprocessingDirective)
3564 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003565
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003566 if (C.kind == CXCursor_MacroInstantiation)
3567 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003568
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003569 if (C.kind == CXCursor_MacroDefinition)
3570 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003571
3572 if (C.kind == CXCursor_InclusionDirective)
3573 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3574
Ted Kremenek007a7c92010-11-01 23:26:51 +00003575 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3576 Decl *D = cxcursor::getCursorDecl(C);
3577 SourceRange R = D->getSourceRange();
3578 // FIXME: Multiple variables declared in a single declaration
3579 // currently lack the information needed to correctly determine their
3580 // ranges when accounting for the type-specifier. We use context
3581 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3582 // and if so, whether it is the first decl.
3583 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3584 if (!cxcursor::isFirstInDeclGroup(C))
3585 R.setBegin(VD->getLocation());
3586 }
3587 return R;
3588 }
Douglas Gregor66537982010-11-17 17:14:07 +00003589 return SourceRange();
3590}
3591
3592/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3593/// the decl-specifier-seq for declarations.
3594static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3595 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3596 Decl *D = cxcursor::getCursorDecl(C);
3597 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003598
Douglas Gregor2494dd02011-03-01 01:34:45 +00003599 // Adjust the start of the location for declarations preceded by
3600 // declaration specifiers.
3601 SourceLocation StartLoc;
3602 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3603 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3604 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3605 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3606 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3607 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3608 }
3609
3610 if (StartLoc.isValid() && R.getBegin().isValid() &&
3611 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3612 R.setBegin(StartLoc);
3613
3614 // FIXME: Multiple variables declared in a single declaration
3615 // currently lack the information needed to correctly determine their
3616 // ranges when accounting for the type-specifier. We use context
3617 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3618 // and if so, whether it is the first decl.
3619 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3620 if (!cxcursor::isFirstInDeclGroup(C))
3621 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003622 }
3623
3624 return R;
3625 }
3626
3627 return getRawCursorExtent(C);
3628}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003629
3630extern "C" {
3631
3632CXSourceRange clang_getCursorExtent(CXCursor C) {
3633 SourceRange R = getRawCursorExtent(C);
3634 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003635 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003636
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003637 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003638}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003639
3640CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003641 if (clang_isInvalid(C.kind))
3642 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003643
Ted Kremeneka60ed472010-11-16 08:15:36 +00003644 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003645 if (clang_isDeclaration(C.kind)) {
3646 Decl *D = getCursorDecl(C);
3647 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003648 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003649 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003650 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003651 if (ObjCForwardProtocolDecl *Protocols
3652 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003653 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003654 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3655 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3656 return MakeCXCursor(Property, tu);
3657
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003658 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003659 }
3660
Douglas Gregor97b98722010-01-19 23:20:36 +00003661 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003662 Expr *E = getCursorExpr(C);
3663 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003664 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003665 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003666
3667 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003668 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003669
Douglas Gregor97b98722010-01-19 23:20:36 +00003670 return clang_getNullCursor();
3671 }
3672
Douglas Gregor36897b02010-09-10 00:22:18 +00003673 if (clang_isStatement(C.kind)) {
3674 Stmt *S = getCursorStmt(C);
3675 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003676 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003677
3678 return clang_getNullCursor();
3679 }
3680
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003681 if (C.kind == CXCursor_MacroInstantiation) {
3682 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003683 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003684 }
3685
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003686 if (!clang_isReference(C.kind))
3687 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003688
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003689 switch (C.kind) {
3690 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003691 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003692
3693 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003694 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003695
3696 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003697 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003698
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003699 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003700 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003701
3702 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003703 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003704
Douglas Gregor69319002010-08-31 23:48:11 +00003705 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003706 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003707
Douglas Gregora67e03f2010-09-09 21:42:20 +00003708 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003709 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003710
Ted Kremenek3064ef92010-08-27 21:34:58 +00003711 case CXCursor_CXXBaseSpecifier: {
3712 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3713 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003714 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003715 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003716
Douglas Gregor36897b02010-09-10 00:22:18 +00003717 case CXCursor_LabelRef:
3718 // FIXME: We end up faking the "parent" declaration here because we
3719 // don't want to make CXCursor larger.
3720 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003721 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3722 .getTranslationUnitDecl(),
3723 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003724
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003725 case CXCursor_OverloadedDeclRef:
3726 return C;
3727
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003728 default:
3729 // We would prefer to enumerate all non-reference cursor kinds here.
3730 llvm_unreachable("Unhandled reference cursor kind");
3731 break;
3732 }
3733 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003734
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003735 return clang_getNullCursor();
3736}
3737
Douglas Gregorb6998662010-01-19 19:34:47 +00003738CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003739 if (clang_isInvalid(C.kind))
3740 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003741
Ted Kremeneka60ed472010-11-16 08:15:36 +00003742 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003743
Douglas Gregorb6998662010-01-19 19:34:47 +00003744 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003745 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003746 C = clang_getCursorReferenced(C);
3747 WasReference = true;
3748 }
3749
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003750 if (C.kind == CXCursor_MacroInstantiation)
3751 return clang_getCursorReferenced(C);
3752
Douglas Gregorb6998662010-01-19 19:34:47 +00003753 if (!clang_isDeclaration(C.kind))
3754 return clang_getNullCursor();
3755
3756 Decl *D = getCursorDecl(C);
3757 if (!D)
3758 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003759
Douglas Gregorb6998662010-01-19 19:34:47 +00003760 switch (D->getKind()) {
3761 // Declaration kinds that don't really separate the notions of
3762 // declaration and definition.
3763 case Decl::Namespace:
3764 case Decl::Typedef:
3765 case Decl::TemplateTypeParm:
3766 case Decl::EnumConstant:
3767 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003768 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003769 case Decl::ObjCIvar:
3770 case Decl::ObjCAtDefsField:
3771 case Decl::ImplicitParam:
3772 case Decl::ParmVar:
3773 case Decl::NonTypeTemplateParm:
3774 case Decl::TemplateTemplateParm:
3775 case Decl::ObjCCategoryImpl:
3776 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003777 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003778 case Decl::LinkageSpec:
3779 case Decl::ObjCPropertyImpl:
3780 case Decl::FileScopeAsm:
3781 case Decl::StaticAssert:
3782 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003783 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003784 return C;
3785
3786 // Declaration kinds that don't make any sense here, but are
3787 // nonetheless harmless.
3788 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003789 break;
3790
3791 // Declaration kinds for which the definition is not resolvable.
3792 case Decl::UnresolvedUsingTypename:
3793 case Decl::UnresolvedUsingValue:
3794 break;
3795
3796 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003797 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003798 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003799
3800 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003801 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003802
3803 case Decl::Enum:
3804 case Decl::Record:
3805 case Decl::CXXRecord:
3806 case Decl::ClassTemplateSpecialization:
3807 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003808 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003809 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003810 return clang_getNullCursor();
3811
3812 case Decl::Function:
3813 case Decl::CXXMethod:
3814 case Decl::CXXConstructor:
3815 case Decl::CXXDestructor:
3816 case Decl::CXXConversion: {
3817 const FunctionDecl *Def = 0;
3818 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003819 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003820 return clang_getNullCursor();
3821 }
3822
3823 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003824 // Ask the variable if it has a definition.
3825 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003826 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003827 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003828 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003829
Douglas Gregorb6998662010-01-19 19:34:47 +00003830 case Decl::FunctionTemplate: {
3831 const FunctionDecl *Def = 0;
3832 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003833 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003834 return clang_getNullCursor();
3835 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorb6998662010-01-19 19:34:47 +00003837 case Decl::ClassTemplate: {
3838 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003839 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003840 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003841 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003842 return clang_getNullCursor();
3843 }
3844
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003845 case Decl::Using:
3846 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003847 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003848
3849 case Decl::UsingShadow:
3850 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003851 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003852 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003853
3854 case Decl::ObjCMethod: {
3855 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3856 if (Method->isThisDeclarationADefinition())
3857 return C;
3858
3859 // Dig out the method definition in the associated
3860 // @implementation, if we have it.
3861 // FIXME: The ASTs should make finding the definition easier.
3862 if (ObjCInterfaceDecl *Class
3863 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3864 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3865 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3866 Method->isInstanceMethod()))
3867 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003868 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003869
3870 return clang_getNullCursor();
3871 }
3872
3873 case Decl::ObjCCategory:
3874 if (ObjCCategoryImplDecl *Impl
3875 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003876 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003877 return clang_getNullCursor();
3878
3879 case Decl::ObjCProtocol:
3880 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3881 return C;
3882 return clang_getNullCursor();
3883
3884 case Decl::ObjCInterface:
3885 // There are two notions of a "definition" for an Objective-C
3886 // class: the interface and its implementation. When we resolved a
3887 // reference to an Objective-C class, produce the @interface as
3888 // the definition; when we were provided with the interface,
3889 // produce the @implementation as the definition.
3890 if (WasReference) {
3891 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3892 return C;
3893 } else if (ObjCImplementationDecl *Impl
3894 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003895 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003896 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003897
Douglas Gregorb6998662010-01-19 19:34:47 +00003898 case Decl::ObjCProperty:
3899 // FIXME: We don't really know where to find the
3900 // ObjCPropertyImplDecls that implement this property.
3901 return clang_getNullCursor();
3902
3903 case Decl::ObjCCompatibleAlias:
3904 if (ObjCInterfaceDecl *Class
3905 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3906 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003907 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003908
Douglas Gregorb6998662010-01-19 19:34:47 +00003909 return clang_getNullCursor();
3910
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003911 case Decl::ObjCForwardProtocol:
3912 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003913 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003914
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003915 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003916 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003917 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003918
3919 case Decl::Friend:
3920 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003921 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003922 return clang_getNullCursor();
3923
3924 case Decl::FriendTemplate:
3925 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003926 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003927 return clang_getNullCursor();
3928 }
3929
3930 return clang_getNullCursor();
3931}
3932
3933unsigned clang_isCursorDefinition(CXCursor C) {
3934 if (!clang_isDeclaration(C.kind))
3935 return 0;
3936
3937 return clang_getCursorDefinition(C) == C;
3938}
3939
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003940CXCursor clang_getCanonicalCursor(CXCursor C) {
3941 if (!clang_isDeclaration(C.kind))
3942 return C;
3943
3944 if (Decl *D = getCursorDecl(C))
3945 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3946
3947 return C;
3948}
3949
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003950unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003951 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003952 return 0;
3953
3954 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3955 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3956 return E->getNumDecls();
3957
3958 if (OverloadedTemplateStorage *S
3959 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3960 return S->size();
3961
3962 Decl *D = Storage.get<Decl*>();
3963 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003964 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003965 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3966 return Classes->size();
3967 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3968 return Protocols->protocol_size();
3969
3970 return 0;
3971}
3972
3973CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003974 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003975 return clang_getNullCursor();
3976
3977 if (index >= clang_getNumOverloadedDecls(cursor))
3978 return clang_getNullCursor();
3979
Ted Kremeneka60ed472010-11-16 08:15:36 +00003980 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003981 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3982 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003983 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003984
3985 if (OverloadedTemplateStorage *S
3986 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003987 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003988
3989 Decl *D = Storage.get<Decl*>();
3990 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3991 // FIXME: This is, unfortunately, linear time.
3992 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3993 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003994 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003995 }
3996
3997 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003998 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003999
4000 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004001 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004002
4003 return clang_getNullCursor();
4004}
4005
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004006void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004007 const char **startBuf,
4008 const char **endBuf,
4009 unsigned *startLine,
4010 unsigned *startColumn,
4011 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004012 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004013 assert(getCursorDecl(C) && "CXCursor has null decl");
4014 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004015 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4016 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004017
Steve Naroff4ade6d62009-09-23 17:52:52 +00004018 SourceManager &SM = FD->getASTContext().getSourceManager();
4019 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4020 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4021 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4022 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4023 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4024 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4025}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004026
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004027void clang_enableStackTraces(void) {
4028 llvm::sys::PrintStackTraceOnErrorSignal();
4029}
4030
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004031void clang_executeOnThread(void (*fn)(void*), void *user_data,
4032 unsigned stack_size) {
4033 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4034}
4035
Ted Kremenekfb480492010-01-13 21:46:36 +00004036} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004037
Ted Kremenekfb480492010-01-13 21:46:36 +00004038//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004039// Token-based Operations.
4040//===----------------------------------------------------------------------===//
4041
4042/* CXToken layout:
4043 * int_data[0]: a CXTokenKind
4044 * int_data[1]: starting token location
4045 * int_data[2]: token length
4046 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004047 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004048 * otherwise unused.
4049 */
4050extern "C" {
4051
4052CXTokenKind clang_getTokenKind(CXToken CXTok) {
4053 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4054}
4055
4056CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4057 switch (clang_getTokenKind(CXTok)) {
4058 case CXToken_Identifier:
4059 case CXToken_Keyword:
4060 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004061 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4062 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004063
4064 case CXToken_Literal: {
4065 // We have stashed the starting pointer in the ptr_data field. Use it.
4066 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004067 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004068 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004069
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004070 case CXToken_Punctuation:
4071 case CXToken_Comment:
4072 break;
4073 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004074
4075 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004076 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004077 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004078 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004079 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004080
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004081 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4082 std::pair<FileID, unsigned> LocInfo
4083 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004084 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004085 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004086 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4087 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004088 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004089
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004090 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004091}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004092
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004093CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004094 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004095 if (!CXXUnit)
4096 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004097
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004098 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4099 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4100}
4101
4102CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004103 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004104 if (!CXXUnit)
4105 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004106
4107 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004108 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4109}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004110
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004111void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4112 CXToken **Tokens, unsigned *NumTokens) {
4113 if (Tokens)
4114 *Tokens = 0;
4115 if (NumTokens)
4116 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004117
Ted Kremeneka60ed472010-11-16 08:15:36 +00004118 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004119 if (!CXXUnit || !Tokens || !NumTokens)
4120 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004121
Douglas Gregorbdf60622010-03-05 21:16:25 +00004122 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4123
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004124 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004125 if (R.isInvalid())
4126 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004127
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004128 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4129 std::pair<FileID, unsigned> BeginLocInfo
4130 = SourceMgr.getDecomposedLoc(R.getBegin());
4131 std::pair<FileID, unsigned> EndLocInfo
4132 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004133
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004134 // Cannot tokenize across files.
4135 if (BeginLocInfo.first != EndLocInfo.first)
4136 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004137
4138 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004139 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004140 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004141 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004142 if (Invalid)
4143 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004144
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004145 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4146 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004147 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004148 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004149
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004150 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004151 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004152 llvm::SmallVector<CXToken, 32> CXTokens;
4153 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004154 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004155 do {
4156 // Lex the next token
4157 Lex.LexFromRawLexer(Tok);
4158 if (Tok.is(tok::eof))
4159 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004160
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004161 // Initialize the CXToken.
4162 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004163
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004164 // - Common fields
4165 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4166 CXTok.int_data[2] = Tok.getLength();
4167 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004168
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004169 // - Kind-specific fields
4170 if (Tok.isLiteral()) {
4171 CXTok.int_data[0] = CXToken_Literal;
4172 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004173 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004174 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004175 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004176 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004177
David Chisnall096428b2010-10-13 21:44:48 +00004178 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004179 CXTok.int_data[0] = CXToken_Keyword;
4180 }
4181 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004182 CXTok.int_data[0] = Tok.is(tok::identifier)
4183 ? CXToken_Identifier
4184 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004185 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004186 CXTok.ptr_data = II;
4187 } else if (Tok.is(tok::comment)) {
4188 CXTok.int_data[0] = CXToken_Comment;
4189 CXTok.ptr_data = 0;
4190 } else {
4191 CXTok.int_data[0] = CXToken_Punctuation;
4192 CXTok.ptr_data = 0;
4193 }
4194 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004195 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004196 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004197
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004198 if (CXTokens.empty())
4199 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004200
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004201 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4202 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4203 *NumTokens = CXTokens.size();
4204}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004205
Ted Kremenek6db61092010-05-05 00:55:15 +00004206void clang_disposeTokens(CXTranslationUnit TU,
4207 CXToken *Tokens, unsigned NumTokens) {
4208 free(Tokens);
4209}
4210
4211} // end: extern "C"
4212
4213//===----------------------------------------------------------------------===//
4214// Token annotation APIs.
4215//===----------------------------------------------------------------------===//
4216
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004217typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004218static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4219 CXCursor parent,
4220 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004221namespace {
4222class AnnotateTokensWorker {
4223 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004224 CXToken *Tokens;
4225 CXCursor *Cursors;
4226 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004227 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004228 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229 CursorVisitor AnnotateVis;
4230 SourceManager &SrcMgr;
4231
4232 bool MoreTokens() const { return TokIdx < NumTokens; }
4233 unsigned NextToken() const { return TokIdx; }
4234 void AdvanceToken() { ++TokIdx; }
4235 SourceLocation GetTokenLoc(unsigned tokI) {
4236 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4237 }
4238
Ted Kremenek6db61092010-05-05 00:55:15 +00004239public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004240 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004241 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004242 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004243 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004244 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004245 AnnotateVis(tu,
4246 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004247 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004248 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004249
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004250 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004251 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004252 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004253 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004254 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004255 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004256};
4257}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004258
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004259void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4260 // Walk the AST within the region of interest, annotating tokens
4261 // along the way.
4262 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004263
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004264 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4265 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004266 if (Pos != Annotated.end() &&
4267 (clang_isInvalid(Cursors[I].kind) ||
4268 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004269 Cursors[I] = Pos->second;
4270 }
4271
4272 // Finish up annotating any tokens left.
4273 if (!MoreTokens())
4274 return;
4275
4276 const CXCursor &C = clang_getNullCursor();
4277 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4278 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4279 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004280 }
4281}
4282
Ted Kremenek6db61092010-05-05 00:55:15 +00004283enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004284AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004286 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004287 if (cursorRange.isInvalid())
4288 return CXChildVisit_Recurse;
4289
Douglas Gregor4419b672010-10-21 06:10:04 +00004290 if (clang_isPreprocessing(cursor.kind)) {
4291 // For macro instantiations, just note where the beginning of the macro
4292 // instantiation occurs.
4293 if (cursor.kind == CXCursor_MacroInstantiation) {
4294 Annotated[Loc.int_data] = cursor;
4295 return CXChildVisit_Recurse;
4296 }
4297
Douglas Gregor4419b672010-10-21 06:10:04 +00004298 // Items in the preprocessing record are kept separate from items in
4299 // declarations, so we keep a separate token index.
4300 unsigned SavedTokIdx = TokIdx;
4301 TokIdx = PreprocessingTokIdx;
4302
4303 // Skip tokens up until we catch up to the beginning of the preprocessing
4304 // entry.
4305 while (MoreTokens()) {
4306 const unsigned I = NextToken();
4307 SourceLocation TokLoc = GetTokenLoc(I);
4308 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4309 case RangeBefore:
4310 AdvanceToken();
4311 continue;
4312 case RangeAfter:
4313 case RangeOverlap:
4314 break;
4315 }
4316 break;
4317 }
4318
4319 // Look at all of the tokens within this range.
4320 while (MoreTokens()) {
4321 const unsigned I = NextToken();
4322 SourceLocation TokLoc = GetTokenLoc(I);
4323 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4324 case RangeBefore:
4325 assert(0 && "Infeasible");
4326 case RangeAfter:
4327 break;
4328 case RangeOverlap:
4329 Cursors[I] = cursor;
4330 AdvanceToken();
4331 continue;
4332 }
4333 break;
4334 }
4335
4336 // Save the preprocessing token index; restore the non-preprocessing
4337 // token index.
4338 PreprocessingTokIdx = TokIdx;
4339 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004340 return CXChildVisit_Recurse;
4341 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004342
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004343 if (cursorRange.isInvalid())
4344 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004345
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004346 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4347
Ted Kremeneka333c662010-05-12 05:29:33 +00004348 // Adjust the annotated range based specific declarations.
4349 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4350 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004351 Decl *D = cxcursor::getCursorDecl(cursor);
4352 // Don't visit synthesized ObjC methods, since they have no syntatic
4353 // representation in the source.
4354 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4355 if (MD->isSynthesized())
4356 return CXChildVisit_Continue;
4357 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004358
4359 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004360 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004361 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4362 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4363 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4364 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4365 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004366 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004367
4368 if (StartLoc.isValid() && L.isValid() &&
4369 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4370 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004371 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004372
Ted Kremenek3f404602010-08-14 01:14:06 +00004373 // If the location of the cursor occurs within a macro instantiation, record
4374 // the spelling location of the cursor in our annotation map. We can then
4375 // paper over the token labelings during a post-processing step to try and
4376 // get cursor mappings for tokens that are the *arguments* of a macro
4377 // instantiation.
4378 if (L.isMacroID()) {
4379 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4380 // Only invalidate the old annotation if it isn't part of a preprocessing
4381 // directive. Here we assume that the default construction of CXCursor
4382 // results in CXCursor.kind being an initialized value (i.e., 0). If
4383 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004384
Ted Kremenek3f404602010-08-14 01:14:06 +00004385 CXCursor &oldC = Annotated[rawEncoding];
4386 if (!clang_isPreprocessing(oldC.kind))
4387 oldC = cursor;
4388 }
4389
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004390 const enum CXCursorKind K = clang_getCursorKind(parent);
4391 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004392 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4393 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004394
4395 while (MoreTokens()) {
4396 const unsigned I = NextToken();
4397 SourceLocation TokLoc = GetTokenLoc(I);
4398 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4399 case RangeBefore:
4400 Cursors[I] = updateC;
4401 AdvanceToken();
4402 continue;
4403 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004404 case RangeOverlap:
4405 break;
4406 }
4407 break;
4408 }
4409
4410 // Visit children to get their cursor information.
4411 const unsigned BeforeChildren = NextToken();
4412 VisitChildren(cursor);
4413 const unsigned AfterChildren = NextToken();
4414
4415 // Adjust 'Last' to the last token within the extent of the cursor.
4416 while (MoreTokens()) {
4417 const unsigned I = NextToken();
4418 SourceLocation TokLoc = GetTokenLoc(I);
4419 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4420 case RangeBefore:
4421 assert(0 && "Infeasible");
4422 case RangeAfter:
4423 break;
4424 case RangeOverlap:
4425 Cursors[I] = updateC;
4426 AdvanceToken();
4427 continue;
4428 }
4429 break;
4430 }
4431 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004432
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004433 // Scan the tokens that are at the beginning of the cursor, but are not
4434 // capture by the child cursors.
4435
4436 // For AST elements within macros, rely on a post-annotate pass to
4437 // to correctly annotate the tokens with cursors. Otherwise we can
4438 // get confusing results of having tokens that map to cursors that really
4439 // are expanded by an instantiation.
4440 if (L.isMacroID())
4441 cursor = clang_getNullCursor();
4442
4443 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4444 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4445 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004446
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004447 Cursors[I] = cursor;
4448 }
4449 // Scan the tokens that are at the end of the cursor, but are not captured
4450 // but the child cursors.
4451 for (unsigned I = AfterChildren; I != Last; ++I)
4452 Cursors[I] = cursor;
4453
4454 TokIdx = Last;
4455 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004456}
4457
Ted Kremenek6db61092010-05-05 00:55:15 +00004458static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4459 CXCursor parent,
4460 CXClientData client_data) {
4461 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4462}
4463
Ted Kremenekab979612010-11-11 08:05:23 +00004464// This gets run a separate thread to avoid stack blowout.
4465static void runAnnotateTokensWorker(void *UserData) {
4466 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4467}
4468
Ted Kremenek6db61092010-05-05 00:55:15 +00004469extern "C" {
4470
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004471void clang_annotateTokens(CXTranslationUnit TU,
4472 CXToken *Tokens, unsigned NumTokens,
4473 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004474
4475 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004476 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004477
Douglas Gregor4419b672010-10-21 06:10:04 +00004478 // Any token we don't specifically annotate will have a NULL cursor.
4479 CXCursor C = clang_getNullCursor();
4480 for (unsigned I = 0; I != NumTokens; ++I)
4481 Cursors[I] = C;
4482
Ted Kremeneka60ed472010-11-16 08:15:36 +00004483 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004484 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004485 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004486
Douglas Gregorbdf60622010-03-05 21:16:25 +00004487 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004488
Douglas Gregor0396f462010-03-19 05:22:59 +00004489 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004490 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004491 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4492 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004493 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4494 clang_getTokenLocation(TU,
4495 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004496
Douglas Gregor0396f462010-03-19 05:22:59 +00004497 // A mapping from the source locations found when re-lexing or traversing the
4498 // region of interest to the corresponding cursors.
4499 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004500
4501 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004502 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004503 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4504 std::pair<FileID, unsigned> BeginLocInfo
4505 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4506 std::pair<FileID, unsigned> EndLocInfo
4507 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004508
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004509 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004510 bool Invalid = false;
4511 if (BeginLocInfo.first == EndLocInfo.first &&
4512 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4513 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004514 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4515 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004516 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004517 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004518 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004519
4520 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004521 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004522 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004523 Token Tok;
4524 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004525
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004526 reprocess:
4527 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4528 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004529 // don't see it while preprocessing these tokens later, but keep track
4530 // of all of the token locations inside this preprocessing directive so
4531 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004532 //
4533 // FIXME: Some simple tests here could identify macro definitions and
4534 // #undefs, to provide specific cursor kinds for those.
4535 std::vector<SourceLocation> Locations;
4536 do {
4537 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004538 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004539 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004540
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004541 using namespace cxcursor;
4542 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004543 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4544 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004545 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004546 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4547 Annotated[Locations[I].getRawEncoding()] = Cursor;
4548 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004549
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004550 if (Tok.isAtStartOfLine())
4551 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004552
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004553 continue;
4554 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004555
Douglas Gregor48072312010-03-18 15:23:44 +00004556 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004557 break;
4558 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004559 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004560
Douglas Gregor0396f462010-03-19 05:22:59 +00004561 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004562 // a specific cursor.
4563 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004564 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004565
4566 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004567 // FIXME: We use a ridiculous stack size here because the data-recursion
4568 // algorithm uses a large stack frame than the non-data recursive version,
4569 // and AnnotationTokensWorker currently transforms the data-recursion
4570 // algorithm back into a traditional recursion by explicitly calling
4571 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004572 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004573 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4574 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004575 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4576 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004577}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004578} // end: extern "C"
4579
4580//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004581// Operations for querying linkage of a cursor.
4582//===----------------------------------------------------------------------===//
4583
4584extern "C" {
4585CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004586 if (!clang_isDeclaration(cursor.kind))
4587 return CXLinkage_Invalid;
4588
Ted Kremenek16b42592010-03-03 06:36:57 +00004589 Decl *D = cxcursor::getCursorDecl(cursor);
4590 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4591 switch (ND->getLinkage()) {
4592 case NoLinkage: return CXLinkage_NoLinkage;
4593 case InternalLinkage: return CXLinkage_Internal;
4594 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4595 case ExternalLinkage: return CXLinkage_External;
4596 };
4597
4598 return CXLinkage_Invalid;
4599}
4600} // end: extern "C"
4601
4602//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004603// Operations for querying language of a cursor.
4604//===----------------------------------------------------------------------===//
4605
4606static CXLanguageKind getDeclLanguage(const Decl *D) {
4607 switch (D->getKind()) {
4608 default:
4609 break;
4610 case Decl::ImplicitParam:
4611 case Decl::ObjCAtDefsField:
4612 case Decl::ObjCCategory:
4613 case Decl::ObjCCategoryImpl:
4614 case Decl::ObjCClass:
4615 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004616 case Decl::ObjCForwardProtocol:
4617 case Decl::ObjCImplementation:
4618 case Decl::ObjCInterface:
4619 case Decl::ObjCIvar:
4620 case Decl::ObjCMethod:
4621 case Decl::ObjCProperty:
4622 case Decl::ObjCPropertyImpl:
4623 case Decl::ObjCProtocol:
4624 return CXLanguage_ObjC;
4625 case Decl::CXXConstructor:
4626 case Decl::CXXConversion:
4627 case Decl::CXXDestructor:
4628 case Decl::CXXMethod:
4629 case Decl::CXXRecord:
4630 case Decl::ClassTemplate:
4631 case Decl::ClassTemplatePartialSpecialization:
4632 case Decl::ClassTemplateSpecialization:
4633 case Decl::Friend:
4634 case Decl::FriendTemplate:
4635 case Decl::FunctionTemplate:
4636 case Decl::LinkageSpec:
4637 case Decl::Namespace:
4638 case Decl::NamespaceAlias:
4639 case Decl::NonTypeTemplateParm:
4640 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004641 case Decl::TemplateTemplateParm:
4642 case Decl::TemplateTypeParm:
4643 case Decl::UnresolvedUsingTypename:
4644 case Decl::UnresolvedUsingValue:
4645 case Decl::Using:
4646 case Decl::UsingDirective:
4647 case Decl::UsingShadow:
4648 return CXLanguage_CPlusPlus;
4649 }
4650
4651 return CXLanguage_C;
4652}
4653
4654extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004655
4656enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4657 if (clang_isDeclaration(cursor.kind))
4658 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4659 if (D->hasAttr<UnavailableAttr>() ||
4660 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4661 return CXAvailability_Available;
4662
4663 if (D->hasAttr<DeprecatedAttr>())
4664 return CXAvailability_Deprecated;
4665 }
4666
4667 return CXAvailability_Available;
4668}
4669
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004670CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4671 if (clang_isDeclaration(cursor.kind))
4672 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4673
4674 return CXLanguage_Invalid;
4675}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004676
4677 /// \brief If the given cursor is the "templated" declaration
4678 /// descibing a class or function template, return the class or
4679 /// function template.
4680static Decl *maybeGetTemplateCursor(Decl *D) {
4681 if (!D)
4682 return 0;
4683
4684 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4685 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4686 return FunTmpl;
4687
4688 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4689 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4690 return ClassTmpl;
4691
4692 return D;
4693}
4694
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004695CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4696 if (clang_isDeclaration(cursor.kind)) {
4697 if (Decl *D = getCursorDecl(cursor)) {
4698 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004699 if (!DC)
4700 return clang_getNullCursor();
4701
4702 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4703 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004704 }
4705 }
4706
4707 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4708 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004709 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004710 }
4711
4712 return clang_getNullCursor();
4713}
4714
4715CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4716 if (clang_isDeclaration(cursor.kind)) {
4717 if (Decl *D = getCursorDecl(cursor)) {
4718 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004719 if (!DC)
4720 return clang_getNullCursor();
4721
4722 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4723 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004724 }
4725 }
4726
4727 // FIXME: Note that we can't easily compute the lexical context of a
4728 // statement or expression, so we return nothing.
4729 return clang_getNullCursor();
4730}
4731
Douglas Gregor9f592342010-10-01 20:25:15 +00004732static void CollectOverriddenMethods(DeclContext *Ctx,
4733 ObjCMethodDecl *Method,
4734 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4735 if (!Ctx)
4736 return;
4737
4738 // If we have a class or category implementation, jump straight to the
4739 // interface.
4740 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4741 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4742
4743 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4744 if (!Container)
4745 return;
4746
4747 // Check whether we have a matching method at this level.
4748 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4749 Method->isInstanceMethod()))
4750 if (Method != Overridden) {
4751 // We found an override at this level; there is no need to look
4752 // into other protocols or categories.
4753 Methods.push_back(Overridden);
4754 return;
4755 }
4756
4757 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4758 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4759 PEnd = Protocol->protocol_end();
4760 P != PEnd; ++P)
4761 CollectOverriddenMethods(*P, Method, Methods);
4762 }
4763
4764 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4765 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4766 PEnd = Category->protocol_end();
4767 P != PEnd; ++P)
4768 CollectOverriddenMethods(*P, Method, Methods);
4769 }
4770
4771 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4772 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4773 PEnd = Interface->protocol_end();
4774 P != PEnd; ++P)
4775 CollectOverriddenMethods(*P, Method, Methods);
4776
4777 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4778 Category; Category = Category->getNextClassCategory())
4779 CollectOverriddenMethods(Category, Method, Methods);
4780
4781 // We only look into the superclass if we haven't found anything yet.
4782 if (Methods.empty())
4783 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4784 return CollectOverriddenMethods(Super, Method, Methods);
4785 }
4786}
4787
4788void clang_getOverriddenCursors(CXCursor cursor,
4789 CXCursor **overridden,
4790 unsigned *num_overridden) {
4791 if (overridden)
4792 *overridden = 0;
4793 if (num_overridden)
4794 *num_overridden = 0;
4795 if (!overridden || !num_overridden)
4796 return;
4797
4798 if (!clang_isDeclaration(cursor.kind))
4799 return;
4800
4801 Decl *D = getCursorDecl(cursor);
4802 if (!D)
4803 return;
4804
4805 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004806 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004807 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4808 *num_overridden = CXXMethod->size_overridden_methods();
4809 if (!*num_overridden)
4810 return;
4811
4812 *overridden = new CXCursor [*num_overridden];
4813 unsigned I = 0;
4814 for (CXXMethodDecl::method_iterator
4815 M = CXXMethod->begin_overridden_methods(),
4816 MEnd = CXXMethod->end_overridden_methods();
4817 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004818 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004819 return;
4820 }
4821
4822 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4823 if (!Method)
4824 return;
4825
4826 // Handle Objective-C methods.
4827 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4828 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4829
4830 if (Methods.empty())
4831 return;
4832
4833 *num_overridden = Methods.size();
4834 *overridden = new CXCursor [Methods.size()];
4835 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004836 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004837}
4838
4839void clang_disposeOverriddenCursors(CXCursor *overridden) {
4840 delete [] overridden;
4841}
4842
Douglas Gregorecdcb882010-10-20 22:00:55 +00004843CXFile clang_getIncludedFile(CXCursor cursor) {
4844 if (cursor.kind != CXCursor_InclusionDirective)
4845 return 0;
4846
4847 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4848 return (void *)ID->getFile();
4849}
4850
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004851} // end: extern "C"
4852
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004853
4854//===----------------------------------------------------------------------===//
4855// C++ AST instrospection.
4856//===----------------------------------------------------------------------===//
4857
4858extern "C" {
4859unsigned clang_CXXMethod_isStatic(CXCursor C) {
4860 if (!clang_isDeclaration(C.kind))
4861 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004862
4863 CXXMethodDecl *Method = 0;
4864 Decl *D = cxcursor::getCursorDecl(C);
4865 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4866 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4867 else
4868 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4869 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004870}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004871
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004872} // end: extern "C"
4873
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004874//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004875// Attribute introspection.
4876//===----------------------------------------------------------------------===//
4877
4878extern "C" {
4879CXType clang_getIBOutletCollectionType(CXCursor C) {
4880 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004881 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004882
4883 IBOutletCollectionAttr *A =
4884 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4885
Ted Kremeneka60ed472010-11-16 08:15:36 +00004886 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004887}
4888} // end: extern "C"
4889
4890//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004891// Misc. utility functions.
4892//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004893
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004894/// Default to using an 8 MB stack size on "safety" threads.
4895static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004896
4897namespace clang {
4898
4899bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004900 void (*Fn)(void*), void *UserData,
4901 unsigned Size) {
4902 if (!Size)
4903 Size = GetSafetyThreadStackSize();
4904 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004905 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4906 return CRC.RunSafely(Fn, UserData);
4907}
4908
4909unsigned GetSafetyThreadStackSize() {
4910 return SafetyStackThreadSize;
4911}
4912
4913void SetSafetyThreadStackSize(unsigned Value) {
4914 SafetyStackThreadSize = Value;
4915}
4916
4917}
4918
Ted Kremenek04bb7162010-01-22 22:44:15 +00004919extern "C" {
4920
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004921CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004922 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004923}
4924
4925} // end: extern "C"