blob: c244bff50f029c1d3614b4ae938e7ed5b75547be [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);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000345
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000346 // Data-recursive visitor functions.
347 bool IsInRegionOfInterest(CXCursor C);
348 bool RunVisitorWorkList(VisitorWorkList &WL);
349 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000350 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000351};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000352
Ted Kremenekab188932010-01-05 19:32:54 +0000353} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000354
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000355static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000356static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
357
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000358
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000359RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000360 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361}
362
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363/// \brief Visit the given cursor and, if requested by the visitor,
364/// its children.
365///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000366/// \param Cursor the cursor to visit.
367///
368/// \param CheckRegionOfInterest if true, then the caller already checked that
369/// this cursor is within the region of interest.
370///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371/// \returns true if the visitation should be aborted, false if it
372/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000373bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 if (clang_isInvalid(Cursor.kind))
375 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000376
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 if (clang_isDeclaration(Cursor.kind)) {
378 Decl *D = getCursorDecl(Cursor);
379 assert(D && "Invalid declaration cursor");
380 if (D->getPCHLevel() > MaxPCHLevel)
381 return false;
382
383 if (D->isImplicit())
384 return false;
385 }
386
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387 // If we have a range of interest, and this cursor doesn't intersect with it,
388 // we're done.
389 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000390 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000391 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392 return false;
393 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000394
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 switch (Visitor(Cursor, Parent, ClientData)) {
396 case CXChildVisit_Break:
397 return true;
398
399 case CXChildVisit_Continue:
400 return false;
401
402 case CXChildVisit_Recurse:
403 return VisitChildren(Cursor);
404 }
405
Douglas Gregorfd643772010-01-25 16:45:46 +0000406 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407}
408
Douglas Gregor788f5a12010-03-20 00:41:21 +0000409std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
410CursorVisitor::getPreprocessedEntities() {
411 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000412 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000413
414 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000415 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
416
417 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
418 // If we would only look at local declarations but we have a region of
419 // interest, check whether that region of interest is in the main file.
420 // If not, we should traverse all declarations.
421 // FIXME: My kingdom for a proper binary search approach to finding
422 // cursors!
423 std::pair<FileID, unsigned> Location
424 = AU->getSourceManager().getDecomposedInstantiationLoc(
425 RegionOfInterest.getBegin());
426 if (Location.first != AU->getSourceManager().getMainFileID())
427 OnlyLocalDecls = false;
428 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000429
Douglas Gregor89d99802010-11-30 06:16:57 +0000430 PreprocessingRecord::iterator StartEntity, EndEntity;
431 if (OnlyLocalDecls) {
432 StartEntity = AU->pp_entity_begin();
433 EndEntity = AU->pp_entity_end();
434 } else {
435 StartEntity = PPRec.begin();
436 EndEntity = PPRec.end();
437 }
438
Douglas Gregor788f5a12010-03-20 00:41:21 +0000439 // There is no region of interest; we have to walk everything.
440 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000441 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000442
443 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000444 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000445 std::pair<FileID, unsigned> Begin
446 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
447 std::pair<FileID, unsigned> End
448 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
449
450 // The region of interest spans files; we have to walk everything.
451 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000452 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000453
454 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000455 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000456 if (ByFileMap.empty()) {
457 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000458 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000459 std::pair<FileID, unsigned> P
460 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000461
Douglas Gregor788f5a12010-03-20 00:41:21 +0000462 ByFileMap[P.first].push_back(*E);
463 }
464 }
465
466 return std::make_pair(ByFileMap[Begin.first].begin(),
467 ByFileMap[Begin.first].end());
468}
469
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000471///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472/// \returns true if the visitation should be aborted, false if it
473/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000474bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000475 if (clang_isReference(Cursor.kind)) {
476 // By definition, references have no children.
477 return false;
478 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479
480 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000481 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000482 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000483
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 if (clang_isDeclaration(Cursor.kind)) {
485 Decl *D = getCursorDecl(Cursor);
486 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000487 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000489
Douglas Gregora59e3902010-01-21 23:27:09 +0000490 if (clang_isStatement(Cursor.kind))
491 return Visit(getCursorStmt(Cursor));
492 if (clang_isExpression(Cursor.kind))
493 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000494
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000496 CXTranslationUnit tu = getCursorTU(Cursor);
497 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000498 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
499 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000500 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
501 TLEnd = CXXUnit->top_level_end();
502 TL != TLEnd; ++TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000503 if (Visit(MakeCXCursor(*TL, tu), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000504 return true;
505 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000506 } else if (VisitDeclContext(
507 CXXUnit->getASTContext().getTranslationUnitDecl()))
508 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000509
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000511 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 // FIXME: Once we have the ability to deserialize a preprocessing record,
513 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000514 PreprocessingRecord::iterator E, EEnd;
515 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000516 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000517 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000519
Douglas Gregor0396f462010-03-19 05:22:59 +0000520 continue;
521 }
522
523 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000524 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
Douglas Gregor0396f462010-03-19 05:22:59 +0000525 return true;
526
527 continue;
528 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000529
530 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000531 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
Douglas Gregorecdcb882010-10-20 22:00:55 +0000532 return true;
533
534 continue;
535 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000536 }
537 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000538 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000540
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000542 return false;
543}
544
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000545bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000546 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
547 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000548
Ted Kremenek664cffd2010-07-22 11:30:19 +0000549 if (Stmt *Body = B->getBody())
550 return Visit(MakeCXCursor(Body, StmtParent, TU));
551
552 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000553}
554
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000555llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
556 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000557 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000558 if (Range.isInvalid())
559 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000560
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000561 switch (CompareRegionOfInterest(Range)) {
562 case RangeBefore:
563 // This declaration comes before the region of interest; skip it.
564 return llvm::Optional<bool>();
565
566 case RangeAfter:
567 // This declaration comes after the region of interest; we're done.
568 return false;
569
570 case RangeOverlap:
571 // This declaration overlaps the region of interest; visit it.
572 break;
573 }
574 }
575 return true;
576}
577
578bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
579 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
580
581 // FIXME: Eventually remove. This part of a hack to support proper
582 // iteration over all Decls contained lexically within an ObjC container.
583 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
584 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
585
586 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000587 Decl *D = *I;
588 if (D->getLexicalDeclContext() != DC)
589 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000590 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000591 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
592 if (!V.hasValue())
593 continue;
594 if (!V.getValue())
595 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000596 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597 return true;
598 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000599 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000600}
601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
603 llvm_unreachable("Translation units are visited directly by Visit()");
604 return false;
605}
606
607bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
608 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
609 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000610
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000611 return false;
612}
613
614bool CursorVisitor::VisitTagDecl(TagDecl *D) {
615 return VisitDeclContext(D);
616}
617
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000618bool CursorVisitor::VisitClassTemplateSpecializationDecl(
619 ClassTemplateSpecializationDecl *D) {
620 bool ShouldVisitBody = false;
621 switch (D->getSpecializationKind()) {
622 case TSK_Undeclared:
623 case TSK_ImplicitInstantiation:
624 // Nothing to visit
625 return false;
626
627 case TSK_ExplicitInstantiationDeclaration:
628 case TSK_ExplicitInstantiationDefinition:
629 break;
630
631 case TSK_ExplicitSpecialization:
632 ShouldVisitBody = true;
633 break;
634 }
635
636 // Visit the template arguments used in the specialization.
637 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
638 TypeLoc TL = SpecType->getTypeLoc();
639 if (TemplateSpecializationTypeLoc *TSTLoc
640 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
641 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
642 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
643 return true;
644 }
645 }
646
647 if (ShouldVisitBody && VisitCXXRecordDecl(D))
648 return true;
649
650 return false;
651}
652
Douglas Gregor74dbe642010-08-31 19:31:58 +0000653bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
654 ClassTemplatePartialSpecializationDecl *D) {
655 // FIXME: Visit the "outer" template parameter lists on the TagDecl
656 // before visiting these template parameters.
657 if (VisitTemplateParameters(D->getTemplateParameters()))
658 return true;
659
660 // Visit the partial specialization arguments.
661 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
662 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
663 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
664 return true;
665
666 return VisitCXXRecordDecl(D);
667}
668
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000669bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000670 // Visit the default argument.
671 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
672 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
673 if (Visit(DefArg->getTypeLoc()))
674 return true;
675
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000676 return false;
677}
678
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000679bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
680 if (Expr *Init = D->getInitExpr())
681 return Visit(MakeCXCursor(Init, StmtParent, TU));
682 return false;
683}
684
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000685bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
686 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
687 if (Visit(TSInfo->getTypeLoc()))
688 return true;
689
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000690 // Visit the nested-name-specifier, if present.
691 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
692 if (VisitNestedNameSpecifierLoc(QualifierLoc))
693 return true;
694
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000695 return false;
696}
697
Douglas Gregora67e03f2010-09-09 21:42:20 +0000698/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000699static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
700 CXXCtorInitializer const * const *X
701 = static_cast<CXXCtorInitializer const * const *>(Xp);
702 CXXCtorInitializer const * const *Y
703 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000704
705 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
706 return -1;
707 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
708 return 1;
709 else
710 return 0;
711}
712
Douglas Gregorb1373d02010-01-20 20:59:29 +0000713bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000714 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
715 // Visit the function declaration's syntactic components in the order
716 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000717 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000718 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
719
720 // If we have a function declared directly (without the use of a typedef),
721 // visit just the return type. Otherwise, just visit the function's type
722 // now.
723 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
724 (!FTL && Visit(TL)))
725 return true;
726
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000727 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000728 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
729 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000730 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000731
732 // Visit the declaration name.
733 if (VisitDeclarationNameInfo(ND->getNameInfo()))
734 return true;
735
736 // FIXME: Visit explicitly-specified template arguments!
737
738 // Visit the function parameters, if we have a function type.
739 if (FTL && VisitFunctionTypeLoc(*FTL, true))
740 return true;
741
742 // FIXME: Attributes?
743 }
744
Douglas Gregora67e03f2010-09-09 21:42:20 +0000745 if (ND->isThisDeclarationADefinition()) {
746 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
747 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000748 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000749 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
750 IEnd = Constructor->init_end();
751 I != IEnd; ++I) {
752 if (!(*I)->isWritten())
753 continue;
754
755 WrittenInits.push_back(*I);
756 }
757
758 // Sort the initializers in source order
759 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000760 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761
762 // Visit the initializers in source order
763 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000764 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000765 if (Init->isAnyMemberInitializer()) {
766 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000767 Init->getMemberLocation(), TU)))
768 return true;
769 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
770 if (Visit(BaseInfo->getTypeLoc()))
771 return true;
772 }
773
774 // Visit the initializer value.
775 if (Expr *Initializer = Init->getInit())
776 if (Visit(MakeCXCursor(Initializer, ND, TU)))
777 return true;
778 }
779 }
780
781 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
782 return true;
783 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregorb1373d02010-01-20 20:59:29 +0000785 return false;
786}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
789 if (VisitDeclaratorDecl(D))
790 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000791
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000792 if (Expr *BitWidth = D->getBitWidth())
793 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 return false;
796}
797
798bool CursorVisitor::VisitVarDecl(VarDecl *D) {
799 if (VisitDeclaratorDecl(D))
800 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 if (Expr *Init = D->getInit())
803 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 return false;
806}
807
Douglas Gregor84b51d72010-09-01 20:16:53 +0000808bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
809 if (VisitDeclaratorDecl(D))
810 return true;
811
812 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
813 if (Expr *DefArg = D->getDefaultArgument())
814 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
815
816 return false;
817}
818
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000819bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
820 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
821 // before visiting these template parameters.
822 if (VisitTemplateParameters(D->getTemplateParameters()))
823 return true;
824
825 return VisitFunctionDecl(D->getTemplatedDecl());
826}
827
Douglas Gregor39d6f072010-08-31 19:02:00 +0000828bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
829 // FIXME: Visit the "outer" template parameter lists on the TagDecl
830 // before visiting these template parameters.
831 if (VisitTemplateParameters(D->getTemplateParameters()))
832 return true;
833
834 return VisitCXXRecordDecl(D->getTemplatedDecl());
835}
836
Douglas Gregor84b51d72010-09-01 20:16:53 +0000837bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
838 if (VisitTemplateParameters(D->getTemplateParameters()))
839 return true;
840
841 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
842 VisitTemplateArgumentLoc(D->getDefaultArgument()))
843 return true;
844
845 return false;
846}
847
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000849 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
850 if (Visit(TSInfo->getTypeLoc()))
851 return true;
852
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 PEnd = ND->param_end();
855 P != PEnd; ++P) {
856 if (Visit(MakeCXCursor(*P, TU)))
857 return true;
858 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000859
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860 if (ND->isThisDeclarationADefinition() &&
861 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
862 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000863
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000864 return false;
865}
866
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000867namespace {
868 struct ContainerDeclsSort {
869 SourceManager &SM;
870 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
871 bool operator()(Decl *A, Decl *B) {
872 SourceLocation L_A = A->getLocStart();
873 SourceLocation L_B = B->getLocStart();
874 assert(L_A.isValid() && L_B.isValid());
875 return SM.isBeforeInTranslationUnit(L_A, L_B);
876 }
877 };
878}
879
Douglas Gregora59e3902010-01-21 23:27:09 +0000880bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000881 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
882 // an @implementation can lexically contain Decls that are not properly
883 // nested in the AST. When we identify such cases, we need to retrofit
884 // this nesting here.
885 if (!DI_current)
886 return VisitDeclContext(D);
887
888 // Scan the Decls that immediately come after the container
889 // in the current DeclContext. If any fall within the
890 // container's lexical region, stash them into a vector
891 // for later processing.
892 llvm::SmallVector<Decl *, 24> DeclsInContainer;
893 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000894 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000895 if (EndLoc.isValid()) {
896 DeclContext::decl_iterator next = *DI_current;
897 while (++next != DE_current) {
898 Decl *D_next = *next;
899 if (!D_next)
900 break;
901 SourceLocation L = D_next->getLocStart();
902 if (!L.isValid())
903 break;
904 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
905 *DI_current = next;
906 DeclsInContainer.push_back(D_next);
907 continue;
908 }
909 break;
910 }
911 }
912
913 // The common case.
914 if (DeclsInContainer.empty())
915 return VisitDeclContext(D);
916
917 // Get all the Decls in the DeclContext, and sort them with the
918 // additional ones we've collected. Then visit them.
919 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
920 I!=E; ++I) {
921 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000922 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
923 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000924 continue;
925 DeclsInContainer.push_back(subDecl);
926 }
927
928 // Now sort the Decls so that they appear in lexical order.
929 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
930 ContainerDeclsSort(SM));
931
932 // Now visit the decls.
933 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
934 E = DeclsInContainer.end(); I != E; ++I) {
935 CXCursor Cursor = MakeCXCursor(*I, TU);
936 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
937 if (!V.hasValue())
938 continue;
939 if (!V.getValue())
940 return false;
941 if (Visit(Cursor, true))
942 return true;
943 }
944 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000945}
946
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000948 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
949 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000950 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000951
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000952 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
953 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
954 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000955 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000956 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000957
Douglas Gregora59e3902010-01-21 23:27:09 +0000958 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000959}
960
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000961bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
962 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
963 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
964 E = PID->protocol_end(); I != E; ++I, ++PL)
965 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
966 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000967
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000968 return VisitObjCContainerDecl(PID);
969}
970
Ted Kremenek23173d72010-05-18 21:09:07 +0000971bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000972 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000973 return true;
974
Ted Kremenek23173d72010-05-18 21:09:07 +0000975 // FIXME: This implements a workaround with @property declarations also being
976 // installed in the DeclContext for the @interface. Eventually this code
977 // should be removed.
978 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
979 if (!CDecl || !CDecl->IsClassExtension())
980 return false;
981
982 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
983 if (!ID)
984 return false;
985
986 IdentifierInfo *PropertyId = PD->getIdentifier();
987 ObjCPropertyDecl *prevDecl =
988 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
989
990 if (!prevDecl)
991 return false;
992
993 // Visit synthesized methods since they will be skipped when visiting
994 // the @interface.
995 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000996 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000997 if (Visit(MakeCXCursor(MD, TU)))
998 return true;
999
1000 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001001 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001002 if (Visit(MakeCXCursor(MD, TU)))
1003 return true;
1004
1005 return false;
1006}
1007
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001009 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001010 if (D->getSuperClass() &&
1011 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001013 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001016 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1017 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1018 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001019 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001020 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021
Douglas Gregora59e3902010-01-21 23:27:09 +00001022 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001023}
1024
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001025bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1026 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001027}
1028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001030 // 'ID' could be null when dealing with invalid code.
1031 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1032 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001035 return VisitObjCImplDecl(D);
1036}
1037
1038bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1039#if 0
1040 // Issue callbacks for super class.
1041 // FIXME: No source location information!
1042 if (D->getSuperClass() &&
1043 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001044 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001045 TU)))
1046 return true;
1047#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001049 return VisitObjCImplDecl(D);
1050}
1051
1052bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1053 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1054 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1055 E = D->protocol_end();
1056 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001057 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001058 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001059
1060 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001061}
1062
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001063bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1064 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1065 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1066 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001067
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001068 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001069}
1070
Douglas Gregora4ffd852010-11-17 01:03:52 +00001071bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1072 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1073 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1074
1075 return false;
1076}
1077
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001078bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1079 return VisitDeclContext(D);
1080}
1081
Douglas Gregor69319002010-08-31 23:48:11 +00001082bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001083 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001084 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1085 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001087
1088 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1089 D->getTargetNameLoc(), TU));
1090}
1091
Douglas Gregor7e242562010-09-01 19:52:22 +00001092bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001093 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001094 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1095 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001097 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001098
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001099 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1100 return true;
1101
Douglas Gregor7e242562010-09-01 19:52:22 +00001102 return VisitDeclarationNameInfo(D->getNameInfo());
1103}
1104
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001105bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001107 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1108 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001109 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001110
1111 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1112 D->getIdentLocation(), TU));
1113}
1114
Douglas Gregor7e242562010-09-01 19:52:22 +00001115bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001116 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001117 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1118 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001119 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001120 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121
Douglas Gregor7e242562010-09-01 19:52:22 +00001122 return VisitDeclarationNameInfo(D->getNameInfo());
1123}
1124
1125bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1126 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001127 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001128 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1129 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001130 return true;
1131
Douglas Gregor7e242562010-09-01 19:52:22 +00001132 return false;
1133}
1134
Douglas Gregor01829d32010-08-31 14:41:23 +00001135bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1136 switch (Name.getName().getNameKind()) {
1137 case clang::DeclarationName::Identifier:
1138 case clang::DeclarationName::CXXLiteralOperatorName:
1139 case clang::DeclarationName::CXXOperatorName:
1140 case clang::DeclarationName::CXXUsingDirective:
1141 return false;
1142
1143 case clang::DeclarationName::CXXConstructorName:
1144 case clang::DeclarationName::CXXDestructorName:
1145 case clang::DeclarationName::CXXConversionFunctionName:
1146 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1147 return Visit(TSInfo->getTypeLoc());
1148 return false;
1149
1150 case clang::DeclarationName::ObjCZeroArgSelector:
1151 case clang::DeclarationName::ObjCOneArgSelector:
1152 case clang::DeclarationName::ObjCMultiArgSelector:
1153 // FIXME: Per-identifier location info?
1154 return false;
1155 }
1156
1157 return false;
1158}
1159
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001160bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1161 SourceRange Range) {
1162 // FIXME: This whole routine is a hack to work around the lack of proper
1163 // source information in nested-name-specifiers (PR5791). Since we do have
1164 // a beginning source location, we can visit the first component of the
1165 // nested-name-specifier, if it's a single-token component.
1166 if (!NNS)
1167 return false;
1168
1169 // Get the first component in the nested-name-specifier.
1170 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1171 NNS = Prefix;
1172
1173 switch (NNS->getKind()) {
1174 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001175 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1176 TU));
1177
Douglas Gregor14aba762011-02-24 02:36:08 +00001178 case NestedNameSpecifier::NamespaceAlias:
1179 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1180 Range.getBegin(), TU));
1181
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001182 case NestedNameSpecifier::TypeSpec: {
1183 // If the type has a form where we know that the beginning of the source
1184 // range matches up with a reference cursor. Visit the appropriate reference
1185 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001186 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001187 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1188 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1189 if (const TagType *Tag = dyn_cast<TagType>(T))
1190 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1191 if (const TemplateSpecializationType *TST
1192 = dyn_cast<TemplateSpecializationType>(T))
1193 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1194 break;
1195 }
1196
1197 case NestedNameSpecifier::TypeSpecWithTemplate:
1198 case NestedNameSpecifier::Global:
1199 case NestedNameSpecifier::Identifier:
1200 break;
1201 }
1202
1203 return false;
1204}
1205
Douglas Gregordc355712011-02-25 00:36:19 +00001206bool
1207CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1208 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1209 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1210 Qualifiers.push_back(Qualifier);
1211
1212 while (!Qualifiers.empty()) {
1213 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1214 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1215 switch (NNS->getKind()) {
1216 case NestedNameSpecifier::Namespace:
1217 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001218 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001219 TU)))
1220 return true;
1221
1222 break;
1223
1224 case NestedNameSpecifier::NamespaceAlias:
1225 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001226 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001227 TU)))
1228 return true;
1229
1230 break;
1231
1232 case NestedNameSpecifier::TypeSpec:
1233 case NestedNameSpecifier::TypeSpecWithTemplate:
1234 if (Visit(Q.getTypeLoc()))
1235 return true;
1236
1237 break;
1238
1239 case NestedNameSpecifier::Global:
1240 case NestedNameSpecifier::Identifier:
1241 break;
1242 }
1243 }
1244
1245 return false;
1246}
1247
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001248bool CursorVisitor::VisitTemplateParameters(
1249 const TemplateParameterList *Params) {
1250 if (!Params)
1251 return false;
1252
1253 for (TemplateParameterList::const_iterator P = Params->begin(),
1254 PEnd = Params->end();
1255 P != PEnd; ++P) {
1256 if (Visit(MakeCXCursor(*P, TU)))
1257 return true;
1258 }
1259
1260 return false;
1261}
1262
Douglas Gregor0b36e612010-08-31 20:37:03 +00001263bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1264 switch (Name.getKind()) {
1265 case TemplateName::Template:
1266 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1267
1268 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001269 // Visit the overloaded template set.
1270 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1271 return true;
1272
Douglas Gregor0b36e612010-08-31 20:37:03 +00001273 return false;
1274
1275 case TemplateName::DependentTemplate:
1276 // FIXME: Visit nested-name-specifier.
1277 return false;
1278
1279 case TemplateName::QualifiedTemplate:
1280 // FIXME: Visit nested-name-specifier.
1281 return Visit(MakeCursorTemplateRef(
1282 Name.getAsQualifiedTemplateName()->getDecl(),
1283 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001284
1285 case TemplateName::SubstTemplateTemplateParmPack:
1286 return Visit(MakeCursorTemplateRef(
1287 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1288 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001289 }
1290
1291 return false;
1292}
1293
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001294bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1295 switch (TAL.getArgument().getKind()) {
1296 case TemplateArgument::Null:
1297 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001298 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001299 return false;
1300
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301 case TemplateArgument::Type:
1302 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1303 return Visit(TSInfo->getTypeLoc());
1304 return false;
1305
1306 case TemplateArgument::Declaration:
1307 if (Expr *E = TAL.getSourceDeclExpression())
1308 return Visit(MakeCXCursor(E, StmtParent, TU));
1309 return false;
1310
1311 case TemplateArgument::Expression:
1312 if (Expr *E = TAL.getSourceExpression())
1313 return Visit(MakeCXCursor(E, StmtParent, TU));
1314 return false;
1315
1316 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001317 case TemplateArgument::TemplateExpansion:
1318 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001319 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001320 }
1321
1322 return false;
1323}
1324
Ted Kremeneka0536d82010-05-07 01:04:29 +00001325bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1326 return VisitDeclContext(D);
1327}
1328
Douglas Gregor01829d32010-08-31 14:41:23 +00001329bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1330 return Visit(TL.getUnqualifiedLoc());
1331}
1332
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001334 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335
1336 // Some builtin types (such as Objective-C's "id", "sel", and
1337 // "Class") have associated declarations. Create cursors for those.
1338 QualType VisitType;
1339 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001340 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001341 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001342 case BuiltinType::Char_U:
1343 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001344 case BuiltinType::Char16:
1345 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001346 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001347 case BuiltinType::UInt:
1348 case BuiltinType::ULong:
1349 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001350 case BuiltinType::UInt128:
1351 case BuiltinType::Char_S:
1352 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001353 case BuiltinType::WChar_U:
1354 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001355 case BuiltinType::Short:
1356 case BuiltinType::Int:
1357 case BuiltinType::Long:
1358 case BuiltinType::LongLong:
1359 case BuiltinType::Int128:
1360 case BuiltinType::Float:
1361 case BuiltinType::Double:
1362 case BuiltinType::LongDouble:
1363 case BuiltinType::NullPtr:
1364 case BuiltinType::Overload:
1365 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001366 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001367
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001368 case BuiltinType::ObjCId:
1369 VisitType = Context.getObjCIdType();
1370 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001371
1372 case BuiltinType::ObjCClass:
1373 VisitType = Context.getObjCClassType();
1374 break;
1375
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376 case BuiltinType::ObjCSel:
1377 VisitType = Context.getObjCSelType();
1378 break;
1379 }
1380
1381 if (!VisitType.isNull()) {
1382 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001383 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384 TU));
1385 }
1386
1387 return false;
1388}
1389
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001390bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1391 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1392}
1393
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1395 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1396}
1397
1398bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1399 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1400}
1401
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001402bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001403 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001404 // no context information with which we can match up the depth/index in the
1405 // type to the appropriate
1406 return false;
1407}
1408
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1410 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1411 return true;
1412
John McCallc12c5bb2010-05-15 11:32:37 +00001413 return false;
1414}
1415
1416bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1417 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1418 return true;
1419
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001420 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1421 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1422 TU)))
1423 return true;
1424 }
1425
1426 return false;
1427}
1428
1429bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001430 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001431}
1432
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001433bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1434 return Visit(TL.getInnerLoc());
1435}
1436
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001437bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1438 return Visit(TL.getPointeeLoc());
1439}
1440
1441bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1442 return Visit(TL.getPointeeLoc());
1443}
1444
1445bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1446 return Visit(TL.getPointeeLoc());
1447}
1448
1449bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001450 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001451}
1452
1453bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455}
1456
Douglas Gregor01829d32010-08-31 14:41:23 +00001457bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1458 bool SkipResultType) {
1459 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001460 return true;
1461
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001462 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001463 if (Decl *D = TL.getArg(I))
1464 if (Visit(MakeCXCursor(D, TU)))
1465 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001466
1467 return false;
1468}
1469
1470bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1471 if (Visit(TL.getElementLoc()))
1472 return true;
1473
1474 if (Expr *Size = TL.getSizeExpr())
1475 return Visit(MakeCXCursor(Size, StmtParent, TU));
1476
1477 return false;
1478}
1479
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001480bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1481 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001482 // Visit the template name.
1483 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1484 TL.getTemplateNameLoc()))
1485 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001486
1487 // Visit the template arguments.
1488 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1489 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1490 return true;
1491
1492 return false;
1493}
1494
Douglas Gregor2332c112010-01-21 20:48:56 +00001495bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1496 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1497}
1498
1499bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1500 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1501 return Visit(TSInfo->getTypeLoc());
1502
1503 return false;
1504}
1505
Douglas Gregor7536dd52010-12-20 02:24:11 +00001506bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1507 return Visit(TL.getPatternLoc());
1508}
1509
Ted Kremenek3064ef92010-08-27 21:34:58 +00001510bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001511 // Visit the nested-name-specifier, if present.
1512 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1513 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1514 return true;
1515
Ted Kremenek3064ef92010-08-27 21:34:58 +00001516 if (D->isDefinition()) {
1517 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1518 E = D->bases_end(); I != E; ++I) {
1519 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1520 return true;
1521 }
1522 }
1523
1524 return VisitTagDecl(D);
1525}
1526
Ted Kremenek09dfa372010-02-18 05:46:33 +00001527bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001528 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1529 i != e; ++i)
1530 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001531 return true;
1532
1533 return false;
1534}
1535
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001536//===----------------------------------------------------------------------===//
1537// Data-recursive visitor methods.
1538//===----------------------------------------------------------------------===//
1539
Ted Kremenek28a71942010-11-13 00:36:47 +00001540namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001541#define DEF_JOB(NAME, DATA, KIND)\
1542class NAME : public VisitorJob {\
1543public:\
1544 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1545 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001546 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001547};
1548
1549DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1550DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001551DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001552DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001553DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1554 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001555DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001556#undef DEF_JOB
1557
1558class DeclVisit : public VisitorJob {
1559public:
1560 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1561 VisitorJob(parent, VisitorJob::DeclVisitKind,
1562 d, isFirst ? (void*) 1 : (void*) 0) {}
1563 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001564 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001565 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001566 Decl *get() const { return static_cast<Decl*>(data[0]); }
1567 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001568};
Ted Kremenek035dc412010-11-13 00:36:50 +00001569class TypeLocVisit : public VisitorJob {
1570public:
1571 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1572 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1573 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1574
1575 static bool classof(const VisitorJob *VJ) {
1576 return VJ->getKind() == TypeLocVisitKind;
1577 }
1578
Ted Kremenek82f3c502010-11-15 22:23:26 +00001579 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001580 QualType T = QualType::getFromOpaquePtr(data[0]);
1581 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001582 }
1583};
1584
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001585class LabelRefVisit : public VisitorJob {
1586public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001587 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1588 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001589 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001590
1591 static bool classof(const VisitorJob *VJ) {
1592 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1593 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001594 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001595 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001596 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001597};
1598class NestedNameSpecifierVisit : public VisitorJob {
1599public:
1600 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1601 CXCursor parent)
1602 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001603 NS, R.getBegin().getPtrEncoding(),
1604 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001605 static bool classof(const VisitorJob *VJ) {
1606 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1607 }
1608 NestedNameSpecifier *get() const {
1609 return static_cast<NestedNameSpecifier*>(data[0]);
1610 }
1611 SourceRange getSourceRange() const {
1612 SourceLocation A =
1613 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1614 SourceLocation B =
1615 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1616 return SourceRange(A, B);
1617 }
1618};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001619
1620class NestedNameSpecifierLocVisit : public VisitorJob {
1621public:
1622 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1623 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1624 Qualifier.getNestedNameSpecifier(),
1625 Qualifier.getOpaqueData()) { }
1626
1627 static bool classof(const VisitorJob *VJ) {
1628 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1629 }
1630
1631 NestedNameSpecifierLoc get() const {
1632 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1633 data[1]);
1634 }
1635};
1636
Ted Kremenekf64d8032010-11-18 00:02:32 +00001637class DeclarationNameInfoVisit : public VisitorJob {
1638public:
1639 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1640 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1641 static bool classof(const VisitorJob *VJ) {
1642 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1643 }
1644 DeclarationNameInfo get() const {
1645 Stmt *S = static_cast<Stmt*>(data[0]);
1646 switch (S->getStmtClass()) {
1647 default:
1648 llvm_unreachable("Unhandled Stmt");
1649 case Stmt::CXXDependentScopeMemberExprClass:
1650 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1651 case Stmt::DependentScopeDeclRefExprClass:
1652 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1653 }
1654 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001655};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001656class MemberRefVisit : public VisitorJob {
1657public:
1658 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1659 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001660 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001661 static bool classof(const VisitorJob *VJ) {
1662 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1663 }
1664 FieldDecl *get() const {
1665 return static_cast<FieldDecl*>(data[0]);
1666 }
1667 SourceLocation getLoc() const {
1668 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1669 }
1670};
Ted Kremenek28a71942010-11-13 00:36:47 +00001671class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1672 VisitorWorkList &WL;
1673 CXCursor Parent;
1674public:
1675 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1676 : WL(wl), Parent(parent) {}
1677
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001678 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001679 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001680 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001681 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001682 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001683 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001684 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001685 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001686 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001687 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001688 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001689 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001690 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001691 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001692 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001693 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001694 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001695 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001696 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1697 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001698 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001699 void VisitIfStmt(IfStmt *If);
1700 void VisitInitListExpr(InitListExpr *IE);
1701 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001702 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001703 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001704 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1705 void VisitOverloadExpr(OverloadExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001706 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001707 void VisitStmt(Stmt *S);
1708 void VisitSwitchStmt(SwitchStmt *S);
1709 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001710 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001711 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001712 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001713 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001714 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001715
Ted Kremenek28a71942010-11-13 00:36:47 +00001716private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001717 void AddDeclarationNameInfo(Stmt *S);
1718 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001719 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001720 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001721 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001722 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001723 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001724 void AddTypeLoc(TypeSourceInfo *TI);
1725 void EnqueueChildren(Stmt *S);
1726};
1727} // end anonyous namespace
1728
Ted Kremenekf64d8032010-11-18 00:02:32 +00001729void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1730 // 'S' should always be non-null, since it comes from the
1731 // statement we are visiting.
1732 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1733}
1734void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1735 SourceRange R) {
1736 if (N)
1737 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1738}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001739
1740void
1741EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1742 if (Qualifier)
1743 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1744}
1745
Ted Kremenek28a71942010-11-13 00:36:47 +00001746void EnqueueVisitor::AddStmt(Stmt *S) {
1747 if (S)
1748 WL.push_back(StmtVisit(S, Parent));
1749}
Ted Kremenek035dc412010-11-13 00:36:50 +00001750void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001752 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001753}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001754void EnqueueVisitor::
1755 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1756 if (A)
1757 WL.push_back(ExplicitTemplateArgsVisit(
1758 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1759}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001760void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1761 if (D)
1762 WL.push_back(MemberRefVisit(D, L, Parent));
1763}
Ted Kremenek28a71942010-11-13 00:36:47 +00001764void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1765 if (TI)
1766 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1767 }
1768void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001769 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001770 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001771 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001772 }
1773 if (size == WL.size())
1774 return;
1775 // Now reverse the entries we just added. This will match the DFS
1776 // ordering performed by the worklist.
1777 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1778 std::reverse(I, E);
1779}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001780void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1781 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1782}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001783void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1784 AddDecl(B->getBlockDecl());
1785}
Ted Kremenek28a71942010-11-13 00:36:47 +00001786void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1787 EnqueueChildren(E);
1788 AddTypeLoc(E->getTypeSourceInfo());
1789}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001790void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1791 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1792 E = S->body_rend(); I != E; ++I) {
1793 AddStmt(*I);
1794 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001795}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001796void EnqueueVisitor::
1797VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1798 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1799 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001800 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1801 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001802 if (!E->isImplicitAccess())
1803 AddStmt(E->getBase());
1804}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001805void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1806 // Enqueue the initializer or constructor arguments.
1807 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1808 AddStmt(E->getConstructorArg(I-1));
1809 // Enqueue the array size, if any.
1810 AddStmt(E->getArraySize());
1811 // Enqueue the allocated type.
1812 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1813 // Enqueue the placement arguments.
1814 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1815 AddStmt(E->getPlacementArg(I-1));
1816}
Ted Kremenek28a71942010-11-13 00:36:47 +00001817void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001818 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1819 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001820 AddStmt(CE->getCallee());
1821 AddStmt(CE->getArg(0));
1822}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001823void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1824 // Visit the name of the type being destroyed.
1825 AddTypeLoc(E->getDestroyedTypeInfo());
1826 // Visit the scope type that looks disturbingly like the nested-name-specifier
1827 // but isn't.
1828 AddTypeLoc(E->getScopeTypeInfo());
1829 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001830 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1831 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001832 // Visit base expression.
1833 AddStmt(E->getBase());
1834}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001835void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1836 AddTypeLoc(E->getTypeSourceInfo());
1837}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001838void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1839 EnqueueChildren(E);
1840 AddTypeLoc(E->getTypeSourceInfo());
1841}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001842void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1843 EnqueueChildren(E);
1844 if (E->isTypeOperand())
1845 AddTypeLoc(E->getTypeOperandSourceInfo());
1846}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001847
1848void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1849 *E) {
1850 EnqueueChildren(E);
1851 AddTypeLoc(E->getTypeSourceInfo());
1852}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001853void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1854 EnqueueChildren(E);
1855 if (E->isTypeOperand())
1856 AddTypeLoc(E->getTypeOperandSourceInfo());
1857}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001858void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001859 if (DR->hasExplicitTemplateArgs()) {
1860 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1861 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001862 WL.push_back(DeclRefExprParts(DR, Parent));
1863}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001864void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1865 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1866 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001867 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001868}
Ted Kremenek035dc412010-11-13 00:36:50 +00001869void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1870 unsigned size = WL.size();
1871 bool isFirst = true;
1872 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1873 D != DEnd; ++D) {
1874 AddDecl(*D, isFirst);
1875 isFirst = false;
1876 }
1877 if (size == WL.size())
1878 return;
1879 // Now reverse the entries we just added. This will match the DFS
1880 // ordering performed by the worklist.
1881 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1882 std::reverse(I, E);
1883}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001884void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1885 AddStmt(E->getInit());
1886 typedef DesignatedInitExpr::Designator Designator;
1887 for (DesignatedInitExpr::reverse_designators_iterator
1888 D = E->designators_rbegin(), DEnd = E->designators_rend();
1889 D != DEnd; ++D) {
1890 if (D->isFieldDesignator()) {
1891 if (FieldDecl *Field = D->getField())
1892 AddMemberRef(Field, D->getFieldLoc());
1893 continue;
1894 }
1895 if (D->isArrayDesignator()) {
1896 AddStmt(E->getArrayIndex(*D));
1897 continue;
1898 }
1899 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1900 AddStmt(E->getArrayRangeEnd(*D));
1901 AddStmt(E->getArrayRangeStart(*D));
1902 }
1903}
Ted Kremenek28a71942010-11-13 00:36:47 +00001904void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1905 EnqueueChildren(E);
1906 AddTypeLoc(E->getTypeInfoAsWritten());
1907}
1908void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1909 AddStmt(FS->getBody());
1910 AddStmt(FS->getInc());
1911 AddStmt(FS->getCond());
1912 AddDecl(FS->getConditionVariable());
1913 AddStmt(FS->getInit());
1914}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001915void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1916 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1917}
Ted Kremenek28a71942010-11-13 00:36:47 +00001918void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1919 AddStmt(If->getElse());
1920 AddStmt(If->getThen());
1921 AddStmt(If->getCond());
1922 AddDecl(If->getConditionVariable());
1923}
1924void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1925 // We care about the syntactic form of the initializer list, only.
1926 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1927 IE = Syntactic;
1928 EnqueueChildren(IE);
1929}
1930void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001931 WL.push_back(MemberExprParts(M, Parent));
1932
1933 // If the base of the member access expression is an implicit 'this', don't
1934 // visit it.
1935 // FIXME: If we ever want to show these implicit accesses, this will be
1936 // unfortunate. However, clang_getCursor() relies on this behavior.
1937 if (CXXThisExpr *This
1938 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts()))
1939 if (This->isImplicit())
1940 return;
1941
Ted Kremenek28a71942010-11-13 00:36:47 +00001942 AddStmt(M->getBase());
1943}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001944void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1945 AddTypeLoc(E->getEncodedTypeSourceInfo());
1946}
Ted Kremenek28a71942010-11-13 00:36:47 +00001947void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1948 EnqueueChildren(M);
1949 AddTypeLoc(M->getClassReceiverTypeInfo());
1950}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001951void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1952 // Visit the components of the offsetof expression.
1953 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1954 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1955 const OffsetOfNode &Node = E->getComponent(I-1);
1956 switch (Node.getKind()) {
1957 case OffsetOfNode::Array:
1958 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
1959 break;
1960 case OffsetOfNode::Field:
1961 AddMemberRef(Node.getField(), Node.getRange().getEnd());
1962 break;
1963 case OffsetOfNode::Identifier:
1964 case OffsetOfNode::Base:
1965 continue;
1966 }
1967 }
1968 // Visit the type into which we're computing the offset.
1969 AddTypeLoc(E->getTypeSourceInfo());
1970}
Ted Kremenek28a71942010-11-13 00:36:47 +00001971void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001972 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00001973 WL.push_back(OverloadExprParts(E, Parent));
1974}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001975void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1976 EnqueueChildren(E);
1977 if (E->isArgumentType())
1978 AddTypeLoc(E->getArgumentTypeInfo());
1979}
Ted Kremenek28a71942010-11-13 00:36:47 +00001980void EnqueueVisitor::VisitStmt(Stmt *S) {
1981 EnqueueChildren(S);
1982}
1983void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1984 AddStmt(S->getBody());
1985 AddStmt(S->getCond());
1986 AddDecl(S->getConditionVariable());
1987}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00001988
Ted Kremenek28a71942010-11-13 00:36:47 +00001989void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1990 AddStmt(W->getBody());
1991 AddStmt(W->getCond());
1992 AddDecl(W->getConditionVariable());
1993}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001994void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1995 AddTypeLoc(E->getQueriedTypeSourceInfo());
1996}
Francois Pichet6ad6f282010-12-07 00:08:36 +00001997
1998void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00001999 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002000 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002001}
2002
Ted Kremenek28a71942010-11-13 00:36:47 +00002003void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2004 VisitOverloadExpr(U);
2005 if (!U->isImplicitAccess())
2006 AddStmt(U->getBase());
2007}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002008void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2009 AddStmt(E->getSubExpr());
2010 AddTypeLoc(E->getWrittenTypeInfo());
2011}
Douglas Gregor94d96292011-01-19 20:34:17 +00002012void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2013 WL.push_back(SizeOfPackExprParts(E, Parent));
2014}
Ted Kremenek60458782010-11-12 21:34:16 +00002015
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002016void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002017 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002018}
2019
2020bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2021 if (RegionOfInterest.isValid()) {
2022 SourceRange Range = getRawCursorExtent(C);
2023 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2024 return false;
2025 }
2026 return true;
2027}
2028
2029bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2030 while (!WL.empty()) {
2031 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002032 VisitorJob LI = WL.back();
2033 WL.pop_back();
2034
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002035 // Set the Parent field, then back to its old value once we're done.
2036 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2037
2038 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002039 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002040 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002041 if (!D)
2042 continue;
2043
2044 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002045 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002046 return true;
2047
2048 continue;
2049 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002050 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2051 const ExplicitTemplateArgumentList *ArgList =
2052 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2053 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2054 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2055 Arg != ArgEnd; ++Arg) {
2056 if (VisitTemplateArgumentLoc(*Arg))
2057 return true;
2058 }
2059 continue;
2060 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002061 case VisitorJob::TypeLocVisitKind: {
2062 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002063 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002064 return true;
2065 continue;
2066 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002067 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002068 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002069 if (LabelStmt *stmt = LS->getStmt()) {
2070 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2071 TU))) {
2072 return true;
2073 }
2074 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002075 continue;
2076 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002077
Ted Kremenekf64d8032010-11-18 00:02:32 +00002078 case VisitorJob::NestedNameSpecifierVisitKind: {
2079 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2080 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2081 return true;
2082 continue;
2083 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002084
2085 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2086 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2087 if (VisitNestedNameSpecifierLoc(V->get()))
2088 return true;
2089 continue;
2090 }
2091
Ted Kremenekf64d8032010-11-18 00:02:32 +00002092 case VisitorJob::DeclarationNameInfoVisitKind: {
2093 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2094 ->get()))
2095 return true;
2096 continue;
2097 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002098 case VisitorJob::MemberRefVisitKind: {
2099 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2100 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2101 return true;
2102 continue;
2103 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002104 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002105 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002106 if (!S)
2107 continue;
2108
Ted Kremenekf1107452010-11-12 18:26:56 +00002109 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002110 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002111 if (!IsInRegionOfInterest(Cursor))
2112 continue;
2113 switch (Visitor(Cursor, Parent, ClientData)) {
2114 case CXChildVisit_Break: return true;
2115 case CXChildVisit_Continue: break;
2116 case CXChildVisit_Recurse:
2117 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002118 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002119 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002120 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002121 }
2122 case VisitorJob::MemberExprPartsKind: {
2123 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002124 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002125
2126 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002127 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2128 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002129 return true;
2130
2131 // Visit the declaration name.
2132 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2133 return true;
2134
2135 // Visit the explicitly-specified template arguments, if any.
2136 if (M->hasExplicitTemplateArgs()) {
2137 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2138 *ArgEnd = Arg + M->getNumTemplateArgs();
2139 Arg != ArgEnd; ++Arg) {
2140 if (VisitTemplateArgumentLoc(*Arg))
2141 return true;
2142 }
2143 }
2144 continue;
2145 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002146 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002147 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002148 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002149 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2150 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002151 return true;
2152 // Visit declaration name.
2153 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2154 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002155 continue;
2156 }
Ted Kremenek60458782010-11-12 21:34:16 +00002157 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002158 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002159 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002160 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2161 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002162 return true;
2163 // Visit the declaration name.
2164 if (VisitDeclarationNameInfo(O->getNameInfo()))
2165 return true;
2166 // Visit the overloaded declaration reference.
2167 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2168 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002169 continue;
2170 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002171 case VisitorJob::SizeOfPackExprPartsKind: {
2172 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2173 NamedDecl *Pack = E->getPack();
2174 if (isa<TemplateTypeParmDecl>(Pack)) {
2175 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2176 E->getPackLoc(), TU)))
2177 return true;
2178
2179 continue;
2180 }
2181
2182 if (isa<TemplateTemplateParmDecl>(Pack)) {
2183 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2184 E->getPackLoc(), TU)))
2185 return true;
2186
2187 continue;
2188 }
2189
2190 // Non-type template parameter packs and function parameter packs are
2191 // treated like DeclRefExpr cursors.
2192 continue;
2193 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002194 }
2195 }
2196 return false;
2197}
2198
Ted Kremenekcdba6592010-11-18 00:42:18 +00002199bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002200 VisitorWorkList *WL = 0;
2201 if (!WorkListFreeList.empty()) {
2202 WL = WorkListFreeList.back();
2203 WL->clear();
2204 WorkListFreeList.pop_back();
2205 }
2206 else {
2207 WL = new VisitorWorkList();
2208 WorkListCache.push_back(WL);
2209 }
2210 EnqueueWorkList(*WL, S);
2211 bool result = RunVisitorWorkList(*WL);
2212 WorkListFreeList.push_back(WL);
2213 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002214}
2215
2216//===----------------------------------------------------------------------===//
2217// Misc. API hooks.
2218//===----------------------------------------------------------------------===//
2219
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002220static llvm::sys::Mutex EnableMultithreadingMutex;
2221static bool EnabledMultithreading;
2222
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002223extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002224CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2225 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002226 // Disable pretty stack trace functionality, which will otherwise be a very
2227 // poor citizen of the world and set up all sorts of signal handlers.
2228 llvm::DisablePrettyStackTrace = true;
2229
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002230 // We use crash recovery to make some of our APIs more reliable, implicitly
2231 // enable it.
2232 llvm::CrashRecoveryContext::Enable();
2233
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002234 // Enable support for multithreading in LLVM.
2235 {
2236 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2237 if (!EnabledMultithreading) {
2238 llvm::llvm_start_multithreaded();
2239 EnabledMultithreading = true;
2240 }
2241 }
2242
Douglas Gregora030b7c2010-01-22 20:35:53 +00002243 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002244 if (excludeDeclarationsFromPCH)
2245 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002246 if (displayDiagnostics)
2247 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002248 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002249}
2250
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002251void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002252 if (CIdx)
2253 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002254}
2255
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002256CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002257 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002258 if (!CIdx)
2259 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002260
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002261 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002262 FileSystemOptions FileSystemOpts;
2263 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002264
Douglas Gregor28019772010-04-05 23:52:57 +00002265 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002266 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002267 CXXIdx->getOnlyLocalDecls(),
2268 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002269 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002270}
2271
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002272unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002273 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002274 CXTranslationUnit_CacheCompletionResults |
2275 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002276}
2277
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002278CXTranslationUnit
2279clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2280 const char *source_filename,
2281 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002282 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002283 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002284 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002285 return clang_parseTranslationUnit(CIdx, source_filename,
2286 command_line_args, num_command_line_args,
2287 unsaved_files, num_unsaved_files,
2288 CXTranslationUnit_DetailedPreprocessingRecord);
2289}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002290
2291struct ParseTranslationUnitInfo {
2292 CXIndex CIdx;
2293 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002294 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002295 int num_command_line_args;
2296 struct CXUnsavedFile *unsaved_files;
2297 unsigned num_unsaved_files;
2298 unsigned options;
2299 CXTranslationUnit result;
2300};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002301static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002302 ParseTranslationUnitInfo *PTUI =
2303 static_cast<ParseTranslationUnitInfo*>(UserData);
2304 CXIndex CIdx = PTUI->CIdx;
2305 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002306 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002307 int num_command_line_args = PTUI->num_command_line_args;
2308 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2309 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2310 unsigned options = PTUI->options;
2311 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002312
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002313 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002314 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002315
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002316 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2317
Douglas Gregor44c181a2010-07-23 00:33:23 +00002318 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002319 bool CompleteTranslationUnit
2320 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002321 bool CacheCodeCompetionResults
2322 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002323 bool CXXPrecompilePreamble
2324 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2325 bool CXXChainedPCH
2326 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002327
Douglas Gregor5352ac02010-01-28 00:27:43 +00002328 // Configure the diagnostics.
2329 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002330 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002331 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2332 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002333
Douglas Gregor4db64a42010-01-23 00:14:00 +00002334 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2335 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002336 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002337 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002338 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002339 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2340 Buffer));
2341 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002342
Douglas Gregorb10daed2010-10-11 16:52:23 +00002343 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002344
Ted Kremenek139ba862009-10-22 00:03:57 +00002345 // The 'source_filename' argument is optional. If the caller does not
2346 // specify it then it is assumed that the source file is specified
2347 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002348 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002349 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002350
2351 // Since the Clang C library is primarily used by batch tools dealing with
2352 // (often very broken) source code, where spell-checking can have a
2353 // significant negative impact on performance (particularly when
2354 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002355 // Only do this if we haven't found a spell-checking-related argument.
2356 bool FoundSpellCheckingArgument = false;
2357 for (int I = 0; I != num_command_line_args; ++I) {
2358 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2359 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2360 FoundSpellCheckingArgument = true;
2361 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002362 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002363 }
2364 if (!FoundSpellCheckingArgument)
2365 Args.push_back("-fno-spell-checking");
2366
2367 Args.insert(Args.end(), command_line_args,
2368 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002369
Douglas Gregor44c181a2010-07-23 00:33:23 +00002370 // Do we need the detailed preprocessing record?
2371 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002372 Args.push_back("-Xclang");
2373 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002374 }
2375
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002376 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002377 llvm::OwningPtr<ASTUnit> Unit(
2378 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2379 Diags,
2380 CXXIdx->getClangResourcesPath(),
2381 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002382 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002383 RemappedFiles.data(),
2384 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002385 PrecompilePreamble,
2386 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002387 CacheCodeCompetionResults,
2388 CXXPrecompilePreamble,
2389 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002390
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002391 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002392 // Make sure to check that 'Unit' is non-NULL.
2393 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2394 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2395 DEnd = Unit->stored_diag_end();
2396 D != DEnd; ++D) {
2397 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2398 CXString Msg = clang_formatDiagnostic(&Diag,
2399 clang_defaultDiagnosticDisplayOptions());
2400 fprintf(stderr, "%s\n", clang_getCString(Msg));
2401 clang_disposeString(Msg);
2402 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002403#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002404 // On Windows, force a flush, since there may be multiple copies of
2405 // stderr and stdout in the file system, all with different buffers
2406 // but writing to the same device.
2407 fflush(stderr);
2408#endif
2409 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002410 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002411
Ted Kremeneka60ed472010-11-16 08:15:36 +00002412 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002413}
2414CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2415 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002416 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002417 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002418 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002419 unsigned num_unsaved_files,
2420 unsigned options) {
2421 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002422 num_command_line_args, unsaved_files,
2423 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002424 llvm::CrashRecoveryContext CRC;
2425
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002426 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002427 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2428 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2429 fprintf(stderr, " 'command_line_args' : [");
2430 for (int i = 0; i != num_command_line_args; ++i) {
2431 if (i)
2432 fprintf(stderr, ", ");
2433 fprintf(stderr, "'%s'", command_line_args[i]);
2434 }
2435 fprintf(stderr, "],\n");
2436 fprintf(stderr, " 'unsaved_files' : [");
2437 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2438 if (i)
2439 fprintf(stderr, ", ");
2440 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2441 unsaved_files[i].Length);
2442 }
2443 fprintf(stderr, "],\n");
2444 fprintf(stderr, " 'options' : %d,\n", options);
2445 fprintf(stderr, "}\n");
2446
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002447 return 0;
2448 }
2449
2450 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002451}
2452
Douglas Gregor19998442010-08-13 15:35:05 +00002453unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2454 return CXSaveTranslationUnit_None;
2455}
2456
2457int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2458 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002459 if (!TU)
2460 return 1;
2461
Ted Kremeneka60ed472010-11-16 08:15:36 +00002462 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002463}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002464
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002465void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002466 if (CTUnit) {
2467 // If the translation unit has been marked as unsafe to free, just discard
2468 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002469 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002470 return;
2471
Ted Kremeneka60ed472010-11-16 08:15:36 +00002472 delete static_cast<ASTUnit *>(CTUnit->TUData);
2473 disposeCXStringPool(CTUnit->StringPool);
2474 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002475 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002476}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002477
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002478unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2479 return CXReparse_None;
2480}
2481
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002482struct ReparseTranslationUnitInfo {
2483 CXTranslationUnit TU;
2484 unsigned num_unsaved_files;
2485 struct CXUnsavedFile *unsaved_files;
2486 unsigned options;
2487 int result;
2488};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002489
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002490static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002491 ReparseTranslationUnitInfo *RTUI =
2492 static_cast<ReparseTranslationUnitInfo*>(UserData);
2493 CXTranslationUnit TU = RTUI->TU;
2494 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2495 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2496 unsigned options = RTUI->options;
2497 (void) options;
2498 RTUI->result = 1;
2499
Douglas Gregorabc563f2010-07-19 21:46:24 +00002500 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002501 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002502
Ted Kremeneka60ed472010-11-16 08:15:36 +00002503 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002504 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002505
2506 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2507 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2508 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2509 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002510 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002511 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2512 Buffer));
2513 }
2514
Douglas Gregor593b0c12010-09-23 18:47:53 +00002515 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2516 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002517}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002518
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002519int clang_reparseTranslationUnit(CXTranslationUnit TU,
2520 unsigned num_unsaved_files,
2521 struct CXUnsavedFile *unsaved_files,
2522 unsigned options) {
2523 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2524 options, 0 };
2525 llvm::CrashRecoveryContext CRC;
2526
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002527 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002528 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002529 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002530 return 1;
2531 }
2532
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002533
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002534 return RTUI.result;
2535}
2536
Douglas Gregordf95a132010-08-09 20:45:32 +00002537
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002538CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002539 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002540 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002541
Ted Kremeneka60ed472010-11-16 08:15:36 +00002542 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002543 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002544}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002545
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002546CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002547 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002548 return Result;
2549}
2550
Ted Kremenekfb480492010-01-13 21:46:36 +00002551} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002552
Ted Kremenekfb480492010-01-13 21:46:36 +00002553//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002554// CXSourceLocation and CXSourceRange Operations.
2555//===----------------------------------------------------------------------===//
2556
Douglas Gregorb9790342010-01-22 21:44:22 +00002557extern "C" {
2558CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002559 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002560 return Result;
2561}
2562
2563unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002564 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2565 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2566 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002567}
2568
2569CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2570 CXFile file,
2571 unsigned line,
2572 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002573 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002574 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002575
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002576 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002577 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002578 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002579 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002580 = CXXUnit->getSourceManager().getLocation(File, line, column);
2581 if (SLoc.isInvalid()) {
2582 if (Logging)
2583 llvm::errs() << "clang_getLocation(\"" << File->getName()
2584 << "\", " << line << ", " << column << ") = invalid\n";
2585 return clang_getNullLocation();
2586 }
2587
2588 if (Logging)
2589 llvm::errs() << "clang_getLocation(\"" << File->getName()
2590 << "\", " << line << ", " << column << ") = "
2591 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002592
2593 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2594}
2595
2596CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2597 CXFile file,
2598 unsigned offset) {
2599 if (!tu || !file)
2600 return clang_getNullLocation();
2601
Ted Kremeneka60ed472010-11-16 08:15:36 +00002602 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002603 SourceLocation Start
2604 = CXXUnit->getSourceManager().getLocation(
2605 static_cast<const FileEntry *>(file),
2606 1, 1);
2607 if (Start.isInvalid()) return clang_getNullLocation();
2608
2609 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2610
2611 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002612
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002613 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002614}
2615
Douglas Gregor5352ac02010-01-28 00:27:43 +00002616CXSourceRange clang_getNullRange() {
2617 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2618 return Result;
2619}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002620
Douglas Gregor5352ac02010-01-28 00:27:43 +00002621CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2622 if (begin.ptr_data[0] != end.ptr_data[0] ||
2623 begin.ptr_data[1] != end.ptr_data[1])
2624 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002625
2626 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002627 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002628 return Result;
2629}
2630
Douglas Gregor46766dc2010-01-26 19:19:08 +00002631void clang_getInstantiationLocation(CXSourceLocation location,
2632 CXFile *file,
2633 unsigned *line,
2634 unsigned *column,
2635 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002636 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2637
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002638 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002639 if (file)
2640 *file = 0;
2641 if (line)
2642 *line = 0;
2643 if (column)
2644 *column = 0;
2645 if (offset)
2646 *offset = 0;
2647 return;
2648 }
2649
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002650 const SourceManager &SM =
2651 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002652 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002653
2654 if (file)
2655 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2656 if (line)
2657 *line = SM.getInstantiationLineNumber(InstLoc);
2658 if (column)
2659 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002660 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002661 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002662}
2663
Douglas Gregora9b06d42010-11-09 06:24:54 +00002664void clang_getSpellingLocation(CXSourceLocation location,
2665 CXFile *file,
2666 unsigned *line,
2667 unsigned *column,
2668 unsigned *offset) {
2669 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2670
2671 if (!location.ptr_data[0] || Loc.isInvalid()) {
2672 if (file)
2673 *file = 0;
2674 if (line)
2675 *line = 0;
2676 if (column)
2677 *column = 0;
2678 if (offset)
2679 *offset = 0;
2680 return;
2681 }
2682
2683 const SourceManager &SM =
2684 *static_cast<const SourceManager*>(location.ptr_data[0]);
2685 SourceLocation SpellLoc = Loc;
2686 if (SpellLoc.isMacroID()) {
2687 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2688 if (SimpleSpellingLoc.isFileID() &&
2689 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2690 SpellLoc = SimpleSpellingLoc;
2691 else
2692 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2693 }
2694
2695 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2696 FileID FID = LocInfo.first;
2697 unsigned FileOffset = LocInfo.second;
2698
2699 if (file)
2700 *file = (void *)SM.getFileEntryForID(FID);
2701 if (line)
2702 *line = SM.getLineNumber(FID, FileOffset);
2703 if (column)
2704 *column = SM.getColumnNumber(FID, FileOffset);
2705 if (offset)
2706 *offset = FileOffset;
2707}
2708
Douglas Gregor1db19de2010-01-19 21:36:55 +00002709CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002710 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002711 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002712 return Result;
2713}
2714
2715CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002716 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002717 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002718 return Result;
2719}
2720
Douglas Gregorb9790342010-01-22 21:44:22 +00002721} // end: extern "C"
2722
Douglas Gregor1db19de2010-01-19 21:36:55 +00002723//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002724// CXFile Operations.
2725//===----------------------------------------------------------------------===//
2726
2727extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002728CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002729 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002730 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002731
Steve Naroff88145032009-10-27 14:35:18 +00002732 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002733 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002734}
2735
2736time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002737 if (!SFile)
2738 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002739
Steve Naroff88145032009-10-27 14:35:18 +00002740 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2741 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002742}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002743
Douglas Gregorb9790342010-01-22 21:44:22 +00002744CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2745 if (!tu)
2746 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002747
Ted Kremeneka60ed472010-11-16 08:15:36 +00002748 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002749
Douglas Gregorb9790342010-01-22 21:44:22 +00002750 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002751 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002752}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002753
Ted Kremenekfb480492010-01-13 21:46:36 +00002754} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002755
Ted Kremenekfb480492010-01-13 21:46:36 +00002756//===----------------------------------------------------------------------===//
2757// CXCursor Operations.
2758//===----------------------------------------------------------------------===//
2759
Ted Kremenekfb480492010-01-13 21:46:36 +00002760static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002761 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2762 return getDeclFromExpr(CE->getSubExpr());
2763
Ted Kremenekfb480492010-01-13 21:46:36 +00002764 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2765 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002766 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2767 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002768 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2769 return ME->getMemberDecl();
2770 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2771 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002772 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002773 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002774
Ted Kremenekfb480492010-01-13 21:46:36 +00002775 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2776 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002777 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2778 if (!CE->isElidable())
2779 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002780 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2781 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002782
Douglas Gregordb1314e2010-10-01 21:11:22 +00002783 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2784 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002785 if (SubstNonTypeTemplateParmPackExpr *NTTP
2786 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2787 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002788 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2789 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2790 isa<ParmVarDecl>(SizeOfPack->getPack()))
2791 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002792
Ted Kremenekfb480492010-01-13 21:46:36 +00002793 return 0;
2794}
2795
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002796static SourceLocation getLocationFromExpr(Expr *E) {
2797 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2798 return /*FIXME:*/Msg->getLeftLoc();
2799 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2800 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002801 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2802 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002803 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2804 return Member->getMemberLoc();
2805 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2806 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002807 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2808 return SizeOfPack->getPackLoc();
2809
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002810 return E->getLocStart();
2811}
2812
Ted Kremenekfb480492010-01-13 21:46:36 +00002813extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002814
2815unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002816 CXCursorVisitor visitor,
2817 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002818 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2819 getCursorASTUnit(parent)->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002820 return CursorVis.VisitChildren(parent);
2821}
2822
David Chisnall3387c652010-11-03 14:12:26 +00002823#ifndef __has_feature
2824#define __has_feature(x) 0
2825#endif
2826#if __has_feature(blocks)
2827typedef enum CXChildVisitResult
2828 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2829
2830static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2831 CXClientData client_data) {
2832 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2833 return block(cursor, parent);
2834}
2835#else
2836// If we are compiled with a compiler that doesn't have native blocks support,
2837// define and call the block manually, so the
2838typedef struct _CXChildVisitResult
2839{
2840 void *isa;
2841 int flags;
2842 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002843 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2844 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002845} *CXCursorVisitorBlock;
2846
2847static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2848 CXClientData client_data) {
2849 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2850 return block->invoke(block, cursor, parent);
2851}
2852#endif
2853
2854
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002855unsigned clang_visitChildrenWithBlock(CXCursor parent,
2856 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002857 return clang_visitChildren(parent, visitWithBlock, block);
2858}
2859
Douglas Gregor78205d42010-01-20 21:45:58 +00002860static CXString getDeclSpelling(Decl *D) {
2861 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002862 if (!ND) {
2863 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2864 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2865 return createCXString(Property->getIdentifier()->getName());
2866
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002867 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002868 }
2869
Douglas Gregor78205d42010-01-20 21:45:58 +00002870 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002871 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002872
Douglas Gregor78205d42010-01-20 21:45:58 +00002873 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2874 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2875 // and returns different names. NamedDecl returns the class name and
2876 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002877 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002878
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002879 if (isa<UsingDirectiveDecl>(D))
2880 return createCXString("");
2881
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002882 llvm::SmallString<1024> S;
2883 llvm::raw_svector_ostream os(S);
2884 ND->printName(os);
2885
2886 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002887}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002889CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002890 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002891 return clang_getTranslationUnitSpelling(
2892 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002893
Steve Narofff334b4e2009-09-02 18:26:48 +00002894 if (clang_isReference(C.kind)) {
2895 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002896 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002897 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002898 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002899 }
2900 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002901 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002902 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002903 }
2904 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002905 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002906 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002907 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002908 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002909 case CXCursor_CXXBaseSpecifier: {
2910 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2911 return createCXString(B->getType().getAsString());
2912 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002913 case CXCursor_TypeRef: {
2914 TypeDecl *Type = getCursorTypeRef(C).first;
2915 assert(Type && "Missing type decl");
2916
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002917 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2918 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002919 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002920 case CXCursor_TemplateRef: {
2921 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002922 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002923
2924 return createCXString(Template->getNameAsString());
2925 }
Douglas Gregor69319002010-08-31 23:48:11 +00002926
2927 case CXCursor_NamespaceRef: {
2928 NamedDecl *NS = getCursorNamespaceRef(C).first;
2929 assert(NS && "Missing namespace decl");
2930
2931 return createCXString(NS->getNameAsString());
2932 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002933
Douglas Gregora67e03f2010-09-09 21:42:20 +00002934 case CXCursor_MemberRef: {
2935 FieldDecl *Field = getCursorMemberRef(C).first;
2936 assert(Field && "Missing member decl");
2937
2938 return createCXString(Field->getNameAsString());
2939 }
2940
Douglas Gregor36897b02010-09-10 00:22:18 +00002941 case CXCursor_LabelRef: {
2942 LabelStmt *Label = getCursorLabelRef(C).first;
2943 assert(Label && "Missing label");
2944
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002945 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002946 }
2947
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002948 case CXCursor_OverloadedDeclRef: {
2949 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2950 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2951 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2952 return createCXString(ND->getNameAsString());
2953 return createCXString("");
2954 }
2955 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2956 return createCXString(E->getName().getAsString());
2957 OverloadedTemplateStorage *Ovl
2958 = Storage.get<OverloadedTemplateStorage*>();
2959 if (Ovl->size() == 0)
2960 return createCXString("");
2961 return createCXString((*Ovl->begin())->getNameAsString());
2962 }
2963
Daniel Dunbaracca7252009-11-30 20:42:49 +00002964 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002965 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002966 }
2967 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002968
2969 if (clang_isExpression(C.kind)) {
2970 Decl *D = getDeclFromExpr(getCursorExpr(C));
2971 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002972 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002973 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002974 }
2975
Douglas Gregor36897b02010-09-10 00:22:18 +00002976 if (clang_isStatement(C.kind)) {
2977 Stmt *S = getCursorStmt(C);
2978 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002979 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00002980
2981 return createCXString("");
2982 }
2983
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002984 if (C.kind == CXCursor_MacroInstantiation)
2985 return createCXString(getCursorMacroInstantiation(C)->getName()
2986 ->getNameStart());
2987
Douglas Gregor572feb22010-03-18 18:04:21 +00002988 if (C.kind == CXCursor_MacroDefinition)
2989 return createCXString(getCursorMacroDefinition(C)->getName()
2990 ->getNameStart());
2991
Douglas Gregorecdcb882010-10-20 22:00:55 +00002992 if (C.kind == CXCursor_InclusionDirective)
2993 return createCXString(getCursorInclusionDirective(C)->getFileName());
2994
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002995 if (clang_isDeclaration(C.kind))
2996 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002997
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002998 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002999}
3000
Douglas Gregor358559d2010-10-02 22:49:11 +00003001CXString clang_getCursorDisplayName(CXCursor C) {
3002 if (!clang_isDeclaration(C.kind))
3003 return clang_getCursorSpelling(C);
3004
3005 Decl *D = getCursorDecl(C);
3006 if (!D)
3007 return createCXString("");
3008
3009 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3010 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3011 D = FunTmpl->getTemplatedDecl();
3012
3013 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3014 llvm::SmallString<64> Str;
3015 llvm::raw_svector_ostream OS(Str);
3016 OS << Function->getNameAsString();
3017 if (Function->getPrimaryTemplate())
3018 OS << "<>";
3019 OS << "(";
3020 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3021 if (I)
3022 OS << ", ";
3023 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3024 }
3025
3026 if (Function->isVariadic()) {
3027 if (Function->getNumParams())
3028 OS << ", ";
3029 OS << "...";
3030 }
3031 OS << ")";
3032 return createCXString(OS.str());
3033 }
3034
3035 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3036 llvm::SmallString<64> Str;
3037 llvm::raw_svector_ostream OS(Str);
3038 OS << ClassTemplate->getNameAsString();
3039 OS << "<";
3040 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3041 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3042 if (I)
3043 OS << ", ";
3044
3045 NamedDecl *Param = Params->getParam(I);
3046 if (Param->getIdentifier()) {
3047 OS << Param->getIdentifier()->getName();
3048 continue;
3049 }
3050
3051 // There is no parameter name, which makes this tricky. Try to come up
3052 // with something useful that isn't too long.
3053 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3054 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3055 else if (NonTypeTemplateParmDecl *NTTP
3056 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3057 OS << NTTP->getType().getAsString(Policy);
3058 else
3059 OS << "template<...> class";
3060 }
3061
3062 OS << ">";
3063 return createCXString(OS.str());
3064 }
3065
3066 if (ClassTemplateSpecializationDecl *ClassSpec
3067 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3068 // If the type was explicitly written, use that.
3069 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3070 return createCXString(TSInfo->getType().getAsString(Policy));
3071
3072 llvm::SmallString<64> Str;
3073 llvm::raw_svector_ostream OS(Str);
3074 OS << ClassSpec->getNameAsString();
3075 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003076 ClassSpec->getTemplateArgs().data(),
3077 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003078 Policy);
3079 return createCXString(OS.str());
3080 }
3081
3082 return clang_getCursorSpelling(C);
3083}
3084
Ted Kremeneke68fff62010-02-17 00:41:32 +00003085CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003086 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003087 case CXCursor_FunctionDecl:
3088 return createCXString("FunctionDecl");
3089 case CXCursor_TypedefDecl:
3090 return createCXString("TypedefDecl");
3091 case CXCursor_EnumDecl:
3092 return createCXString("EnumDecl");
3093 case CXCursor_EnumConstantDecl:
3094 return createCXString("EnumConstantDecl");
3095 case CXCursor_StructDecl:
3096 return createCXString("StructDecl");
3097 case CXCursor_UnionDecl:
3098 return createCXString("UnionDecl");
3099 case CXCursor_ClassDecl:
3100 return createCXString("ClassDecl");
3101 case CXCursor_FieldDecl:
3102 return createCXString("FieldDecl");
3103 case CXCursor_VarDecl:
3104 return createCXString("VarDecl");
3105 case CXCursor_ParmDecl:
3106 return createCXString("ParmDecl");
3107 case CXCursor_ObjCInterfaceDecl:
3108 return createCXString("ObjCInterfaceDecl");
3109 case CXCursor_ObjCCategoryDecl:
3110 return createCXString("ObjCCategoryDecl");
3111 case CXCursor_ObjCProtocolDecl:
3112 return createCXString("ObjCProtocolDecl");
3113 case CXCursor_ObjCPropertyDecl:
3114 return createCXString("ObjCPropertyDecl");
3115 case CXCursor_ObjCIvarDecl:
3116 return createCXString("ObjCIvarDecl");
3117 case CXCursor_ObjCInstanceMethodDecl:
3118 return createCXString("ObjCInstanceMethodDecl");
3119 case CXCursor_ObjCClassMethodDecl:
3120 return createCXString("ObjCClassMethodDecl");
3121 case CXCursor_ObjCImplementationDecl:
3122 return createCXString("ObjCImplementationDecl");
3123 case CXCursor_ObjCCategoryImplDecl:
3124 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003125 case CXCursor_CXXMethod:
3126 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003127 case CXCursor_UnexposedDecl:
3128 return createCXString("UnexposedDecl");
3129 case CXCursor_ObjCSuperClassRef:
3130 return createCXString("ObjCSuperClassRef");
3131 case CXCursor_ObjCProtocolRef:
3132 return createCXString("ObjCProtocolRef");
3133 case CXCursor_ObjCClassRef:
3134 return createCXString("ObjCClassRef");
3135 case CXCursor_TypeRef:
3136 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003137 case CXCursor_TemplateRef:
3138 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003139 case CXCursor_NamespaceRef:
3140 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003141 case CXCursor_MemberRef:
3142 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003143 case CXCursor_LabelRef:
3144 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003145 case CXCursor_OverloadedDeclRef:
3146 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003147 case CXCursor_UnexposedExpr:
3148 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003149 case CXCursor_BlockExpr:
3150 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003151 case CXCursor_DeclRefExpr:
3152 return createCXString("DeclRefExpr");
3153 case CXCursor_MemberRefExpr:
3154 return createCXString("MemberRefExpr");
3155 case CXCursor_CallExpr:
3156 return createCXString("CallExpr");
3157 case CXCursor_ObjCMessageExpr:
3158 return createCXString("ObjCMessageExpr");
3159 case CXCursor_UnexposedStmt:
3160 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003161 case CXCursor_LabelStmt:
3162 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003163 case CXCursor_InvalidFile:
3164 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003165 case CXCursor_InvalidCode:
3166 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003167 case CXCursor_NoDeclFound:
3168 return createCXString("NoDeclFound");
3169 case CXCursor_NotImplemented:
3170 return createCXString("NotImplemented");
3171 case CXCursor_TranslationUnit:
3172 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003173 case CXCursor_UnexposedAttr:
3174 return createCXString("UnexposedAttr");
3175 case CXCursor_IBActionAttr:
3176 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003177 case CXCursor_IBOutletAttr:
3178 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003179 case CXCursor_IBOutletCollectionAttr:
3180 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003181 case CXCursor_PreprocessingDirective:
3182 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003183 case CXCursor_MacroDefinition:
3184 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003185 case CXCursor_MacroInstantiation:
3186 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003187 case CXCursor_InclusionDirective:
3188 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003189 case CXCursor_Namespace:
3190 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003191 case CXCursor_LinkageSpec:
3192 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003193 case CXCursor_CXXBaseSpecifier:
3194 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003195 case CXCursor_Constructor:
3196 return createCXString("CXXConstructor");
3197 case CXCursor_Destructor:
3198 return createCXString("CXXDestructor");
3199 case CXCursor_ConversionFunction:
3200 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003201 case CXCursor_TemplateTypeParameter:
3202 return createCXString("TemplateTypeParameter");
3203 case CXCursor_NonTypeTemplateParameter:
3204 return createCXString("NonTypeTemplateParameter");
3205 case CXCursor_TemplateTemplateParameter:
3206 return createCXString("TemplateTemplateParameter");
3207 case CXCursor_FunctionTemplate:
3208 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003209 case CXCursor_ClassTemplate:
3210 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003211 case CXCursor_ClassTemplatePartialSpecialization:
3212 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003213 case CXCursor_NamespaceAlias:
3214 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003215 case CXCursor_UsingDirective:
3216 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003217 case CXCursor_UsingDeclaration:
3218 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003219 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003220
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003221 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003222 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003223}
Steve Naroff89922f82009-08-31 00:59:03 +00003224
Ted Kremeneke68fff62010-02-17 00:41:32 +00003225enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3226 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003227 CXClientData client_data) {
3228 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003229
3230 // If our current best cursor is the construction of a temporary object,
3231 // don't replace that cursor with a type reference, because we want
3232 // clang_getCursor() to point at the constructor.
3233 if (clang_isExpression(BestCursor->kind) &&
3234 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3235 cursor.kind == CXCursor_TypeRef)
3236 return CXChildVisit_Recurse;
3237
Douglas Gregor85fe1562010-12-10 07:23:11 +00003238 // Don't override a preprocessing cursor with another preprocessing
3239 // cursor; we want the outermost preprocessing cursor.
3240 if (clang_isPreprocessing(cursor.kind) &&
3241 clang_isPreprocessing(BestCursor->kind))
3242 return CXChildVisit_Recurse;
3243
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003244 *BestCursor = cursor;
3245 return CXChildVisit_Recurse;
3246}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003247
Douglas Gregorb9790342010-01-22 21:44:22 +00003248CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3249 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003250 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003251
Ted Kremeneka60ed472010-11-16 08:15:36 +00003252 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003253 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3254
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003255 // Translate the given source location to make it point at the beginning of
3256 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003257 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003258
3259 // Guard against an invalid SourceLocation, or we may assert in one
3260 // of the following calls.
3261 if (SLoc.isInvalid())
3262 return clang_getNullCursor();
3263
Douglas Gregor40749ee2010-11-03 00:35:38 +00003264 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003265 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3266 CXXUnit->getASTContext().getLangOptions());
3267
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003268 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3269 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003270 // FIXME: Would be great to have a "hint" cursor, then walk from that
3271 // hint cursor upward until we find a cursor whose source range encloses
3272 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003273 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3274 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003275 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003276 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003277 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003278
3279 if (Logging) {
3280 CXFile SearchFile;
3281 unsigned SearchLine, SearchColumn;
3282 CXFile ResultFile;
3283 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003284 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3285 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003286 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3287
3288 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3289 0);
3290 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3291 &ResultColumn, 0);
3292 SearchFileName = clang_getFileName(SearchFile);
3293 ResultFileName = clang_getFileName(ResultFile);
3294 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003295 USR = clang_getCursorUSR(Result);
3296 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003297 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3298 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003299 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3300 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003301 clang_disposeString(SearchFileName);
3302 clang_disposeString(ResultFileName);
3303 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003304 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003305
3306 CXCursor Definition = clang_getCursorDefinition(Result);
3307 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3308 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3309 CXString DefinitionKindSpelling
3310 = clang_getCursorKindSpelling(Definition.kind);
3311 CXFile DefinitionFile;
3312 unsigned DefinitionLine, DefinitionColumn;
3313 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3314 &DefinitionLine, &DefinitionColumn, 0);
3315 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3316 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3317 clang_getCString(DefinitionKindSpelling),
3318 clang_getCString(DefinitionFileName),
3319 DefinitionLine, DefinitionColumn);
3320 clang_disposeString(DefinitionFileName);
3321 clang_disposeString(DefinitionKindSpelling);
3322 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003323 }
3324
Ted Kremeneke68fff62010-02-17 00:41:32 +00003325 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003326}
3327
Ted Kremenek73885552009-11-17 19:28:59 +00003328CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003329 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003330}
3331
3332unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003333 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003334}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003335
Douglas Gregor9ce55842010-11-20 00:09:34 +00003336unsigned clang_hashCursor(CXCursor C) {
3337 unsigned Index = 0;
3338 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3339 Index = 1;
3340
3341 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3342 std::make_pair(C.kind, C.data[Index]));
3343}
3344
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003345unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003346 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3347}
3348
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003349unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003350 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3351}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003352
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003353unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003354 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3355}
3356
Douglas Gregor97b98722010-01-19 23:20:36 +00003357unsigned clang_isExpression(enum CXCursorKind K) {
3358 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3359}
3360
3361unsigned clang_isStatement(enum CXCursorKind K) {
3362 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3363}
3364
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003365unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3366 return K == CXCursor_TranslationUnit;
3367}
3368
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003369unsigned clang_isPreprocessing(enum CXCursorKind K) {
3370 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3371}
3372
Ted Kremenekad6eff62010-03-08 21:17:29 +00003373unsigned clang_isUnexposed(enum CXCursorKind K) {
3374 switch (K) {
3375 case CXCursor_UnexposedDecl:
3376 case CXCursor_UnexposedExpr:
3377 case CXCursor_UnexposedStmt:
3378 case CXCursor_UnexposedAttr:
3379 return true;
3380 default:
3381 return false;
3382 }
3383}
3384
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003385CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003386 return C.kind;
3387}
3388
Douglas Gregor98258af2010-01-18 22:46:11 +00003389CXSourceLocation clang_getCursorLocation(CXCursor C) {
3390 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003391 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003392 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003393 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3394 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003395 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003396 }
3397
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003398 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003399 std::pair<ObjCProtocolDecl *, SourceLocation> P
3400 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003401 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003402 }
3403
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003404 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003405 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3406 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003407 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003408 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003409
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003410 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003411 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003412 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003413 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003414
3415 case CXCursor_TemplateRef: {
3416 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3417 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3418 }
3419
Douglas Gregor69319002010-08-31 23:48:11 +00003420 case CXCursor_NamespaceRef: {
3421 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3422 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3423 }
3424
Douglas Gregora67e03f2010-09-09 21:42:20 +00003425 case CXCursor_MemberRef: {
3426 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3427 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3428 }
3429
Ted Kremenek3064ef92010-08-27 21:34:58 +00003430 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003431 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3432 if (!BaseSpec)
3433 return clang_getNullLocation();
3434
3435 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3436 return cxloc::translateSourceLocation(getCursorContext(C),
3437 TSInfo->getTypeLoc().getBeginLoc());
3438
3439 return cxloc::translateSourceLocation(getCursorContext(C),
3440 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003441 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003442
Douglas Gregor36897b02010-09-10 00:22:18 +00003443 case CXCursor_LabelRef: {
3444 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3445 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3446 }
3447
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003448 case CXCursor_OverloadedDeclRef:
3449 return cxloc::translateSourceLocation(getCursorContext(C),
3450 getCursorOverloadedDeclRef(C).second);
3451
Douglas Gregorf46034a2010-01-18 23:41:10 +00003452 default:
3453 // FIXME: Need a way to enumerate all non-reference cases.
3454 llvm_unreachable("Missed a reference kind");
3455 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003456 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003457
3458 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003459 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003460 getLocationFromExpr(getCursorExpr(C)));
3461
Douglas Gregor36897b02010-09-10 00:22:18 +00003462 if (clang_isStatement(C.kind))
3463 return cxloc::translateSourceLocation(getCursorContext(C),
3464 getCursorStmt(C)->getLocStart());
3465
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003466 if (C.kind == CXCursor_PreprocessingDirective) {
3467 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3468 return cxloc::translateSourceLocation(getCursorContext(C), L);
3469 }
Douglas Gregor48072312010-03-18 15:23:44 +00003470
3471 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003472 SourceLocation L
3473 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003474 return cxloc::translateSourceLocation(getCursorContext(C), L);
3475 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003476
3477 if (C.kind == CXCursor_MacroDefinition) {
3478 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3479 return cxloc::translateSourceLocation(getCursorContext(C), L);
3480 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003481
3482 if (C.kind == CXCursor_InclusionDirective) {
3483 SourceLocation L
3484 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3485 return cxloc::translateSourceLocation(getCursorContext(C), L);
3486 }
3487
Ted Kremenek9a700d22010-05-12 06:16:13 +00003488 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003489 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003490
Douglas Gregorf46034a2010-01-18 23:41:10 +00003491 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003492 SourceLocation Loc = D->getLocation();
3493 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3494 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003495 // FIXME: Multiple variables declared in a single declaration
3496 // currently lack the information needed to correctly determine their
3497 // ranges when accounting for the type-specifier. We use context
3498 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3499 // and if so, whether it is the first decl.
3500 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3501 if (!cxcursor::isFirstInDeclGroup(C))
3502 Loc = VD->getLocation();
3503 }
3504
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003505 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003506}
Douglas Gregora7bde202010-01-19 00:34:46 +00003507
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003508} // end extern "C"
3509
3510static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003511 if (clang_isReference(C.kind)) {
3512 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003513 case CXCursor_ObjCSuperClassRef:
3514 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003515
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003516 case CXCursor_ObjCProtocolRef:
3517 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003518
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003519 case CXCursor_ObjCClassRef:
3520 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003521
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003522 case CXCursor_TypeRef:
3523 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003524
3525 case CXCursor_TemplateRef:
3526 return getCursorTemplateRef(C).second;
3527
Douglas Gregor69319002010-08-31 23:48:11 +00003528 case CXCursor_NamespaceRef:
3529 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003530
3531 case CXCursor_MemberRef:
3532 return getCursorMemberRef(C).second;
3533
Ted Kremenek3064ef92010-08-27 21:34:58 +00003534 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003535 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003536
Douglas Gregor36897b02010-09-10 00:22:18 +00003537 case CXCursor_LabelRef:
3538 return getCursorLabelRef(C).second;
3539
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003540 case CXCursor_OverloadedDeclRef:
3541 return getCursorOverloadedDeclRef(C).second;
3542
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003543 default:
3544 // FIXME: Need a way to enumerate all non-reference cases.
3545 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003546 }
3547 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003548
3549 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003550 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003551
3552 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003553 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003554
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003555 if (C.kind == CXCursor_PreprocessingDirective)
3556 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003557
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003558 if (C.kind == CXCursor_MacroInstantiation)
3559 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003560
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003561 if (C.kind == CXCursor_MacroDefinition)
3562 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003563
3564 if (C.kind == CXCursor_InclusionDirective)
3565 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3566
Ted Kremenek007a7c92010-11-01 23:26:51 +00003567 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3568 Decl *D = cxcursor::getCursorDecl(C);
3569 SourceRange R = D->getSourceRange();
3570 // FIXME: Multiple variables declared in a single declaration
3571 // currently lack the information needed to correctly determine their
3572 // ranges when accounting for the type-specifier. We use context
3573 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3574 // and if so, whether it is the first decl.
3575 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3576 if (!cxcursor::isFirstInDeclGroup(C))
3577 R.setBegin(VD->getLocation());
3578 }
3579 return R;
3580 }
Douglas Gregor66537982010-11-17 17:14:07 +00003581 return SourceRange();
3582}
3583
3584/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3585/// the decl-specifier-seq for declarations.
3586static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3587 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3588 Decl *D = cxcursor::getCursorDecl(C);
3589 SourceRange R = D->getSourceRange();
3590
3591 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3592 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3593 TypeLoc TL = TI->getTypeLoc();
3594 SourceLocation TLoc = TL.getSourceRange().getBegin();
3595 if (TLoc.isValid() && R.getBegin().isValid() &&
3596 SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3597 R.setBegin(TLoc);
3598 }
3599
3600 // FIXME: Multiple variables declared in a single declaration
3601 // currently lack the information needed to correctly determine their
3602 // ranges when accounting for the type-specifier. We use context
3603 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3604 // and if so, whether it is the first decl.
3605 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3606 if (!cxcursor::isFirstInDeclGroup(C))
3607 R.setBegin(VD->getLocation());
3608 }
3609 }
3610
3611 return R;
3612 }
3613
3614 return getRawCursorExtent(C);
3615}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003616
3617extern "C" {
3618
3619CXSourceRange clang_getCursorExtent(CXCursor C) {
3620 SourceRange R = getRawCursorExtent(C);
3621 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003622 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003623
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003624 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003625}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003626
3627CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003628 if (clang_isInvalid(C.kind))
3629 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003630
Ted Kremeneka60ed472010-11-16 08:15:36 +00003631 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003632 if (clang_isDeclaration(C.kind)) {
3633 Decl *D = getCursorDecl(C);
3634 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003635 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003636 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003637 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003638 if (ObjCForwardProtocolDecl *Protocols
3639 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003640 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003641 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3642 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3643 return MakeCXCursor(Property, tu);
3644
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003645 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003646 }
3647
Douglas Gregor97b98722010-01-19 23:20:36 +00003648 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003649 Expr *E = getCursorExpr(C);
3650 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003651 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003652 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003653
3654 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003655 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003656
Douglas Gregor97b98722010-01-19 23:20:36 +00003657 return clang_getNullCursor();
3658 }
3659
Douglas Gregor36897b02010-09-10 00:22:18 +00003660 if (clang_isStatement(C.kind)) {
3661 Stmt *S = getCursorStmt(C);
3662 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003663 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003664
3665 return clang_getNullCursor();
3666 }
3667
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003668 if (C.kind == CXCursor_MacroInstantiation) {
3669 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003670 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003671 }
3672
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003673 if (!clang_isReference(C.kind))
3674 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003675
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003676 switch (C.kind) {
3677 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003678 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003679
3680 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003681 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003682
3683 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003684 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003685
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003686 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003687 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003688
3689 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003690 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003691
Douglas Gregor69319002010-08-31 23:48:11 +00003692 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003693 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003694
Douglas Gregora67e03f2010-09-09 21:42:20 +00003695 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003696 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003697
Ted Kremenek3064ef92010-08-27 21:34:58 +00003698 case CXCursor_CXXBaseSpecifier: {
3699 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3700 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003701 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003702 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003703
Douglas Gregor36897b02010-09-10 00:22:18 +00003704 case CXCursor_LabelRef:
3705 // FIXME: We end up faking the "parent" declaration here because we
3706 // don't want to make CXCursor larger.
3707 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003708 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3709 .getTranslationUnitDecl(),
3710 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003711
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003712 case CXCursor_OverloadedDeclRef:
3713 return C;
3714
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003715 default:
3716 // We would prefer to enumerate all non-reference cursor kinds here.
3717 llvm_unreachable("Unhandled reference cursor kind");
3718 break;
3719 }
3720 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003721
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003722 return clang_getNullCursor();
3723}
3724
Douglas Gregorb6998662010-01-19 19:34:47 +00003725CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003726 if (clang_isInvalid(C.kind))
3727 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003728
Ted Kremeneka60ed472010-11-16 08:15:36 +00003729 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003730
Douglas Gregorb6998662010-01-19 19:34:47 +00003731 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003732 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003733 C = clang_getCursorReferenced(C);
3734 WasReference = true;
3735 }
3736
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003737 if (C.kind == CXCursor_MacroInstantiation)
3738 return clang_getCursorReferenced(C);
3739
Douglas Gregorb6998662010-01-19 19:34:47 +00003740 if (!clang_isDeclaration(C.kind))
3741 return clang_getNullCursor();
3742
3743 Decl *D = getCursorDecl(C);
3744 if (!D)
3745 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003746
Douglas Gregorb6998662010-01-19 19:34:47 +00003747 switch (D->getKind()) {
3748 // Declaration kinds that don't really separate the notions of
3749 // declaration and definition.
3750 case Decl::Namespace:
3751 case Decl::Typedef:
3752 case Decl::TemplateTypeParm:
3753 case Decl::EnumConstant:
3754 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003755 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003756 case Decl::ObjCIvar:
3757 case Decl::ObjCAtDefsField:
3758 case Decl::ImplicitParam:
3759 case Decl::ParmVar:
3760 case Decl::NonTypeTemplateParm:
3761 case Decl::TemplateTemplateParm:
3762 case Decl::ObjCCategoryImpl:
3763 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003764 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003765 case Decl::LinkageSpec:
3766 case Decl::ObjCPropertyImpl:
3767 case Decl::FileScopeAsm:
3768 case Decl::StaticAssert:
3769 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003770 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003771 return C;
3772
3773 // Declaration kinds that don't make any sense here, but are
3774 // nonetheless harmless.
3775 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003776 break;
3777
3778 // Declaration kinds for which the definition is not resolvable.
3779 case Decl::UnresolvedUsingTypename:
3780 case Decl::UnresolvedUsingValue:
3781 break;
3782
3783 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003784 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003785 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003786
3787 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003788 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003789
3790 case Decl::Enum:
3791 case Decl::Record:
3792 case Decl::CXXRecord:
3793 case Decl::ClassTemplateSpecialization:
3794 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003795 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003796 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003797 return clang_getNullCursor();
3798
3799 case Decl::Function:
3800 case Decl::CXXMethod:
3801 case Decl::CXXConstructor:
3802 case Decl::CXXDestructor:
3803 case Decl::CXXConversion: {
3804 const FunctionDecl *Def = 0;
3805 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003806 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003807 return clang_getNullCursor();
3808 }
3809
3810 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003811 // Ask the variable if it has a definition.
3812 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003813 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003814 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003815 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003816
Douglas Gregorb6998662010-01-19 19:34:47 +00003817 case Decl::FunctionTemplate: {
3818 const FunctionDecl *Def = 0;
3819 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003820 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003821 return clang_getNullCursor();
3822 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003823
Douglas Gregorb6998662010-01-19 19:34:47 +00003824 case Decl::ClassTemplate: {
3825 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003826 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003827 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003828 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003829 return clang_getNullCursor();
3830 }
3831
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003832 case Decl::Using:
3833 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003834 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003835
3836 case Decl::UsingShadow:
3837 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003838 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003839 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003840
3841 case Decl::ObjCMethod: {
3842 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3843 if (Method->isThisDeclarationADefinition())
3844 return C;
3845
3846 // Dig out the method definition in the associated
3847 // @implementation, if we have it.
3848 // FIXME: The ASTs should make finding the definition easier.
3849 if (ObjCInterfaceDecl *Class
3850 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3851 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3852 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3853 Method->isInstanceMethod()))
3854 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003855 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003856
3857 return clang_getNullCursor();
3858 }
3859
3860 case Decl::ObjCCategory:
3861 if (ObjCCategoryImplDecl *Impl
3862 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003863 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003864 return clang_getNullCursor();
3865
3866 case Decl::ObjCProtocol:
3867 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3868 return C;
3869 return clang_getNullCursor();
3870
3871 case Decl::ObjCInterface:
3872 // There are two notions of a "definition" for an Objective-C
3873 // class: the interface and its implementation. When we resolved a
3874 // reference to an Objective-C class, produce the @interface as
3875 // the definition; when we were provided with the interface,
3876 // produce the @implementation as the definition.
3877 if (WasReference) {
3878 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3879 return C;
3880 } else if (ObjCImplementationDecl *Impl
3881 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003882 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003883 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003884
Douglas Gregorb6998662010-01-19 19:34:47 +00003885 case Decl::ObjCProperty:
3886 // FIXME: We don't really know where to find the
3887 // ObjCPropertyImplDecls that implement this property.
3888 return clang_getNullCursor();
3889
3890 case Decl::ObjCCompatibleAlias:
3891 if (ObjCInterfaceDecl *Class
3892 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3893 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003894 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003895
Douglas Gregorb6998662010-01-19 19:34:47 +00003896 return clang_getNullCursor();
3897
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003898 case Decl::ObjCForwardProtocol:
3899 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003900 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003901
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003902 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003903 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003904 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003905
3906 case Decl::Friend:
3907 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003908 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003909 return clang_getNullCursor();
3910
3911 case Decl::FriendTemplate:
3912 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003913 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003914 return clang_getNullCursor();
3915 }
3916
3917 return clang_getNullCursor();
3918}
3919
3920unsigned clang_isCursorDefinition(CXCursor C) {
3921 if (!clang_isDeclaration(C.kind))
3922 return 0;
3923
3924 return clang_getCursorDefinition(C) == C;
3925}
3926
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003927CXCursor clang_getCanonicalCursor(CXCursor C) {
3928 if (!clang_isDeclaration(C.kind))
3929 return C;
3930
3931 if (Decl *D = getCursorDecl(C))
3932 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3933
3934 return C;
3935}
3936
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003937unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003938 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003939 return 0;
3940
3941 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3942 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3943 return E->getNumDecls();
3944
3945 if (OverloadedTemplateStorage *S
3946 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3947 return S->size();
3948
3949 Decl *D = Storage.get<Decl*>();
3950 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003951 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003952 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3953 return Classes->size();
3954 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3955 return Protocols->protocol_size();
3956
3957 return 0;
3958}
3959
3960CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003961 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003962 return clang_getNullCursor();
3963
3964 if (index >= clang_getNumOverloadedDecls(cursor))
3965 return clang_getNullCursor();
3966
Ted Kremeneka60ed472010-11-16 08:15:36 +00003967 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003968 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3969 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003970 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003971
3972 if (OverloadedTemplateStorage *S
3973 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003974 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003975
3976 Decl *D = Storage.get<Decl*>();
3977 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3978 // FIXME: This is, unfortunately, linear time.
3979 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3980 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003981 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003982 }
3983
3984 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003985 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003986
3987 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003988 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003989
3990 return clang_getNullCursor();
3991}
3992
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003993void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003994 const char **startBuf,
3995 const char **endBuf,
3996 unsigned *startLine,
3997 unsigned *startColumn,
3998 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003999 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004000 assert(getCursorDecl(C) && "CXCursor has null decl");
4001 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004002 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4003 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004004
Steve Naroff4ade6d62009-09-23 17:52:52 +00004005 SourceManager &SM = FD->getASTContext().getSourceManager();
4006 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4007 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4008 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4009 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4010 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4011 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4012}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004013
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004014void clang_enableStackTraces(void) {
4015 llvm::sys::PrintStackTraceOnErrorSignal();
4016}
4017
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004018void clang_executeOnThread(void (*fn)(void*), void *user_data,
4019 unsigned stack_size) {
4020 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4021}
4022
Ted Kremenekfb480492010-01-13 21:46:36 +00004023} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004024
Ted Kremenekfb480492010-01-13 21:46:36 +00004025//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004026// Token-based Operations.
4027//===----------------------------------------------------------------------===//
4028
4029/* CXToken layout:
4030 * int_data[0]: a CXTokenKind
4031 * int_data[1]: starting token location
4032 * int_data[2]: token length
4033 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004034 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004035 * otherwise unused.
4036 */
4037extern "C" {
4038
4039CXTokenKind clang_getTokenKind(CXToken CXTok) {
4040 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4041}
4042
4043CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4044 switch (clang_getTokenKind(CXTok)) {
4045 case CXToken_Identifier:
4046 case CXToken_Keyword:
4047 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004048 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4049 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004050
4051 case CXToken_Literal: {
4052 // We have stashed the starting pointer in the ptr_data field. Use it.
4053 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004054 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004055 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004056
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004057 case CXToken_Punctuation:
4058 case CXToken_Comment:
4059 break;
4060 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004061
4062 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004063 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004064 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004065 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004066 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004067
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004068 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4069 std::pair<FileID, unsigned> LocInfo
4070 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004071 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004072 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004073 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4074 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004075 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004076
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004077 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004078}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004079
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004080CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004081 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004082 if (!CXXUnit)
4083 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004084
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004085 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4086 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4087}
4088
4089CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004090 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004091 if (!CXXUnit)
4092 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004093
4094 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004095 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4096}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004097
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004098void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4099 CXToken **Tokens, unsigned *NumTokens) {
4100 if (Tokens)
4101 *Tokens = 0;
4102 if (NumTokens)
4103 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004104
Ted Kremeneka60ed472010-11-16 08:15:36 +00004105 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004106 if (!CXXUnit || !Tokens || !NumTokens)
4107 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004108
Douglas Gregorbdf60622010-03-05 21:16:25 +00004109 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4110
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004111 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004112 if (R.isInvalid())
4113 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004114
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004115 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4116 std::pair<FileID, unsigned> BeginLocInfo
4117 = SourceMgr.getDecomposedLoc(R.getBegin());
4118 std::pair<FileID, unsigned> EndLocInfo
4119 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004120
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004121 // Cannot tokenize across files.
4122 if (BeginLocInfo.first != EndLocInfo.first)
4123 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004124
4125 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004126 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004127 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004128 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004129 if (Invalid)
4130 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004131
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004132 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4133 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004134 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004135 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004136
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004137 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004138 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004139 llvm::SmallVector<CXToken, 32> CXTokens;
4140 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004141 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004142 do {
4143 // Lex the next token
4144 Lex.LexFromRawLexer(Tok);
4145 if (Tok.is(tok::eof))
4146 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004147
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004148 // Initialize the CXToken.
4149 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004150
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004151 // - Common fields
4152 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4153 CXTok.int_data[2] = Tok.getLength();
4154 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004155
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004156 // - Kind-specific fields
4157 if (Tok.isLiteral()) {
4158 CXTok.int_data[0] = CXToken_Literal;
4159 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004160 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004161 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004162 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004163 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004164
David Chisnall096428b2010-10-13 21:44:48 +00004165 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004166 CXTok.int_data[0] = CXToken_Keyword;
4167 }
4168 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004169 CXTok.int_data[0] = Tok.is(tok::identifier)
4170 ? CXToken_Identifier
4171 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004172 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004173 CXTok.ptr_data = II;
4174 } else if (Tok.is(tok::comment)) {
4175 CXTok.int_data[0] = CXToken_Comment;
4176 CXTok.ptr_data = 0;
4177 } else {
4178 CXTok.int_data[0] = CXToken_Punctuation;
4179 CXTok.ptr_data = 0;
4180 }
4181 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004182 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004183 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004184
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004185 if (CXTokens.empty())
4186 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004187
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004188 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4189 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4190 *NumTokens = CXTokens.size();
4191}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004192
Ted Kremenek6db61092010-05-05 00:55:15 +00004193void clang_disposeTokens(CXTranslationUnit TU,
4194 CXToken *Tokens, unsigned NumTokens) {
4195 free(Tokens);
4196}
4197
4198} // end: extern "C"
4199
4200//===----------------------------------------------------------------------===//
4201// Token annotation APIs.
4202//===----------------------------------------------------------------------===//
4203
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004204typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004205static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4206 CXCursor parent,
4207 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004208namespace {
4209class AnnotateTokensWorker {
4210 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004211 CXToken *Tokens;
4212 CXCursor *Cursors;
4213 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004214 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004215 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004216 CursorVisitor AnnotateVis;
4217 SourceManager &SrcMgr;
4218
4219 bool MoreTokens() const { return TokIdx < NumTokens; }
4220 unsigned NextToken() const { return TokIdx; }
4221 void AdvanceToken() { ++TokIdx; }
4222 SourceLocation GetTokenLoc(unsigned tokI) {
4223 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4224 }
4225
Ted Kremenek6db61092010-05-05 00:55:15 +00004226public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004227 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004228 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004229 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004230 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004231 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004232 AnnotateVis(tu,
4233 AnnotateTokensVisitor, this,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004234 Decl::MaxPCHLevel, RegionOfInterest),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004235 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00004236
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004237 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004238 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004240 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004241 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004242 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004243};
4244}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004245
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004246void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4247 // Walk the AST within the region of interest, annotating tokens
4248 // along the way.
4249 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004250
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004251 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4252 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004253 if (Pos != Annotated.end() &&
4254 (clang_isInvalid(Cursors[I].kind) ||
4255 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004256 Cursors[I] = Pos->second;
4257 }
4258
4259 // Finish up annotating any tokens left.
4260 if (!MoreTokens())
4261 return;
4262
4263 const CXCursor &C = clang_getNullCursor();
4264 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4265 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4266 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004267 }
4268}
4269
Ted Kremenek6db61092010-05-05 00:55:15 +00004270enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004271AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004272 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004273 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004274 if (cursorRange.isInvalid())
4275 return CXChildVisit_Recurse;
4276
Douglas Gregor4419b672010-10-21 06:10:04 +00004277 if (clang_isPreprocessing(cursor.kind)) {
4278 // For macro instantiations, just note where the beginning of the macro
4279 // instantiation occurs.
4280 if (cursor.kind == CXCursor_MacroInstantiation) {
4281 Annotated[Loc.int_data] = cursor;
4282 return CXChildVisit_Recurse;
4283 }
4284
Douglas Gregor4419b672010-10-21 06:10:04 +00004285 // Items in the preprocessing record are kept separate from items in
4286 // declarations, so we keep a separate token index.
4287 unsigned SavedTokIdx = TokIdx;
4288 TokIdx = PreprocessingTokIdx;
4289
4290 // Skip tokens up until we catch up to the beginning of the preprocessing
4291 // entry.
4292 while (MoreTokens()) {
4293 const unsigned I = NextToken();
4294 SourceLocation TokLoc = GetTokenLoc(I);
4295 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4296 case RangeBefore:
4297 AdvanceToken();
4298 continue;
4299 case RangeAfter:
4300 case RangeOverlap:
4301 break;
4302 }
4303 break;
4304 }
4305
4306 // Look at all of the tokens within this range.
4307 while (MoreTokens()) {
4308 const unsigned I = NextToken();
4309 SourceLocation TokLoc = GetTokenLoc(I);
4310 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4311 case RangeBefore:
4312 assert(0 && "Infeasible");
4313 case RangeAfter:
4314 break;
4315 case RangeOverlap:
4316 Cursors[I] = cursor;
4317 AdvanceToken();
4318 continue;
4319 }
4320 break;
4321 }
4322
4323 // Save the preprocessing token index; restore the non-preprocessing
4324 // token index.
4325 PreprocessingTokIdx = TokIdx;
4326 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004327 return CXChildVisit_Recurse;
4328 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004329
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004330 if (cursorRange.isInvalid())
4331 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004332
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004333 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4334
Ted Kremeneka333c662010-05-12 05:29:33 +00004335 // Adjust the annotated range based specific declarations.
4336 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4337 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004338 Decl *D = cxcursor::getCursorDecl(cursor);
4339 // Don't visit synthesized ObjC methods, since they have no syntatic
4340 // representation in the source.
4341 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4342 if (MD->isSynthesized())
4343 return CXChildVisit_Continue;
4344 }
4345 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004346 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4347 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004348 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004349 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004350 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004351 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004352 }
4353 }
4354 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004355
Ted Kremenek3f404602010-08-14 01:14:06 +00004356 // If the location of the cursor occurs within a macro instantiation, record
4357 // the spelling location of the cursor in our annotation map. We can then
4358 // paper over the token labelings during a post-processing step to try and
4359 // get cursor mappings for tokens that are the *arguments* of a macro
4360 // instantiation.
4361 if (L.isMacroID()) {
4362 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4363 // Only invalidate the old annotation if it isn't part of a preprocessing
4364 // directive. Here we assume that the default construction of CXCursor
4365 // results in CXCursor.kind being an initialized value (i.e., 0). If
4366 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004367
Ted Kremenek3f404602010-08-14 01:14:06 +00004368 CXCursor &oldC = Annotated[rawEncoding];
4369 if (!clang_isPreprocessing(oldC.kind))
4370 oldC = cursor;
4371 }
4372
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004373 const enum CXCursorKind K = clang_getCursorKind(parent);
4374 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004375 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4376 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004377
4378 while (MoreTokens()) {
4379 const unsigned I = NextToken();
4380 SourceLocation TokLoc = GetTokenLoc(I);
4381 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4382 case RangeBefore:
4383 Cursors[I] = updateC;
4384 AdvanceToken();
4385 continue;
4386 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004387 case RangeOverlap:
4388 break;
4389 }
4390 break;
4391 }
4392
4393 // Visit children to get their cursor information.
4394 const unsigned BeforeChildren = NextToken();
4395 VisitChildren(cursor);
4396 const unsigned AfterChildren = NextToken();
4397
4398 // Adjust 'Last' to the last token within the extent of the cursor.
4399 while (MoreTokens()) {
4400 const unsigned I = NextToken();
4401 SourceLocation TokLoc = GetTokenLoc(I);
4402 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4403 case RangeBefore:
4404 assert(0 && "Infeasible");
4405 case RangeAfter:
4406 break;
4407 case RangeOverlap:
4408 Cursors[I] = updateC;
4409 AdvanceToken();
4410 continue;
4411 }
4412 break;
4413 }
4414 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004415
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004416 // Scan the tokens that are at the beginning of the cursor, but are not
4417 // capture by the child cursors.
4418
4419 // For AST elements within macros, rely on a post-annotate pass to
4420 // to correctly annotate the tokens with cursors. Otherwise we can
4421 // get confusing results of having tokens that map to cursors that really
4422 // are expanded by an instantiation.
4423 if (L.isMacroID())
4424 cursor = clang_getNullCursor();
4425
4426 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4427 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4428 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004429
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004430 Cursors[I] = cursor;
4431 }
4432 // Scan the tokens that are at the end of the cursor, but are not captured
4433 // but the child cursors.
4434 for (unsigned I = AfterChildren; I != Last; ++I)
4435 Cursors[I] = cursor;
4436
4437 TokIdx = Last;
4438 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004439}
4440
Ted Kremenek6db61092010-05-05 00:55:15 +00004441static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4442 CXCursor parent,
4443 CXClientData client_data) {
4444 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4445}
4446
Ted Kremenekab979612010-11-11 08:05:23 +00004447// This gets run a separate thread to avoid stack blowout.
4448static void runAnnotateTokensWorker(void *UserData) {
4449 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4450}
4451
Ted Kremenek6db61092010-05-05 00:55:15 +00004452extern "C" {
4453
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004454void clang_annotateTokens(CXTranslationUnit TU,
4455 CXToken *Tokens, unsigned NumTokens,
4456 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004457
4458 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004459 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004460
Douglas Gregor4419b672010-10-21 06:10:04 +00004461 // Any token we don't specifically annotate will have a NULL cursor.
4462 CXCursor C = clang_getNullCursor();
4463 for (unsigned I = 0; I != NumTokens; ++I)
4464 Cursors[I] = C;
4465
Ted Kremeneka60ed472010-11-16 08:15:36 +00004466 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004467 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004468 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004469
Douglas Gregorbdf60622010-03-05 21:16:25 +00004470 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004471
Douglas Gregor0396f462010-03-19 05:22:59 +00004472 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004473 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004474 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4475 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004476 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4477 clang_getTokenLocation(TU,
4478 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004479
Douglas Gregor0396f462010-03-19 05:22:59 +00004480 // A mapping from the source locations found when re-lexing or traversing the
4481 // region of interest to the corresponding cursors.
4482 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004483
4484 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004485 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004486 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4487 std::pair<FileID, unsigned> BeginLocInfo
4488 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4489 std::pair<FileID, unsigned> EndLocInfo
4490 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004491
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004492 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004493 bool Invalid = false;
4494 if (BeginLocInfo.first == EndLocInfo.first &&
4495 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4496 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004497 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4498 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004499 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004500 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004501 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004502
4503 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004504 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004505 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004506 Token Tok;
4507 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004508
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004509 reprocess:
4510 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4511 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004512 // don't see it while preprocessing these tokens later, but keep track
4513 // of all of the token locations inside this preprocessing directive so
4514 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004515 //
4516 // FIXME: Some simple tests here could identify macro definitions and
4517 // #undefs, to provide specific cursor kinds for those.
4518 std::vector<SourceLocation> Locations;
4519 do {
4520 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004521 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004522 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004523
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004524 using namespace cxcursor;
4525 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004526 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4527 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004528 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004529 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4530 Annotated[Locations[I].getRawEncoding()] = Cursor;
4531 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004532
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004533 if (Tok.isAtStartOfLine())
4534 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004535
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004536 continue;
4537 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004538
Douglas Gregor48072312010-03-18 15:23:44 +00004539 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004540 break;
4541 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004542 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004543
Douglas Gregor0396f462010-03-19 05:22:59 +00004544 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004545 // a specific cursor.
4546 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004547 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004548
4549 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004550 // FIXME: We use a ridiculous stack size here because the data-recursion
4551 // algorithm uses a large stack frame than the non-data recursive version,
4552 // and AnnotationTokensWorker currently transforms the data-recursion
4553 // algorithm back into a traditional recursion by explicitly calling
4554 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004555 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004556 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4557 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004558 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4559 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004560}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004561} // end: extern "C"
4562
4563//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004564// Operations for querying linkage of a cursor.
4565//===----------------------------------------------------------------------===//
4566
4567extern "C" {
4568CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004569 if (!clang_isDeclaration(cursor.kind))
4570 return CXLinkage_Invalid;
4571
Ted Kremenek16b42592010-03-03 06:36:57 +00004572 Decl *D = cxcursor::getCursorDecl(cursor);
4573 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4574 switch (ND->getLinkage()) {
4575 case NoLinkage: return CXLinkage_NoLinkage;
4576 case InternalLinkage: return CXLinkage_Internal;
4577 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4578 case ExternalLinkage: return CXLinkage_External;
4579 };
4580
4581 return CXLinkage_Invalid;
4582}
4583} // end: extern "C"
4584
4585//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004586// Operations for querying language of a cursor.
4587//===----------------------------------------------------------------------===//
4588
4589static CXLanguageKind getDeclLanguage(const Decl *D) {
4590 switch (D->getKind()) {
4591 default:
4592 break;
4593 case Decl::ImplicitParam:
4594 case Decl::ObjCAtDefsField:
4595 case Decl::ObjCCategory:
4596 case Decl::ObjCCategoryImpl:
4597 case Decl::ObjCClass:
4598 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004599 case Decl::ObjCForwardProtocol:
4600 case Decl::ObjCImplementation:
4601 case Decl::ObjCInterface:
4602 case Decl::ObjCIvar:
4603 case Decl::ObjCMethod:
4604 case Decl::ObjCProperty:
4605 case Decl::ObjCPropertyImpl:
4606 case Decl::ObjCProtocol:
4607 return CXLanguage_ObjC;
4608 case Decl::CXXConstructor:
4609 case Decl::CXXConversion:
4610 case Decl::CXXDestructor:
4611 case Decl::CXXMethod:
4612 case Decl::CXXRecord:
4613 case Decl::ClassTemplate:
4614 case Decl::ClassTemplatePartialSpecialization:
4615 case Decl::ClassTemplateSpecialization:
4616 case Decl::Friend:
4617 case Decl::FriendTemplate:
4618 case Decl::FunctionTemplate:
4619 case Decl::LinkageSpec:
4620 case Decl::Namespace:
4621 case Decl::NamespaceAlias:
4622 case Decl::NonTypeTemplateParm:
4623 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004624 case Decl::TemplateTemplateParm:
4625 case Decl::TemplateTypeParm:
4626 case Decl::UnresolvedUsingTypename:
4627 case Decl::UnresolvedUsingValue:
4628 case Decl::Using:
4629 case Decl::UsingDirective:
4630 case Decl::UsingShadow:
4631 return CXLanguage_CPlusPlus;
4632 }
4633
4634 return CXLanguage_C;
4635}
4636
4637extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004638
4639enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4640 if (clang_isDeclaration(cursor.kind))
4641 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4642 if (D->hasAttr<UnavailableAttr>() ||
4643 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4644 return CXAvailability_Available;
4645
4646 if (D->hasAttr<DeprecatedAttr>())
4647 return CXAvailability_Deprecated;
4648 }
4649
4650 return CXAvailability_Available;
4651}
4652
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004653CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4654 if (clang_isDeclaration(cursor.kind))
4655 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4656
4657 return CXLanguage_Invalid;
4658}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004659
4660 /// \brief If the given cursor is the "templated" declaration
4661 /// descibing a class or function template, return the class or
4662 /// function template.
4663static Decl *maybeGetTemplateCursor(Decl *D) {
4664 if (!D)
4665 return 0;
4666
4667 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4668 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4669 return FunTmpl;
4670
4671 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4672 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4673 return ClassTmpl;
4674
4675 return D;
4676}
4677
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004678CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4679 if (clang_isDeclaration(cursor.kind)) {
4680 if (Decl *D = getCursorDecl(cursor)) {
4681 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004682 if (!DC)
4683 return clang_getNullCursor();
4684
4685 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4686 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004687 }
4688 }
4689
4690 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4691 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004692 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004693 }
4694
4695 return clang_getNullCursor();
4696}
4697
4698CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4699 if (clang_isDeclaration(cursor.kind)) {
4700 if (Decl *D = getCursorDecl(cursor)) {
4701 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004702 if (!DC)
4703 return clang_getNullCursor();
4704
4705 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4706 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004707 }
4708 }
4709
4710 // FIXME: Note that we can't easily compute the lexical context of a
4711 // statement or expression, so we return nothing.
4712 return clang_getNullCursor();
4713}
4714
Douglas Gregor9f592342010-10-01 20:25:15 +00004715static void CollectOverriddenMethods(DeclContext *Ctx,
4716 ObjCMethodDecl *Method,
4717 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4718 if (!Ctx)
4719 return;
4720
4721 // If we have a class or category implementation, jump straight to the
4722 // interface.
4723 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4724 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4725
4726 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4727 if (!Container)
4728 return;
4729
4730 // Check whether we have a matching method at this level.
4731 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4732 Method->isInstanceMethod()))
4733 if (Method != Overridden) {
4734 // We found an override at this level; there is no need to look
4735 // into other protocols or categories.
4736 Methods.push_back(Overridden);
4737 return;
4738 }
4739
4740 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4741 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4742 PEnd = Protocol->protocol_end();
4743 P != PEnd; ++P)
4744 CollectOverriddenMethods(*P, Method, Methods);
4745 }
4746
4747 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4748 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4749 PEnd = Category->protocol_end();
4750 P != PEnd; ++P)
4751 CollectOverriddenMethods(*P, Method, Methods);
4752 }
4753
4754 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4755 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4756 PEnd = Interface->protocol_end();
4757 P != PEnd; ++P)
4758 CollectOverriddenMethods(*P, Method, Methods);
4759
4760 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4761 Category; Category = Category->getNextClassCategory())
4762 CollectOverriddenMethods(Category, Method, Methods);
4763
4764 // We only look into the superclass if we haven't found anything yet.
4765 if (Methods.empty())
4766 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4767 return CollectOverriddenMethods(Super, Method, Methods);
4768 }
4769}
4770
4771void clang_getOverriddenCursors(CXCursor cursor,
4772 CXCursor **overridden,
4773 unsigned *num_overridden) {
4774 if (overridden)
4775 *overridden = 0;
4776 if (num_overridden)
4777 *num_overridden = 0;
4778 if (!overridden || !num_overridden)
4779 return;
4780
4781 if (!clang_isDeclaration(cursor.kind))
4782 return;
4783
4784 Decl *D = getCursorDecl(cursor);
4785 if (!D)
4786 return;
4787
4788 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004789 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004790 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4791 *num_overridden = CXXMethod->size_overridden_methods();
4792 if (!*num_overridden)
4793 return;
4794
4795 *overridden = new CXCursor [*num_overridden];
4796 unsigned I = 0;
4797 for (CXXMethodDecl::method_iterator
4798 M = CXXMethod->begin_overridden_methods(),
4799 MEnd = CXXMethod->end_overridden_methods();
4800 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004801 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004802 return;
4803 }
4804
4805 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4806 if (!Method)
4807 return;
4808
4809 // Handle Objective-C methods.
4810 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4811 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4812
4813 if (Methods.empty())
4814 return;
4815
4816 *num_overridden = Methods.size();
4817 *overridden = new CXCursor [Methods.size()];
4818 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004819 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00004820}
4821
4822void clang_disposeOverriddenCursors(CXCursor *overridden) {
4823 delete [] overridden;
4824}
4825
Douglas Gregorecdcb882010-10-20 22:00:55 +00004826CXFile clang_getIncludedFile(CXCursor cursor) {
4827 if (cursor.kind != CXCursor_InclusionDirective)
4828 return 0;
4829
4830 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4831 return (void *)ID->getFile();
4832}
4833
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004834} // end: extern "C"
4835
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004836
4837//===----------------------------------------------------------------------===//
4838// C++ AST instrospection.
4839//===----------------------------------------------------------------------===//
4840
4841extern "C" {
4842unsigned clang_CXXMethod_isStatic(CXCursor C) {
4843 if (!clang_isDeclaration(C.kind))
4844 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004845
4846 CXXMethodDecl *Method = 0;
4847 Decl *D = cxcursor::getCursorDecl(C);
4848 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4849 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4850 else
4851 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4852 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004853}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004854
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004855} // end: extern "C"
4856
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004857//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004858// Attribute introspection.
4859//===----------------------------------------------------------------------===//
4860
4861extern "C" {
4862CXType clang_getIBOutletCollectionType(CXCursor C) {
4863 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00004864 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004865
4866 IBOutletCollectionAttr *A =
4867 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4868
Ted Kremeneka60ed472010-11-16 08:15:36 +00004869 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00004870}
4871} // end: extern "C"
4872
4873//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00004874// Misc. utility functions.
4875//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004876
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004877/// Default to using an 8 MB stack size on "safety" threads.
4878static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004879
4880namespace clang {
4881
4882bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004883 void (*Fn)(void*), void *UserData,
4884 unsigned Size) {
4885 if (!Size)
4886 Size = GetSafetyThreadStackSize();
4887 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004888 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4889 return CRC.RunSafely(Fn, UserData);
4890}
4891
4892unsigned GetSafetyThreadStackSize() {
4893 return SafetyStackThreadSize;
4894}
4895
4896void SetSafetyThreadStackSize(unsigned Value) {
4897 SafetyStackThreadSize = Value;
4898}
4899
4900}
4901
Ted Kremenek04bb7162010-01-22 22:44:15 +00004902extern "C" {
4903
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004904CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004905 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004906}
4907
4908} // end: extern "C"