blob: 8d5c701d4772487050165058c7f81edc3c358aa0 [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"
Douglas Gregorf5251602011-03-08 17:10:18 +000037#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000038#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000039#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000040#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000041#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000043#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000048#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000049
Steve Naroff50398192009-08-28 15:28:48 +000050using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000051using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000052using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000053
Ted Kremeneka60ed472010-11-16 08:15:36 +000054static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
55 if (!TU)
56 return 0;
57 CXTranslationUnit D = new CXTranslationUnitImpl();
58 D->TUData = TU;
59 D->StringPool = createCXStringPool();
60 return D;
61}
62
Douglas Gregor33e9abd2010-01-22 19:49:59 +000063/// \brief The result of comparing two source ranges.
64enum RangeComparisonResult {
65 /// \brief Either the ranges overlap or one of the ranges is invalid.
66 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067
Douglas Gregor33e9abd2010-01-22 19:49:59 +000068 /// \brief The first range ends before the second range starts.
69 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000070
Douglas Gregor33e9abd2010-01-22 19:49:59 +000071 /// \brief The first range starts after the second range ends.
72 RangeAfter
73};
74
Ted Kremenekf0e23e82010-02-17 00:41:40 +000075/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000076/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000077static RangeComparisonResult RangeCompare(SourceManager &SM,
78 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000079 SourceRange R2) {
80 assert(R1.isValid() && "First range is invalid?");
81 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000082 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000083 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000084 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000085 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000086 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000087 return RangeAfter;
88 return RangeOverlap;
89}
90
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000091/// \brief Determine if a source location falls within, before, or after a
92/// a given source range.
93static RangeComparisonResult LocationCompare(SourceManager &SM,
94 SourceLocation L, SourceRange R) {
95 assert(R.isValid() && "First range is invalid?");
96 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000097 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000098 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000099 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
100 return RangeBefore;
101 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
102 return RangeAfter;
103 return RangeOverlap;
104}
105
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000106/// \brief Translate a Clang source range into a CIndex source range.
107///
108/// Clang internally represents ranges where the end location points to the
109/// start of the token at the end. However, for external clients it is more
110/// useful to have a CXSourceRange be a proper half-open interval. This routine
111/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000112CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000113 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000114 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000115 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000116 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000117 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000118 if (EndLoc.isValid() && EndLoc.isMacroID())
119 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000120 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000121 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000122 EndLoc = EndLoc.getFileLocWithOffset(Length);
123 }
124
125 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
126 R.getBegin().getRawEncoding(),
127 EndLoc.getRawEncoding() };
128 return Result;
129}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000130
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000131//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000133//===----------------------------------------------------------------------===//
134
Steve Naroff89922f82009-08-31 00:59:03 +0000135namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000136
137class VisitorJob {
138public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000139 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000140 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000141 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000142 ExplicitTemplateArgsVisitKind,
143 NestedNameSpecifierVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000144 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000145 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000146 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000148 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000149 CXCursor parent;
150 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000151 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
152 : parent(C), K(k) {
153 data[0] = d1;
154 data[1] = d2;
155 data[2] = d3;
156 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000157public:
158 Kind getKind() const { return K; }
159 const CXCursor &getParent() const { return parent; }
160 static bool classof(VisitorJob *VJ) { return true; }
161};
162
163typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
164
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000167 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000168{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000169 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000170 CXTranslationUnit TU;
171 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176 /// \brief The declaration that serves at the parent of any statement or
177 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000178 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000183 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000186 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
187 // to the visitor. Declarations with a PCH level greater than this value will
188 // be suppressed.
189 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000191 /// \brief Whether we should visit the preprocessing record entries last,
192 /// after visiting other declarations.
193 bool VisitPreprocessorLast;
194
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195 /// \brief When valid, a source range to which the cursor should restrict
196 /// its search.
197 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000198
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000199 // FIXME: Eventually remove. This part of a hack to support proper
200 // iteration over all Decls contained lexically within an ObjC container.
201 DeclContext::decl_iterator *DI_current;
202 DeclContext::decl_iterator DE_current;
203
Ted Kremenekd1ded662010-11-15 23:31:32 +0000204 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
205 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList;
206 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache;
207
Douglas Gregorb1373d02010-01-20 20:59:29 +0000208 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000209 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
211 /// \brief Determine whether this particular source range comes before, comes
212 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000214 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
216
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000217 class SetParentRAII {
218 CXCursor &Parent;
219 Decl *&StmtParent;
220 CXCursor OldParent;
221
222 public:
223 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
224 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
225 {
226 Parent = NewParent;
227 if (clang_isDeclaration(Parent.kind))
228 StmtParent = getCursorDecl(Parent);
229 }
230
231 ~SetParentRAII() {
232 Parent = OldParent;
233 if (clang_isDeclaration(Parent.kind))
234 StmtParent = getCursorDecl(Parent);
235 }
236 };
237
Steve Naroff89922f82009-08-31 00:59:03 +0000238public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000239 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
240 CXClientData ClientData,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000241 unsigned MaxPCHLevel,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000242 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000243 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000244 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
245 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000246 MaxPCHLevel(MaxPCHLevel), VisitPreprocessorLast(VisitPreprocessorLast),
247 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 {
249 Parent.kind = CXCursor_NoDeclFound;
250 Parent.data[0] = 0;
251 Parent.data[1] = 0;
252 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000253 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000254 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000255
Ted Kremenekd1ded662010-11-15 23:31:32 +0000256 ~CursorVisitor() {
257 // Free the pre-allocated worklists for data-recursion.
258 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator
259 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
260 delete *I;
261 }
262 }
263
Ted Kremeneka60ed472010-11-16 08:15:36 +0000264 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
265 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000266
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000267 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000268
269 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
270 getPreprocessedEntities();
271
Douglas Gregorb1373d02010-01-20 20:59:29 +0000272 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000273
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000274 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000275 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000276 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000277 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000278 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000279 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000280 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
281 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000282 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000283 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000284 bool VisitClassTemplatePartialSpecializationDecl(
285 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000286 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000287 bool VisitEnumConstantDecl(EnumConstantDecl *D);
288 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
289 bool VisitFunctionDecl(FunctionDecl *ND);
290 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000291 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000292 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000293 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000294 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000295 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000296 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
297 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
298 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
299 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000300 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000301 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
302 bool VisitObjCImplDecl(ObjCImplDecl *D);
303 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
304 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000305 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
306 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
307 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000308 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000309 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000310 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000311 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000312 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000313 bool VisitUsingDecl(UsingDecl *D);
314 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
315 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000316
Douglas Gregor01829d32010-08-31 14:41:23 +0000317 // Name visitor
318 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000319 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000320 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000321
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000322 // Template visitors
323 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000324 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000325 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
326
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000327 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000328 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000329 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000330 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
332 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000333 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000334 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000335 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000337 bool VisitParenTypeLoc(ParenTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitPointerTypeLoc(PointerTypeLoc TL);
339 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
340 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
341 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
342 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000343 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000344 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000345 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000346 // FIXME: Implement visitors here when the unimplemented TypeLocs get
347 // implemented
348 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
Douglas Gregor7536dd52010-12-20 02:24:11 +0000349 bool VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000350 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000351 bool VisitDependentNameTypeLoc(DependentNameTypeLoc TL);
Douglas Gregor94fdffa2011-03-01 20:11:18 +0000352 bool VisitDependentTemplateSpecializationTypeLoc(
353 DependentTemplateSpecializationTypeLoc TL);
Douglas Gregor9e876872011-03-01 18:12:44 +0000354 bool VisitElaboratedTypeLoc(ElaboratedTypeLoc TL);
Douglas Gregor2494dd02011-03-01 01:34:45 +0000355
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000356 // Data-recursive visitor functions.
357 bool IsInRegionOfInterest(CXCursor C);
358 bool RunVisitorWorkList(VisitorWorkList &WL);
359 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000360 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000361};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000362
Ted Kremenekab188932010-01-05 19:32:54 +0000363} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000364
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000365static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000366static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
367
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000368
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000369RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000370 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371}
372
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373/// \brief Visit the given cursor and, if requested by the visitor,
374/// its children.
375///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000376/// \param Cursor the cursor to visit.
377///
378/// \param CheckRegionOfInterest if true, then the caller already checked that
379/// this cursor is within the region of interest.
380///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381/// \returns true if the visitation should be aborted, false if it
382/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000383bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000384 if (clang_isInvalid(Cursor.kind))
385 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000386
Douglas Gregorb1373d02010-01-20 20:59:29 +0000387 if (clang_isDeclaration(Cursor.kind)) {
388 Decl *D = getCursorDecl(Cursor);
389 assert(D && "Invalid declaration cursor");
390 if (D->getPCHLevel() > MaxPCHLevel)
391 return false;
392
393 if (D->isImplicit())
394 return false;
395 }
396
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000397 // If we have a range of interest, and this cursor doesn't intersect with it,
398 // we're done.
399 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000400 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000401 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000402 return false;
403 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000404
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405 switch (Visitor(Cursor, Parent, ClientData)) {
406 case CXChildVisit_Break:
407 return true;
408
409 case CXChildVisit_Continue:
410 return false;
411
412 case CXChildVisit_Recurse:
413 return VisitChildren(Cursor);
414 }
415
Douglas Gregorfd643772010-01-25 16:45:46 +0000416 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000417}
418
Douglas Gregor788f5a12010-03-20 00:41:21 +0000419std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
420CursorVisitor::getPreprocessedEntities() {
421 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000422 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000423
424 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000425 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
426
427 if (OnlyLocalDecls && RegionOfInterest.isValid()) {
428 // If we would only look at local declarations but we have a region of
429 // interest, check whether that region of interest is in the main file.
430 // If not, we should traverse all declarations.
431 // FIXME: My kingdom for a proper binary search approach to finding
432 // cursors!
433 std::pair<FileID, unsigned> Location
434 = AU->getSourceManager().getDecomposedInstantiationLoc(
435 RegionOfInterest.getBegin());
436 if (Location.first != AU->getSourceManager().getMainFileID())
437 OnlyLocalDecls = false;
438 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000439
Douglas Gregor89d99802010-11-30 06:16:57 +0000440 PreprocessingRecord::iterator StartEntity, EndEntity;
441 if (OnlyLocalDecls) {
442 StartEntity = AU->pp_entity_begin();
443 EndEntity = AU->pp_entity_end();
444 } else {
445 StartEntity = PPRec.begin();
446 EndEntity = PPRec.end();
447 }
448
Douglas Gregor788f5a12010-03-20 00:41:21 +0000449 // There is no region of interest; we have to walk everything.
450 if (RegionOfInterest.isInvalid())
Douglas Gregor89d99802010-11-30 06:16:57 +0000451 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000452
453 // Find the file in which the region of interest lands.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000454 SourceManager &SM = AU->getSourceManager();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000455 std::pair<FileID, unsigned> Begin
456 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
457 std::pair<FileID, unsigned> End
458 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
459
460 // The region of interest spans files; we have to walk everything.
461 if (Begin.first != End.first)
Douglas Gregor89d99802010-11-30 06:16:57 +0000462 return std::make_pair(StartEntity, EndEntity);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000463
464 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
Ted Kremeneka60ed472010-11-16 08:15:36 +0000465 = AU->getPreprocessedEntitiesByFile();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000466 if (ByFileMap.empty()) {
467 // Build the mapping from files to sets of preprocessed entities.
Douglas Gregor89d99802010-11-30 06:16:57 +0000468 for (PreprocessingRecord::iterator E = StartEntity; E != EndEntity; ++E) {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000469 std::pair<FileID, unsigned> P
470 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
Douglas Gregor89d99802010-11-30 06:16:57 +0000471
Douglas Gregor788f5a12010-03-20 00:41:21 +0000472 ByFileMap[P.first].push_back(*E);
473 }
474 }
475
476 return std::make_pair(ByFileMap[Begin.first].begin(),
477 ByFileMap[Begin.first].end());
478}
479
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000481///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482/// \returns true if the visitation should be aborted, false if it
483/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000484bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000485 if (clang_isReference(Cursor.kind) &&
486 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000487 // By definition, references have no children.
488 return false;
489 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000490
491 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000492 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000493 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000494
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 if (clang_isDeclaration(Cursor.kind)) {
496 Decl *D = getCursorDecl(Cursor);
497 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000498 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000499 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500
Douglas Gregora59e3902010-01-21 23:27:09 +0000501 if (clang_isStatement(Cursor.kind))
502 return Visit(getCursorStmt(Cursor));
503 if (clang_isExpression(Cursor.kind))
504 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000505
Douglas Gregorb1373d02010-01-20 20:59:29 +0000506 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000507 CXTranslationUnit tu = getCursorTU(Cursor);
508 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000509
510 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
511 for (unsigned I = 0; I != 2; ++I) {
512 if (VisitOrder[I]) {
513 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
514 RegionOfInterest.isInvalid()) {
515 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
516 TLEnd = CXXUnit->top_level_end();
517 TL != TLEnd; ++TL) {
518 if (Visit(MakeCXCursor(*TL, tu), true))
519 return true;
520 }
521 } else if (VisitDeclContext(
522 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000523 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000524 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000525 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000526
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000527 // Walk the preprocessing record.
528 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
529 // FIXME: Once we have the ability to deserialize a preprocessing record,
530 // do so.
531 PreprocessingRecord::iterator E, EEnd;
532 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
533 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
534 if (Visit(MakeMacroInstantiationCursor(MI, tu)))
535 return true;
536
537 continue;
538 }
Douglas Gregor788f5a12010-03-20 00:41:21 +0000539
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000540 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
541 if (Visit(MakeMacroDefinitionCursor(MD, tu)))
542 return true;
543
544 continue;
545 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000546
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000547 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
548 if (Visit(MakeInclusionDirectiveCursor(ID, tu)))
549 return true;
550
551 continue;
552 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000553 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000554 }
555 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000556
Douglas Gregor7b691f332010-01-20 21:13:59 +0000557 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000559
Douglas Gregorc314aa42011-03-02 19:17:03 +0000560 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
561 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
562 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
563 return Visit(BaseTSInfo->getTypeLoc());
564 }
565 }
566 }
567
Douglas Gregorb1373d02010-01-20 20:59:29 +0000568 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000569 return false;
570}
571
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000572bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000573 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
574 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000575
Ted Kremenek664cffd2010-07-22 11:30:19 +0000576 if (Stmt *Body = B->getBody())
577 return Visit(MakeCXCursor(Body, StmtParent, TU));
578
579 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000580}
581
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000582llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
583 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000584 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000585 if (Range.isInvalid())
586 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000587
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000588 switch (CompareRegionOfInterest(Range)) {
589 case RangeBefore:
590 // This declaration comes before the region of interest; skip it.
591 return llvm::Optional<bool>();
592
593 case RangeAfter:
594 // This declaration comes after the region of interest; we're done.
595 return false;
596
597 case RangeOverlap:
598 // This declaration overlaps the region of interest; visit it.
599 break;
600 }
601 }
602 return true;
603}
604
605bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
606 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
607
608 // FIXME: Eventually remove. This part of a hack to support proper
609 // iteration over all Decls contained lexically within an ObjC container.
610 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
611 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
612
613 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000614 Decl *D = *I;
615 if (D->getLexicalDeclContext() != DC)
616 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000617 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000618 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
619 if (!V.hasValue())
620 continue;
621 if (!V.getValue())
622 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000623 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000624 return true;
625 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000626 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000627}
628
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000629bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
630 llvm_unreachable("Translation units are visited directly by Visit()");
631 return false;
632}
633
634bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
635 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
636 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000637
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000638 return false;
639}
640
641bool CursorVisitor::VisitTagDecl(TagDecl *D) {
642 return VisitDeclContext(D);
643}
644
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000645bool CursorVisitor::VisitClassTemplateSpecializationDecl(
646 ClassTemplateSpecializationDecl *D) {
647 bool ShouldVisitBody = false;
648 switch (D->getSpecializationKind()) {
649 case TSK_Undeclared:
650 case TSK_ImplicitInstantiation:
651 // Nothing to visit
652 return false;
653
654 case TSK_ExplicitInstantiationDeclaration:
655 case TSK_ExplicitInstantiationDefinition:
656 break;
657
658 case TSK_ExplicitSpecialization:
659 ShouldVisitBody = true;
660 break;
661 }
662
663 // Visit the template arguments used in the specialization.
664 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
665 TypeLoc TL = SpecType->getTypeLoc();
666 if (TemplateSpecializationTypeLoc *TSTLoc
667 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
668 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
669 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
670 return true;
671 }
672 }
673
674 if (ShouldVisitBody && VisitCXXRecordDecl(D))
675 return true;
676
677 return false;
678}
679
Douglas Gregor74dbe642010-08-31 19:31:58 +0000680bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
681 ClassTemplatePartialSpecializationDecl *D) {
682 // FIXME: Visit the "outer" template parameter lists on the TagDecl
683 // before visiting these template parameters.
684 if (VisitTemplateParameters(D->getTemplateParameters()))
685 return true;
686
687 // Visit the partial specialization arguments.
688 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
689 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
690 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
691 return true;
692
693 return VisitCXXRecordDecl(D);
694}
695
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000696bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000697 // Visit the default argument.
698 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
699 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
700 if (Visit(DefArg->getTypeLoc()))
701 return true;
702
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000703 return false;
704}
705
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000706bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
707 if (Expr *Init = D->getInitExpr())
708 return Visit(MakeCXCursor(Init, StmtParent, TU));
709 return false;
710}
711
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000712bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
713 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
714 if (Visit(TSInfo->getTypeLoc()))
715 return true;
716
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000717 // Visit the nested-name-specifier, if present.
718 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
719 if (VisitNestedNameSpecifierLoc(QualifierLoc))
720 return true;
721
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000722 return false;
723}
724
Douglas Gregora67e03f2010-09-09 21:42:20 +0000725/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000726static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
727 CXXCtorInitializer const * const *X
728 = static_cast<CXXCtorInitializer const * const *>(Xp);
729 CXXCtorInitializer const * const *Y
730 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000731
732 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
733 return -1;
734 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
735 return 1;
736 else
737 return 0;
738}
739
Douglas Gregorb1373d02010-01-20 20:59:29 +0000740bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000741 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
742 // Visit the function declaration's syntactic components in the order
743 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000744 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000745 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
746
747 // If we have a function declared directly (without the use of a typedef),
748 // visit just the return type. Otherwise, just visit the function's type
749 // now.
750 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
751 (!FTL && Visit(TL)))
752 return true;
753
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000754 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000755 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
756 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000757 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000758
759 // Visit the declaration name.
760 if (VisitDeclarationNameInfo(ND->getNameInfo()))
761 return true;
762
763 // FIXME: Visit explicitly-specified template arguments!
764
765 // Visit the function parameters, if we have a function type.
766 if (FTL && VisitFunctionTypeLoc(*FTL, true))
767 return true;
768
769 // FIXME: Attributes?
770 }
771
Douglas Gregora67e03f2010-09-09 21:42:20 +0000772 if (ND->isThisDeclarationADefinition()) {
773 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
774 // Find the initializers that were written in the source.
Sean Huntcbb67482011-01-08 20:30:50 +0000775 llvm::SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000776 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
777 IEnd = Constructor->init_end();
778 I != IEnd; ++I) {
779 if (!(*I)->isWritten())
780 continue;
781
782 WrittenInits.push_back(*I);
783 }
784
785 // Sort the initializers in source order
786 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000787 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000788
789 // Visit the initializers in source order
790 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000791 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000792 if (Init->isAnyMemberInitializer()) {
793 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000794 Init->getMemberLocation(), TU)))
795 return true;
796 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
797 if (Visit(BaseInfo->getTypeLoc()))
798 return true;
799 }
800
801 // Visit the initializer value.
802 if (Expr *Initializer = Init->getInit())
803 if (Visit(MakeCXCursor(Initializer, ND, TU)))
804 return true;
805 }
806 }
807
808 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
809 return true;
810 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000811
Douglas Gregorb1373d02010-01-20 20:59:29 +0000812 return false;
813}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
816 if (VisitDeclaratorDecl(D))
817 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000818
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000819 if (Expr *BitWidth = D->getBitWidth())
820 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000821
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000822 return false;
823}
824
825bool CursorVisitor::VisitVarDecl(VarDecl *D) {
826 if (VisitDeclaratorDecl(D))
827 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000828
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000829 if (Expr *Init = D->getInit())
830 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832 return false;
833}
834
Douglas Gregor84b51d72010-09-01 20:16:53 +0000835bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
836 if (VisitDeclaratorDecl(D))
837 return true;
838
839 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
840 if (Expr *DefArg = D->getDefaultArgument())
841 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
842
843 return false;
844}
845
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000846bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
847 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
848 // before visiting these template parameters.
849 if (VisitTemplateParameters(D->getTemplateParameters()))
850 return true;
851
852 return VisitFunctionDecl(D->getTemplatedDecl());
853}
854
Douglas Gregor39d6f072010-08-31 19:02:00 +0000855bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
856 // FIXME: Visit the "outer" template parameter lists on the TagDecl
857 // before visiting these template parameters.
858 if (VisitTemplateParameters(D->getTemplateParameters()))
859 return true;
860
861 return VisitCXXRecordDecl(D->getTemplatedDecl());
862}
863
Douglas Gregor84b51d72010-09-01 20:16:53 +0000864bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
865 if (VisitTemplateParameters(D->getTemplateParameters()))
866 return true;
867
868 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
869 VisitTemplateArgumentLoc(D->getDefaultArgument()))
870 return true;
871
872 return false;
873}
874
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000875bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000876 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
877 if (Visit(TSInfo->getTypeLoc()))
878 return true;
879
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000880 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000881 PEnd = ND->param_end();
882 P != PEnd; ++P) {
883 if (Visit(MakeCXCursor(*P, TU)))
884 return true;
885 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000886
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000887 if (ND->isThisDeclarationADefinition() &&
888 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
889 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000890
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000891 return false;
892}
893
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000894namespace {
895 struct ContainerDeclsSort {
896 SourceManager &SM;
897 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
898 bool operator()(Decl *A, Decl *B) {
899 SourceLocation L_A = A->getLocStart();
900 SourceLocation L_B = B->getLocStart();
901 assert(L_A.isValid() && L_B.isValid());
902 return SM.isBeforeInTranslationUnit(L_A, L_B);
903 }
904 };
905}
906
Douglas Gregora59e3902010-01-21 23:27:09 +0000907bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000908 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
909 // an @implementation can lexically contain Decls that are not properly
910 // nested in the AST. When we identify such cases, we need to retrofit
911 // this nesting here.
912 if (!DI_current)
913 return VisitDeclContext(D);
914
915 // Scan the Decls that immediately come after the container
916 // in the current DeclContext. If any fall within the
917 // container's lexical region, stash them into a vector
918 // for later processing.
919 llvm::SmallVector<Decl *, 24> DeclsInContainer;
920 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000921 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000922 if (EndLoc.isValid()) {
923 DeclContext::decl_iterator next = *DI_current;
924 while (++next != DE_current) {
925 Decl *D_next = *next;
926 if (!D_next)
927 break;
928 SourceLocation L = D_next->getLocStart();
929 if (!L.isValid())
930 break;
931 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
932 *DI_current = next;
933 DeclsInContainer.push_back(D_next);
934 continue;
935 }
936 break;
937 }
938 }
939
940 // The common case.
941 if (DeclsInContainer.empty())
942 return VisitDeclContext(D);
943
944 // Get all the Decls in the DeclContext, and sort them with the
945 // additional ones we've collected. Then visit them.
946 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
947 I!=E; ++I) {
948 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000949 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
950 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000951 continue;
952 DeclsInContainer.push_back(subDecl);
953 }
954
955 // Now sort the Decls so that they appear in lexical order.
956 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
957 ContainerDeclsSort(SM));
958
959 // Now visit the decls.
960 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
961 E = DeclsInContainer.end(); I != E; ++I) {
962 CXCursor Cursor = MakeCXCursor(*I, TU);
963 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
964 if (!V.hasValue())
965 continue;
966 if (!V.getValue())
967 return false;
968 if (Visit(Cursor, true))
969 return true;
970 }
971 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000972}
973
Douglas Gregorb1373d02010-01-20 20:59:29 +0000974bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000975 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
976 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000977 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000978
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000979 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
980 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
981 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000982 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000983 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000984
Douglas Gregora59e3902010-01-21 23:27:09 +0000985 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000986}
987
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000988bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
989 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
990 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
991 E = PID->protocol_end(); I != E; ++I, ++PL)
992 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
993 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000995 return VisitObjCContainerDecl(PID);
996}
997
Ted Kremenek23173d72010-05-18 21:09:07 +0000998bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000999 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +00001000 return true;
1001
Ted Kremenek23173d72010-05-18 21:09:07 +00001002 // FIXME: This implements a workaround with @property declarations also being
1003 // installed in the DeclContext for the @interface. Eventually this code
1004 // should be removed.
1005 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1006 if (!CDecl || !CDecl->IsClassExtension())
1007 return false;
1008
1009 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1010 if (!ID)
1011 return false;
1012
1013 IdentifierInfo *PropertyId = PD->getIdentifier();
1014 ObjCPropertyDecl *prevDecl =
1015 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1016
1017 if (!prevDecl)
1018 return false;
1019
1020 // Visit synthesized methods since they will be skipped when visiting
1021 // the @interface.
1022 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001023 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001024 if (Visit(MakeCXCursor(MD, TU)))
1025 return true;
1026
1027 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001028 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001029 if (Visit(MakeCXCursor(MD, TU)))
1030 return true;
1031
1032 return false;
1033}
1034
Douglas Gregorb1373d02010-01-20 20:59:29 +00001035bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001036 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001037 if (D->getSuperClass() &&
1038 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001040 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001041 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001043 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1044 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1045 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001046 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001047 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048
Douglas Gregora59e3902010-01-21 23:27:09 +00001049 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001050}
1051
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001052bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1053 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001054}
1055
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001056bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001057 // 'ID' could be null when dealing with invalid code.
1058 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1059 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1060 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062 return VisitObjCImplDecl(D);
1063}
1064
1065bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1066#if 0
1067 // Issue callbacks for super class.
1068 // FIXME: No source location information!
1069 if (D->getSuperClass() &&
1070 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001071 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001072 TU)))
1073 return true;
1074#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001075
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001076 return VisitObjCImplDecl(D);
1077}
1078
1079bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1080 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1081 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1082 E = D->protocol_end();
1083 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001084 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001085 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001086
1087 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001088}
1089
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001090bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1091 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1092 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1093 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001094
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001095 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001096}
1097
Douglas Gregora4ffd852010-11-17 01:03:52 +00001098bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1099 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1100 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1101
1102 return false;
1103}
1104
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001105bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1106 return VisitDeclContext(D);
1107}
1108
Douglas Gregor69319002010-08-31 23:48:11 +00001109bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001111 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1112 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001113 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001114
1115 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1116 D->getTargetNameLoc(), TU));
1117}
1118
Douglas Gregor7e242562010-09-01 19:52:22 +00001119bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001121 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1122 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001123 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001124 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001125
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001126 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1127 return true;
1128
Douglas Gregor7e242562010-09-01 19:52:22 +00001129 return VisitDeclarationNameInfo(D->getNameInfo());
1130}
1131
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001132bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001133 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001134 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1135 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001136 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001137
1138 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1139 D->getIdentLocation(), TU));
1140}
1141
Douglas Gregor7e242562010-09-01 19:52:22 +00001142bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001143 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001144 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1145 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001146 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001147 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001148
Douglas Gregor7e242562010-09-01 19:52:22 +00001149 return VisitDeclarationNameInfo(D->getNameInfo());
1150}
1151
1152bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1153 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001154 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001155 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1156 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001157 return true;
1158
Douglas Gregor7e242562010-09-01 19:52:22 +00001159 return false;
1160}
1161
Douglas Gregor01829d32010-08-31 14:41:23 +00001162bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1163 switch (Name.getName().getNameKind()) {
1164 case clang::DeclarationName::Identifier:
1165 case clang::DeclarationName::CXXLiteralOperatorName:
1166 case clang::DeclarationName::CXXOperatorName:
1167 case clang::DeclarationName::CXXUsingDirective:
1168 return false;
1169
1170 case clang::DeclarationName::CXXConstructorName:
1171 case clang::DeclarationName::CXXDestructorName:
1172 case clang::DeclarationName::CXXConversionFunctionName:
1173 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1174 return Visit(TSInfo->getTypeLoc());
1175 return false;
1176
1177 case clang::DeclarationName::ObjCZeroArgSelector:
1178 case clang::DeclarationName::ObjCOneArgSelector:
1179 case clang::DeclarationName::ObjCMultiArgSelector:
1180 // FIXME: Per-identifier location info?
1181 return false;
1182 }
1183
1184 return false;
1185}
1186
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001187bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1188 SourceRange Range) {
1189 // FIXME: This whole routine is a hack to work around the lack of proper
1190 // source information in nested-name-specifiers (PR5791). Since we do have
1191 // a beginning source location, we can visit the first component of the
1192 // nested-name-specifier, if it's a single-token component.
1193 if (!NNS)
1194 return false;
1195
1196 // Get the first component in the nested-name-specifier.
1197 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1198 NNS = Prefix;
1199
1200 switch (NNS->getKind()) {
1201 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001202 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1203 TU));
1204
Douglas Gregor14aba762011-02-24 02:36:08 +00001205 case NestedNameSpecifier::NamespaceAlias:
1206 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1207 Range.getBegin(), TU));
1208
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001209 case NestedNameSpecifier::TypeSpec: {
1210 // If the type has a form where we know that the beginning of the source
1211 // range matches up with a reference cursor. Visit the appropriate reference
1212 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001213 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001214 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1215 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1216 if (const TagType *Tag = dyn_cast<TagType>(T))
1217 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1218 if (const TemplateSpecializationType *TST
1219 = dyn_cast<TemplateSpecializationType>(T))
1220 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1221 break;
1222 }
1223
1224 case NestedNameSpecifier::TypeSpecWithTemplate:
1225 case NestedNameSpecifier::Global:
1226 case NestedNameSpecifier::Identifier:
1227 break;
1228 }
1229
1230 return false;
1231}
1232
Douglas Gregordc355712011-02-25 00:36:19 +00001233bool
1234CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1235 llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1236 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1237 Qualifiers.push_back(Qualifier);
1238
1239 while (!Qualifiers.empty()) {
1240 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1241 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1242 switch (NNS->getKind()) {
1243 case NestedNameSpecifier::Namespace:
1244 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001245 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001246 TU)))
1247 return true;
1248
1249 break;
1250
1251 case NestedNameSpecifier::NamespaceAlias:
1252 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001253 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001254 TU)))
1255 return true;
1256
1257 break;
1258
1259 case NestedNameSpecifier::TypeSpec:
1260 case NestedNameSpecifier::TypeSpecWithTemplate:
1261 if (Visit(Q.getTypeLoc()))
1262 return true;
1263
1264 break;
1265
1266 case NestedNameSpecifier::Global:
1267 case NestedNameSpecifier::Identifier:
1268 break;
1269 }
1270 }
1271
1272 return false;
1273}
1274
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001275bool CursorVisitor::VisitTemplateParameters(
1276 const TemplateParameterList *Params) {
1277 if (!Params)
1278 return false;
1279
1280 for (TemplateParameterList::const_iterator P = Params->begin(),
1281 PEnd = Params->end();
1282 P != PEnd; ++P) {
1283 if (Visit(MakeCXCursor(*P, TU)))
1284 return true;
1285 }
1286
1287 return false;
1288}
1289
Douglas Gregor0b36e612010-08-31 20:37:03 +00001290bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1291 switch (Name.getKind()) {
1292 case TemplateName::Template:
1293 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1294
1295 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001296 // Visit the overloaded template set.
1297 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1298 return true;
1299
Douglas Gregor0b36e612010-08-31 20:37:03 +00001300 return false;
1301
1302 case TemplateName::DependentTemplate:
1303 // FIXME: Visit nested-name-specifier.
1304 return false;
1305
1306 case TemplateName::QualifiedTemplate:
1307 // FIXME: Visit nested-name-specifier.
1308 return Visit(MakeCursorTemplateRef(
1309 Name.getAsQualifiedTemplateName()->getDecl(),
1310 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001311
1312 case TemplateName::SubstTemplateTemplateParmPack:
1313 return Visit(MakeCursorTemplateRef(
1314 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1315 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001316 }
1317
1318 return false;
1319}
1320
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001321bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1322 switch (TAL.getArgument().getKind()) {
1323 case TemplateArgument::Null:
1324 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001325 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001326 return false;
1327
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001328 case TemplateArgument::Type:
1329 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1330 return Visit(TSInfo->getTypeLoc());
1331 return false;
1332
1333 case TemplateArgument::Declaration:
1334 if (Expr *E = TAL.getSourceDeclExpression())
1335 return Visit(MakeCXCursor(E, StmtParent, TU));
1336 return false;
1337
1338 case TemplateArgument::Expression:
1339 if (Expr *E = TAL.getSourceExpression())
1340 return Visit(MakeCXCursor(E, StmtParent, TU));
1341 return false;
1342
1343 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001344 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001345 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1346 return true;
1347
Douglas Gregora7fc9012011-01-05 18:58:31 +00001348 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001349 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001350 }
1351
1352 return false;
1353}
1354
Ted Kremeneka0536d82010-05-07 01:04:29 +00001355bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1356 return VisitDeclContext(D);
1357}
1358
Douglas Gregor01829d32010-08-31 14:41:23 +00001359bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1360 return Visit(TL.getUnqualifiedLoc());
1361}
1362
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001363bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001364 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001365
1366 // Some builtin types (such as Objective-C's "id", "sel", and
1367 // "Class") have associated declarations. Create cursors for those.
1368 QualType VisitType;
1369 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001370 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001371 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001372 case BuiltinType::Char_U:
1373 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001374 case BuiltinType::Char16:
1375 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001376 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001377 case BuiltinType::UInt:
1378 case BuiltinType::ULong:
1379 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001380 case BuiltinType::UInt128:
1381 case BuiltinType::Char_S:
1382 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001383 case BuiltinType::WChar_U:
1384 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001385 case BuiltinType::Short:
1386 case BuiltinType::Int:
1387 case BuiltinType::Long:
1388 case BuiltinType::LongLong:
1389 case BuiltinType::Int128:
1390 case BuiltinType::Float:
1391 case BuiltinType::Double:
1392 case BuiltinType::LongDouble:
1393 case BuiltinType::NullPtr:
1394 case BuiltinType::Overload:
1395 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001396 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001397
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001398 case BuiltinType::ObjCId:
1399 VisitType = Context.getObjCIdType();
1400 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001401
1402 case BuiltinType::ObjCClass:
1403 VisitType = Context.getObjCClassType();
1404 break;
1405
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001406 case BuiltinType::ObjCSel:
1407 VisitType = Context.getObjCSelType();
1408 break;
1409 }
1410
1411 if (!VisitType.isNull()) {
1412 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001413 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001414 TU));
1415 }
1416
1417 return false;
1418}
1419
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001420bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1421 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1422}
1423
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001424bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1425 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1426}
1427
1428bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1429 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1430}
1431
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001432bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001433 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001434 // no context information with which we can match up the depth/index in the
1435 // type to the appropriate
1436 return false;
1437}
1438
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001439bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1440 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1441 return true;
1442
John McCallc12c5bb2010-05-15 11:32:37 +00001443 return false;
1444}
1445
1446bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1447 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1448 return true;
1449
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001450 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1451 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1452 TU)))
1453 return true;
1454 }
1455
1456 return false;
1457}
1458
1459bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001460 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001461}
1462
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001463bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1464 return Visit(TL.getInnerLoc());
1465}
1466
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001467bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1468 return Visit(TL.getPointeeLoc());
1469}
1470
1471bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1472 return Visit(TL.getPointeeLoc());
1473}
1474
1475bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1476 return Visit(TL.getPointeeLoc());
1477}
1478
1479bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001480 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001481}
1482
1483bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001484 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001485}
1486
Douglas Gregor01829d32010-08-31 14:41:23 +00001487bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1488 bool SkipResultType) {
1489 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001490 return true;
1491
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001492 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001493 if (Decl *D = TL.getArg(I))
1494 if (Visit(MakeCXCursor(D, TU)))
1495 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001496
1497 return false;
1498}
1499
1500bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1501 if (Visit(TL.getElementLoc()))
1502 return true;
1503
1504 if (Expr *Size = TL.getSizeExpr())
1505 return Visit(MakeCXCursor(Size, StmtParent, TU));
1506
1507 return false;
1508}
1509
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001510bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1511 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001512 // Visit the template name.
1513 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1514 TL.getTemplateNameLoc()))
1515 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001516
1517 // Visit the template arguments.
1518 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1519 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1520 return true;
1521
1522 return false;
1523}
1524
Douglas Gregor2332c112010-01-21 20:48:56 +00001525bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1526 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1527}
1528
1529bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1530 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1531 return Visit(TSInfo->getTypeLoc());
1532
1533 return false;
1534}
1535
Douglas Gregor2494dd02011-03-01 01:34:45 +00001536bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1537 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1538 return true;
1539
1540 return false;
1541}
1542
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001543bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1544 DependentTemplateSpecializationTypeLoc TL) {
1545 // Visit the nested-name-specifier, if there is one.
1546 if (TL.getQualifierLoc() &&
1547 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1548 return true;
1549
1550 // Visit the template arguments.
1551 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1552 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1553 return true;
1554
1555 return false;
1556}
1557
Douglas Gregor9e876872011-03-01 18:12:44 +00001558bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1559 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1560 return true;
1561
1562 return Visit(TL.getNamedTypeLoc());
1563}
1564
Douglas Gregor7536dd52010-12-20 02:24:11 +00001565bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1566 return Visit(TL.getPatternLoc());
1567}
1568
Ted Kremenek3064ef92010-08-27 21:34:58 +00001569bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001570 // Visit the nested-name-specifier, if present.
1571 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1572 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1573 return true;
1574
Ted Kremenek3064ef92010-08-27 21:34:58 +00001575 if (D->isDefinition()) {
1576 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1577 E = D->bases_end(); I != E; ++I) {
1578 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1579 return true;
1580 }
1581 }
1582
1583 return VisitTagDecl(D);
1584}
1585
Ted Kremenek09dfa372010-02-18 05:46:33 +00001586bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001587 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1588 i != e; ++i)
1589 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001590 return true;
1591
1592 return false;
1593}
1594
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001595//===----------------------------------------------------------------------===//
1596// Data-recursive visitor methods.
1597//===----------------------------------------------------------------------===//
1598
Ted Kremenek28a71942010-11-13 00:36:47 +00001599namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001600#define DEF_JOB(NAME, DATA, KIND)\
1601class NAME : public VisitorJob {\
1602public:\
1603 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1604 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001605 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001606};
1607
1608DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1609DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001610DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001611DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001612DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1613 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001614DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001615#undef DEF_JOB
1616
1617class DeclVisit : public VisitorJob {
1618public:
1619 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1620 VisitorJob(parent, VisitorJob::DeclVisitKind,
1621 d, isFirst ? (void*) 1 : (void*) 0) {}
1622 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001623 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001624 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001625 Decl *get() const { return static_cast<Decl*>(data[0]); }
1626 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001627};
Ted Kremenek035dc412010-11-13 00:36:50 +00001628class TypeLocVisit : public VisitorJob {
1629public:
1630 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1631 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1632 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1633
1634 static bool classof(const VisitorJob *VJ) {
1635 return VJ->getKind() == TypeLocVisitKind;
1636 }
1637
Ted Kremenek82f3c502010-11-15 22:23:26 +00001638 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001639 QualType T = QualType::getFromOpaquePtr(data[0]);
1640 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001641 }
1642};
1643
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001644class LabelRefVisit : public VisitorJob {
1645public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001646 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1647 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001648 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001649
1650 static bool classof(const VisitorJob *VJ) {
1651 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1652 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001653 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001654 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001655 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001656};
1657class NestedNameSpecifierVisit : public VisitorJob {
1658public:
1659 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R,
1660 CXCursor parent)
1661 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001662 NS, R.getBegin().getPtrEncoding(),
1663 R.getEnd().getPtrEncoding()) {}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001664 static bool classof(const VisitorJob *VJ) {
1665 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind;
1666 }
1667 NestedNameSpecifier *get() const {
1668 return static_cast<NestedNameSpecifier*>(data[0]);
1669 }
1670 SourceRange getSourceRange() const {
1671 SourceLocation A =
1672 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1673 SourceLocation B =
1674 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]);
1675 return SourceRange(A, B);
1676 }
1677};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001678
1679class NestedNameSpecifierLocVisit : public VisitorJob {
1680public:
1681 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1682 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1683 Qualifier.getNestedNameSpecifier(),
1684 Qualifier.getOpaqueData()) { }
1685
1686 static bool classof(const VisitorJob *VJ) {
1687 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1688 }
1689
1690 NestedNameSpecifierLoc get() const {
1691 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1692 data[1]);
1693 }
1694};
1695
Ted Kremenekf64d8032010-11-18 00:02:32 +00001696class DeclarationNameInfoVisit : public VisitorJob {
1697public:
1698 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1699 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1700 static bool classof(const VisitorJob *VJ) {
1701 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1702 }
1703 DeclarationNameInfo get() const {
1704 Stmt *S = static_cast<Stmt*>(data[0]);
1705 switch (S->getStmtClass()) {
1706 default:
1707 llvm_unreachable("Unhandled Stmt");
1708 case Stmt::CXXDependentScopeMemberExprClass:
1709 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1710 case Stmt::DependentScopeDeclRefExprClass:
1711 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1712 }
1713 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001714};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001715class MemberRefVisit : public VisitorJob {
1716public:
1717 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1718 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001719 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001720 static bool classof(const VisitorJob *VJ) {
1721 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1722 }
1723 FieldDecl *get() const {
1724 return static_cast<FieldDecl*>(data[0]);
1725 }
1726 SourceLocation getLoc() const {
1727 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1728 }
1729};
Ted Kremenek28a71942010-11-13 00:36:47 +00001730class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1731 VisitorWorkList &WL;
1732 CXCursor Parent;
1733public:
1734 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1735 : WL(wl), Parent(parent) {}
1736
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001737 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001738 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001739 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001740 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001741 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001742 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001743 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001744 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001745 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001746 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001747 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001748 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001749 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001750 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001751 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001752 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001753 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001754 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001755 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1756 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001757 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001758 void VisitIfStmt(IfStmt *If);
1759 void VisitInitListExpr(InitListExpr *IE);
1760 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001761 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001762 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001763 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1764 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001765 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001766 void VisitStmt(Stmt *S);
1767 void VisitSwitchStmt(SwitchStmt *S);
1768 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001769 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001770 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001771 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001772 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001773 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001774
Ted Kremenek28a71942010-11-13 00:36:47 +00001775private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001776 void AddDeclarationNameInfo(Stmt *S);
1777 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001778 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001779 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001780 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001781 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001782 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001783 void AddTypeLoc(TypeSourceInfo *TI);
1784 void EnqueueChildren(Stmt *S);
1785};
1786} // end anonyous namespace
1787
Ted Kremenekf64d8032010-11-18 00:02:32 +00001788void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1789 // 'S' should always be non-null, since it comes from the
1790 // statement we are visiting.
1791 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1792}
1793void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N,
1794 SourceRange R) {
1795 if (N)
1796 WL.push_back(NestedNameSpecifierVisit(N, R, Parent));
1797}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001798
1799void
1800EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1801 if (Qualifier)
1802 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1803}
1804
Ted Kremenek28a71942010-11-13 00:36:47 +00001805void EnqueueVisitor::AddStmt(Stmt *S) {
1806 if (S)
1807 WL.push_back(StmtVisit(S, Parent));
1808}
Ted Kremenek035dc412010-11-13 00:36:50 +00001809void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001810 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001811 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001812}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001813void EnqueueVisitor::
1814 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1815 if (A)
1816 WL.push_back(ExplicitTemplateArgsVisit(
1817 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1818}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001819void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1820 if (D)
1821 WL.push_back(MemberRefVisit(D, L, Parent));
1822}
Ted Kremenek28a71942010-11-13 00:36:47 +00001823void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1824 if (TI)
1825 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1826 }
1827void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001828 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001829 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001830 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001831 }
1832 if (size == WL.size())
1833 return;
1834 // Now reverse the entries we just added. This will match the DFS
1835 // ordering performed by the worklist.
1836 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1837 std::reverse(I, E);
1838}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001839void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1840 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1841}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001842void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1843 AddDecl(B->getBlockDecl());
1844}
Ted Kremenek28a71942010-11-13 00:36:47 +00001845void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1846 EnqueueChildren(E);
1847 AddTypeLoc(E->getTypeSourceInfo());
1848}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001849void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1850 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1851 E = S->body_rend(); I != E; ++I) {
1852 AddStmt(*I);
1853 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001854}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001855void EnqueueVisitor::
1856VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1857 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1858 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001859 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1860 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001861 if (!E->isImplicitAccess())
1862 AddStmt(E->getBase());
1863}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001864void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1865 // Enqueue the initializer or constructor arguments.
1866 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1867 AddStmt(E->getConstructorArg(I-1));
1868 // Enqueue the array size, if any.
1869 AddStmt(E->getArraySize());
1870 // Enqueue the allocated type.
1871 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1872 // Enqueue the placement arguments.
1873 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1874 AddStmt(E->getPlacementArg(I-1));
1875}
Ted Kremenek28a71942010-11-13 00:36:47 +00001876void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001877 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1878 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001879 AddStmt(CE->getCallee());
1880 AddStmt(CE->getArg(0));
1881}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001882void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1883 // Visit the name of the type being destroyed.
1884 AddTypeLoc(E->getDestroyedTypeInfo());
1885 // Visit the scope type that looks disturbingly like the nested-name-specifier
1886 // but isn't.
1887 AddTypeLoc(E->getScopeTypeInfo());
1888 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001889 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1890 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001891 // Visit base expression.
1892 AddStmt(E->getBase());
1893}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001894void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1895 AddTypeLoc(E->getTypeSourceInfo());
1896}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001897void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1898 EnqueueChildren(E);
1899 AddTypeLoc(E->getTypeSourceInfo());
1900}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001901void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1902 EnqueueChildren(E);
1903 if (E->isTypeOperand())
1904 AddTypeLoc(E->getTypeOperandSourceInfo());
1905}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001906
1907void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1908 *E) {
1909 EnqueueChildren(E);
1910 AddTypeLoc(E->getTypeSourceInfo());
1911}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001912void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1913 EnqueueChildren(E);
1914 if (E->isTypeOperand())
1915 AddTypeLoc(E->getTypeOperandSourceInfo());
1916}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001917void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001918 if (DR->hasExplicitTemplateArgs()) {
1919 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1920 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001921 WL.push_back(DeclRefExprParts(DR, Parent));
1922}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001923void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1924 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1925 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001926 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001927}
Ted Kremenek035dc412010-11-13 00:36:50 +00001928void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1929 unsigned size = WL.size();
1930 bool isFirst = true;
1931 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1932 D != DEnd; ++D) {
1933 AddDecl(*D, isFirst);
1934 isFirst = false;
1935 }
1936 if (size == WL.size())
1937 return;
1938 // Now reverse the entries we just added. This will match the DFS
1939 // ordering performed by the worklist.
1940 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1941 std::reverse(I, E);
1942}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001943void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1944 AddStmt(E->getInit());
1945 typedef DesignatedInitExpr::Designator Designator;
1946 for (DesignatedInitExpr::reverse_designators_iterator
1947 D = E->designators_rbegin(), DEnd = E->designators_rend();
1948 D != DEnd; ++D) {
1949 if (D->isFieldDesignator()) {
1950 if (FieldDecl *Field = D->getField())
1951 AddMemberRef(Field, D->getFieldLoc());
1952 continue;
1953 }
1954 if (D->isArrayDesignator()) {
1955 AddStmt(E->getArrayIndex(*D));
1956 continue;
1957 }
1958 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1959 AddStmt(E->getArrayRangeEnd(*D));
1960 AddStmt(E->getArrayRangeStart(*D));
1961 }
1962}
Ted Kremenek28a71942010-11-13 00:36:47 +00001963void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1964 EnqueueChildren(E);
1965 AddTypeLoc(E->getTypeInfoAsWritten());
1966}
1967void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1968 AddStmt(FS->getBody());
1969 AddStmt(FS->getInc());
1970 AddStmt(FS->getCond());
1971 AddDecl(FS->getConditionVariable());
1972 AddStmt(FS->getInit());
1973}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001974void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1975 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1976}
Ted Kremenek28a71942010-11-13 00:36:47 +00001977void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1978 AddStmt(If->getElse());
1979 AddStmt(If->getThen());
1980 AddStmt(If->getCond());
1981 AddDecl(If->getConditionVariable());
1982}
1983void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1984 // We care about the syntactic form of the initializer list, only.
1985 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1986 IE = Syntactic;
1987 EnqueueChildren(IE);
1988}
1989void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001990 WL.push_back(MemberExprParts(M, Parent));
1991
1992 // If the base of the member access expression is an implicit 'this', don't
1993 // visit it.
1994 // FIXME: If we ever want to show these implicit accesses, this will be
1995 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001996 if (!M->isImplicitAccess())
1997 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001998}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001999void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2000 AddTypeLoc(E->getEncodedTypeSourceInfo());
2001}
Ted Kremenek28a71942010-11-13 00:36:47 +00002002void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2003 EnqueueChildren(M);
2004 AddTypeLoc(M->getClassReceiverTypeInfo());
2005}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002006void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2007 // Visit the components of the offsetof expression.
2008 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2009 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2010 const OffsetOfNode &Node = E->getComponent(I-1);
2011 switch (Node.getKind()) {
2012 case OffsetOfNode::Array:
2013 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2014 break;
2015 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002016 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002017 break;
2018 case OffsetOfNode::Identifier:
2019 case OffsetOfNode::Base:
2020 continue;
2021 }
2022 }
2023 // Visit the type into which we're computing the offset.
2024 AddTypeLoc(E->getTypeSourceInfo());
2025}
Ted Kremenek28a71942010-11-13 00:36:47 +00002026void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002027 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002028 WL.push_back(OverloadExprParts(E, Parent));
2029}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002030void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2031 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002032 EnqueueChildren(E);
2033 if (E->isArgumentType())
2034 AddTypeLoc(E->getArgumentTypeInfo());
2035}
Ted Kremenek28a71942010-11-13 00:36:47 +00002036void EnqueueVisitor::VisitStmt(Stmt *S) {
2037 EnqueueChildren(S);
2038}
2039void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2040 AddStmt(S->getBody());
2041 AddStmt(S->getCond());
2042 AddDecl(S->getConditionVariable());
2043}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002044
Ted Kremenek28a71942010-11-13 00:36:47 +00002045void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2046 AddStmt(W->getBody());
2047 AddStmt(W->getCond());
2048 AddDecl(W->getConditionVariable());
2049}
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002050void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2051 AddTypeLoc(E->getQueriedTypeSourceInfo());
2052}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002053
2054void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002055 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002056 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002057}
2058
Ted Kremenek28a71942010-11-13 00:36:47 +00002059void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2060 VisitOverloadExpr(U);
2061 if (!U->isImplicitAccess())
2062 AddStmt(U->getBase());
2063}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002064void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2065 AddStmt(E->getSubExpr());
2066 AddTypeLoc(E->getWrittenTypeInfo());
2067}
Douglas Gregor94d96292011-01-19 20:34:17 +00002068void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2069 WL.push_back(SizeOfPackExprParts(E, Parent));
2070}
Ted Kremenek60458782010-11-12 21:34:16 +00002071
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002072void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002073 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002074}
2075
2076bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2077 if (RegionOfInterest.isValid()) {
2078 SourceRange Range = getRawCursorExtent(C);
2079 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2080 return false;
2081 }
2082 return true;
2083}
2084
2085bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2086 while (!WL.empty()) {
2087 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002088 VisitorJob LI = WL.back();
2089 WL.pop_back();
2090
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002091 // Set the Parent field, then back to its old value once we're done.
2092 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2093
2094 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002095 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002096 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002097 if (!D)
2098 continue;
2099
2100 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002101 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002102 return true;
2103
2104 continue;
2105 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002106 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2107 const ExplicitTemplateArgumentList *ArgList =
2108 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2109 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2110 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2111 Arg != ArgEnd; ++Arg) {
2112 if (VisitTemplateArgumentLoc(*Arg))
2113 return true;
2114 }
2115 continue;
2116 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002117 case VisitorJob::TypeLocVisitKind: {
2118 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002119 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002120 return true;
2121 continue;
2122 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002123 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002124 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002125 if (LabelStmt *stmt = LS->getStmt()) {
2126 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2127 TU))) {
2128 return true;
2129 }
2130 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002131 continue;
2132 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002133
Ted Kremenekf64d8032010-11-18 00:02:32 +00002134 case VisitorJob::NestedNameSpecifierVisitKind: {
2135 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI);
2136 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange()))
2137 return true;
2138 continue;
2139 }
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002140
2141 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2142 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2143 if (VisitNestedNameSpecifierLoc(V->get()))
2144 return true;
2145 continue;
2146 }
2147
Ted Kremenekf64d8032010-11-18 00:02:32 +00002148 case VisitorJob::DeclarationNameInfoVisitKind: {
2149 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2150 ->get()))
2151 return true;
2152 continue;
2153 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002154 case VisitorJob::MemberRefVisitKind: {
2155 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2156 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2157 return true;
2158 continue;
2159 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002160 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002161 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002162 if (!S)
2163 continue;
2164
Ted Kremenekf1107452010-11-12 18:26:56 +00002165 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002166 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002167 if (!IsInRegionOfInterest(Cursor))
2168 continue;
2169 switch (Visitor(Cursor, Parent, ClientData)) {
2170 case CXChildVisit_Break: return true;
2171 case CXChildVisit_Continue: break;
2172 case CXChildVisit_Recurse:
2173 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002174 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002175 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002176 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002177 }
2178 case VisitorJob::MemberExprPartsKind: {
2179 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002180 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002181
2182 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002183 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2184 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002185 return true;
2186
2187 // Visit the declaration name.
2188 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2189 return true;
2190
2191 // Visit the explicitly-specified template arguments, if any.
2192 if (M->hasExplicitTemplateArgs()) {
2193 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2194 *ArgEnd = Arg + M->getNumTemplateArgs();
2195 Arg != ArgEnd; ++Arg) {
2196 if (VisitTemplateArgumentLoc(*Arg))
2197 return true;
2198 }
2199 }
2200 continue;
2201 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002202 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002203 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002204 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002205 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2206 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002207 return true;
2208 // Visit declaration name.
2209 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2210 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002211 continue;
2212 }
Ted Kremenek60458782010-11-12 21:34:16 +00002213 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002214 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002215 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002216 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2217 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002218 return true;
2219 // Visit the declaration name.
2220 if (VisitDeclarationNameInfo(O->getNameInfo()))
2221 return true;
2222 // Visit the overloaded declaration reference.
2223 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2224 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002225 continue;
2226 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002227 case VisitorJob::SizeOfPackExprPartsKind: {
2228 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2229 NamedDecl *Pack = E->getPack();
2230 if (isa<TemplateTypeParmDecl>(Pack)) {
2231 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2232 E->getPackLoc(), TU)))
2233 return true;
2234
2235 continue;
2236 }
2237
2238 if (isa<TemplateTemplateParmDecl>(Pack)) {
2239 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2240 E->getPackLoc(), TU)))
2241 return true;
2242
2243 continue;
2244 }
2245
2246 // Non-type template parameter packs and function parameter packs are
2247 // treated like DeclRefExpr cursors.
2248 continue;
2249 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002250 }
2251 }
2252 return false;
2253}
2254
Ted Kremenekcdba6592010-11-18 00:42:18 +00002255bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002256 VisitorWorkList *WL = 0;
2257 if (!WorkListFreeList.empty()) {
2258 WL = WorkListFreeList.back();
2259 WL->clear();
2260 WorkListFreeList.pop_back();
2261 }
2262 else {
2263 WL = new VisitorWorkList();
2264 WorkListCache.push_back(WL);
2265 }
2266 EnqueueWorkList(*WL, S);
2267 bool result = RunVisitorWorkList(*WL);
2268 WorkListFreeList.push_back(WL);
2269 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002270}
2271
2272//===----------------------------------------------------------------------===//
2273// Misc. API hooks.
2274//===----------------------------------------------------------------------===//
2275
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002276static llvm::sys::Mutex EnableMultithreadingMutex;
2277static bool EnabledMultithreading;
2278
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002279extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002280CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2281 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002282 // Disable pretty stack trace functionality, which will otherwise be a very
2283 // poor citizen of the world and set up all sorts of signal handlers.
2284 llvm::DisablePrettyStackTrace = true;
2285
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002286 // We use crash recovery to make some of our APIs more reliable, implicitly
2287 // enable it.
2288 llvm::CrashRecoveryContext::Enable();
2289
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002290 // Enable support for multithreading in LLVM.
2291 {
2292 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2293 if (!EnabledMultithreading) {
2294 llvm::llvm_start_multithreaded();
2295 EnabledMultithreading = true;
2296 }
2297 }
2298
Douglas Gregora030b7c2010-01-22 20:35:53 +00002299 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002300 if (excludeDeclarationsFromPCH)
2301 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002302 if (displayDiagnostics)
2303 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002304 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002305}
2306
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002307void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002308 if (CIdx)
2309 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002310}
2311
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002312CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002313 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002314 if (!CIdx)
2315 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002316
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002317 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002318 FileSystemOptions FileSystemOpts;
2319 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002320
Douglas Gregor28019772010-04-05 23:52:57 +00002321 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002322 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002323 CXXIdx->getOnlyLocalDecls(),
2324 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002325 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002326}
2327
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002328unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002329 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002330 CXTranslationUnit_CacheCompletionResults |
2331 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002332}
2333
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002334CXTranslationUnit
2335clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2336 const char *source_filename,
2337 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002338 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002339 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002340 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002341 return clang_parseTranslationUnit(CIdx, source_filename,
2342 command_line_args, num_command_line_args,
2343 unsaved_files, num_unsaved_files,
2344 CXTranslationUnit_DetailedPreprocessingRecord);
2345}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002346
2347struct ParseTranslationUnitInfo {
2348 CXIndex CIdx;
2349 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002350 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002351 int num_command_line_args;
2352 struct CXUnsavedFile *unsaved_files;
2353 unsigned num_unsaved_files;
2354 unsigned options;
2355 CXTranslationUnit result;
2356};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002357static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002358 ParseTranslationUnitInfo *PTUI =
2359 static_cast<ParseTranslationUnitInfo*>(UserData);
2360 CXIndex CIdx = PTUI->CIdx;
2361 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002362 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002363 int num_command_line_args = PTUI->num_command_line_args;
2364 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2365 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2366 unsigned options = PTUI->options;
2367 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002368
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002369 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002370 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002371
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002372 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2373
Douglas Gregor44c181a2010-07-23 00:33:23 +00002374 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002375 bool CompleteTranslationUnit
2376 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002377 bool CacheCodeCompetionResults
2378 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002379 bool CXXPrecompilePreamble
2380 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2381 bool CXXChainedPCH
2382 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002383
Douglas Gregor5352ac02010-01-28 00:27:43 +00002384 // Configure the diagnostics.
2385 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002386 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002387 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2388 command_line_args);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002389
Douglas Gregor4db64a42010-01-23 00:14:00 +00002390 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2391 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002392 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002393 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002394 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002395 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2396 Buffer));
2397 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002398
Douglas Gregorb10daed2010-10-11 16:52:23 +00002399 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002400
Ted Kremenek139ba862009-10-22 00:03:57 +00002401 // The 'source_filename' argument is optional. If the caller does not
2402 // specify it then it is assumed that the source file is specified
2403 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002404 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002405 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002406
2407 // Since the Clang C library is primarily used by batch tools dealing with
2408 // (often very broken) source code, where spell-checking can have a
2409 // significant negative impact on performance (particularly when
2410 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002411 // Only do this if we haven't found a spell-checking-related argument.
2412 bool FoundSpellCheckingArgument = false;
2413 for (int I = 0; I != num_command_line_args; ++I) {
2414 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2415 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2416 FoundSpellCheckingArgument = true;
2417 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002418 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002419 }
2420 if (!FoundSpellCheckingArgument)
2421 Args.push_back("-fno-spell-checking");
2422
2423 Args.insert(Args.end(), command_line_args,
2424 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002425
Douglas Gregor44c181a2010-07-23 00:33:23 +00002426 // Do we need the detailed preprocessing record?
2427 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002428 Args.push_back("-Xclang");
2429 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002430 }
2431
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002432 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002433 llvm::OwningPtr<ASTUnit> Unit(
2434 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2435 Diags,
2436 CXXIdx->getClangResourcesPath(),
2437 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002438 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002439 RemappedFiles.data(),
2440 RemappedFiles.size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002441 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002442 PrecompilePreamble,
2443 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002444 CacheCodeCompetionResults,
2445 CXXPrecompilePreamble,
2446 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002447
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002448 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002449 // Make sure to check that 'Unit' is non-NULL.
2450 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2451 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2452 DEnd = Unit->stored_diag_end();
2453 D != DEnd; ++D) {
2454 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2455 CXString Msg = clang_formatDiagnostic(&Diag,
2456 clang_defaultDiagnosticDisplayOptions());
2457 fprintf(stderr, "%s\n", clang_getCString(Msg));
2458 clang_disposeString(Msg);
2459 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002460#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002461 // On Windows, force a flush, since there may be multiple copies of
2462 // stderr and stdout in the file system, all with different buffers
2463 // but writing to the same device.
2464 fflush(stderr);
2465#endif
2466 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002467 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002468
Ted Kremeneka60ed472010-11-16 08:15:36 +00002469 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002470}
2471CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2472 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002473 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002474 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002475 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002476 unsigned num_unsaved_files,
2477 unsigned options) {
2478 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002479 num_command_line_args, unsaved_files,
2480 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002481 llvm::CrashRecoveryContext CRC;
2482
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002483 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002484 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2485 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2486 fprintf(stderr, " 'command_line_args' : [");
2487 for (int i = 0; i != num_command_line_args; ++i) {
2488 if (i)
2489 fprintf(stderr, ", ");
2490 fprintf(stderr, "'%s'", command_line_args[i]);
2491 }
2492 fprintf(stderr, "],\n");
2493 fprintf(stderr, " 'unsaved_files' : [");
2494 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2495 if (i)
2496 fprintf(stderr, ", ");
2497 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2498 unsaved_files[i].Length);
2499 }
2500 fprintf(stderr, "],\n");
2501 fprintf(stderr, " 'options' : %d,\n", options);
2502 fprintf(stderr, "}\n");
2503
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002504 return 0;
2505 }
2506
2507 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002508}
2509
Douglas Gregor19998442010-08-13 15:35:05 +00002510unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2511 return CXSaveTranslationUnit_None;
2512}
2513
2514int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2515 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002516 if (!TU)
2517 return 1;
2518
Ted Kremeneka60ed472010-11-16 08:15:36 +00002519 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002520}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002521
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002522void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002523 if (CTUnit) {
2524 // If the translation unit has been marked as unsafe to free, just discard
2525 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002526 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002527 return;
2528
Ted Kremeneka60ed472010-11-16 08:15:36 +00002529 delete static_cast<ASTUnit *>(CTUnit->TUData);
2530 disposeCXStringPool(CTUnit->StringPool);
2531 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002532 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002533}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002534
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002535unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2536 return CXReparse_None;
2537}
2538
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002539struct ReparseTranslationUnitInfo {
2540 CXTranslationUnit TU;
2541 unsigned num_unsaved_files;
2542 struct CXUnsavedFile *unsaved_files;
2543 unsigned options;
2544 int result;
2545};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002546
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002547static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002548 ReparseTranslationUnitInfo *RTUI =
2549 static_cast<ReparseTranslationUnitInfo*>(UserData);
2550 CXTranslationUnit TU = RTUI->TU;
2551 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2552 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2553 unsigned options = RTUI->options;
2554 (void) options;
2555 RTUI->result = 1;
2556
Douglas Gregorabc563f2010-07-19 21:46:24 +00002557 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002558 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002559
Ted Kremeneka60ed472010-11-16 08:15:36 +00002560 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002561 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002562
2563 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2564 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2565 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2566 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002567 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002568 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2569 Buffer));
2570 }
2571
Douglas Gregor593b0c12010-09-23 18:47:53 +00002572 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2573 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002574}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002575
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002576int clang_reparseTranslationUnit(CXTranslationUnit TU,
2577 unsigned num_unsaved_files,
2578 struct CXUnsavedFile *unsaved_files,
2579 unsigned options) {
2580 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2581 options, 0 };
2582 llvm::CrashRecoveryContext CRC;
2583
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002584 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002585 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002586 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002587 return 1;
2588 }
2589
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002590
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002591 return RTUI.result;
2592}
2593
Douglas Gregordf95a132010-08-09 20:45:32 +00002594
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002595CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002596 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002597 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Ted Kremeneka60ed472010-11-16 08:15:36 +00002599 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002600 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002601}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002602
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002603CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002604 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002605 return Result;
2606}
2607
Ted Kremenekfb480492010-01-13 21:46:36 +00002608} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002609
Ted Kremenekfb480492010-01-13 21:46:36 +00002610//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002611// CXSourceLocation and CXSourceRange Operations.
2612//===----------------------------------------------------------------------===//
2613
Douglas Gregorb9790342010-01-22 21:44:22 +00002614extern "C" {
2615CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002616 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002617 return Result;
2618}
2619
2620unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002621 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2622 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2623 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002624}
2625
2626CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2627 CXFile file,
2628 unsigned line,
2629 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002630 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002631 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002632
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002633 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002634 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002635 const FileEntry *File = static_cast<const FileEntry *>(file);
Douglas Gregorb9790342010-01-22 21:44:22 +00002636 SourceLocation SLoc
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002637 = CXXUnit->getSourceManager().getLocation(File, line, column);
2638 if (SLoc.isInvalid()) {
2639 if (Logging)
2640 llvm::errs() << "clang_getLocation(\"" << File->getName()
2641 << "\", " << line << ", " << column << ") = invalid\n";
2642 return clang_getNullLocation();
2643 }
2644
2645 if (Logging)
2646 llvm::errs() << "clang_getLocation(\"" << File->getName()
2647 << "\", " << line << ", " << column << ") = "
2648 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002649
2650 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2651}
2652
2653CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2654 CXFile file,
2655 unsigned offset) {
2656 if (!tu || !file)
2657 return clang_getNullLocation();
2658
Ted Kremeneka60ed472010-11-16 08:15:36 +00002659 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
David Chisnall83889a72010-10-15 17:07:39 +00002660 SourceLocation Start
2661 = CXXUnit->getSourceManager().getLocation(
2662 static_cast<const FileEntry *>(file),
2663 1, 1);
2664 if (Start.isInvalid()) return clang_getNullLocation();
2665
2666 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2667
2668 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002669
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002670 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002671}
2672
Douglas Gregor5352ac02010-01-28 00:27:43 +00002673CXSourceRange clang_getNullRange() {
2674 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2675 return Result;
2676}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002677
Douglas Gregor5352ac02010-01-28 00:27:43 +00002678CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2679 if (begin.ptr_data[0] != end.ptr_data[0] ||
2680 begin.ptr_data[1] != end.ptr_data[1])
2681 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002682
2683 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002684 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002685 return Result;
2686}
2687
Douglas Gregor46766dc2010-01-26 19:19:08 +00002688void clang_getInstantiationLocation(CXSourceLocation location,
2689 CXFile *file,
2690 unsigned *line,
2691 unsigned *column,
2692 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002693 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2694
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002695 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002696 if (file)
2697 *file = 0;
2698 if (line)
2699 *line = 0;
2700 if (column)
2701 *column = 0;
2702 if (offset)
2703 *offset = 0;
2704 return;
2705 }
2706
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002707 const SourceManager &SM =
2708 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002709 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002710
2711 if (file)
2712 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2713 if (line)
2714 *line = SM.getInstantiationLineNumber(InstLoc);
2715 if (column)
2716 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002717 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002718 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002719}
2720
Douglas Gregora9b06d42010-11-09 06:24:54 +00002721void clang_getSpellingLocation(CXSourceLocation location,
2722 CXFile *file,
2723 unsigned *line,
2724 unsigned *column,
2725 unsigned *offset) {
2726 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2727
2728 if (!location.ptr_data[0] || Loc.isInvalid()) {
2729 if (file)
2730 *file = 0;
2731 if (line)
2732 *line = 0;
2733 if (column)
2734 *column = 0;
2735 if (offset)
2736 *offset = 0;
2737 return;
2738 }
2739
2740 const SourceManager &SM =
2741 *static_cast<const SourceManager*>(location.ptr_data[0]);
2742 SourceLocation SpellLoc = Loc;
2743 if (SpellLoc.isMacroID()) {
2744 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2745 if (SimpleSpellingLoc.isFileID() &&
2746 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2747 SpellLoc = SimpleSpellingLoc;
2748 else
2749 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2750 }
2751
2752 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2753 FileID FID = LocInfo.first;
2754 unsigned FileOffset = LocInfo.second;
2755
2756 if (file)
2757 *file = (void *)SM.getFileEntryForID(FID);
2758 if (line)
2759 *line = SM.getLineNumber(FID, FileOffset);
2760 if (column)
2761 *column = SM.getColumnNumber(FID, FileOffset);
2762 if (offset)
2763 *offset = FileOffset;
2764}
2765
Douglas Gregor1db19de2010-01-19 21:36:55 +00002766CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002767 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002768 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002769 return Result;
2770}
2771
2772CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002773 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002774 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002775 return Result;
2776}
2777
Douglas Gregorb9790342010-01-22 21:44:22 +00002778} // end: extern "C"
2779
Douglas Gregor1db19de2010-01-19 21:36:55 +00002780//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002781// CXFile Operations.
2782//===----------------------------------------------------------------------===//
2783
2784extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002785CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002786 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002787 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002788
Steve Naroff88145032009-10-27 14:35:18 +00002789 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002790 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002791}
2792
2793time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002794 if (!SFile)
2795 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002796
Steve Naroff88145032009-10-27 14:35:18 +00002797 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2798 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002799}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002800
Douglas Gregorb9790342010-01-22 21:44:22 +00002801CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2802 if (!tu)
2803 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002804
Ted Kremeneka60ed472010-11-16 08:15:36 +00002805 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002806
Douglas Gregorb9790342010-01-22 21:44:22 +00002807 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002808 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002809}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002810
Ted Kremenekfb480492010-01-13 21:46:36 +00002811} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002812
Ted Kremenekfb480492010-01-13 21:46:36 +00002813//===----------------------------------------------------------------------===//
2814// CXCursor Operations.
2815//===----------------------------------------------------------------------===//
2816
Ted Kremenekfb480492010-01-13 21:46:36 +00002817static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002818 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2819 return getDeclFromExpr(CE->getSubExpr());
2820
Ted Kremenekfb480492010-01-13 21:46:36 +00002821 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2822 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002823 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2824 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002825 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2826 return ME->getMemberDecl();
2827 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2828 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002829 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002830 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002831
Ted Kremenekfb480492010-01-13 21:46:36 +00002832 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2833 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002834 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2835 if (!CE->isElidable())
2836 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002837 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2838 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002839
Douglas Gregordb1314e2010-10-01 21:11:22 +00002840 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2841 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002842 if (SubstNonTypeTemplateParmPackExpr *NTTP
2843 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2844 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002845 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2846 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2847 isa<ParmVarDecl>(SizeOfPack->getPack()))
2848 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002849
Ted Kremenekfb480492010-01-13 21:46:36 +00002850 return 0;
2851}
2852
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002853static SourceLocation getLocationFromExpr(Expr *E) {
2854 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2855 return /*FIXME:*/Msg->getLeftLoc();
2856 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2857 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002858 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2859 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002860 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2861 return Member->getMemberLoc();
2862 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2863 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002864 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2865 return SizeOfPack->getPackLoc();
2866
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002867 return E->getLocStart();
2868}
2869
Ted Kremenekfb480492010-01-13 21:46:36 +00002870extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002871
2872unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002873 CXCursorVisitor visitor,
2874 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00002875 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00002876 getCursorASTUnit(parent)->getMaxPCHLevel(),
2877 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002878 return CursorVis.VisitChildren(parent);
2879}
2880
David Chisnall3387c652010-11-03 14:12:26 +00002881#ifndef __has_feature
2882#define __has_feature(x) 0
2883#endif
2884#if __has_feature(blocks)
2885typedef enum CXChildVisitResult
2886 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2887
2888static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2889 CXClientData client_data) {
2890 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2891 return block(cursor, parent);
2892}
2893#else
2894// If we are compiled with a compiler that doesn't have native blocks support,
2895// define and call the block manually, so the
2896typedef struct _CXChildVisitResult
2897{
2898 void *isa;
2899 int flags;
2900 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002901 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2902 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002903} *CXCursorVisitorBlock;
2904
2905static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2906 CXClientData client_data) {
2907 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2908 return block->invoke(block, cursor, parent);
2909}
2910#endif
2911
2912
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002913unsigned clang_visitChildrenWithBlock(CXCursor parent,
2914 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002915 return clang_visitChildren(parent, visitWithBlock, block);
2916}
2917
Douglas Gregor78205d42010-01-20 21:45:58 +00002918static CXString getDeclSpelling(Decl *D) {
2919 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00002920 if (!ND) {
2921 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2922 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2923 return createCXString(Property->getIdentifier()->getName());
2924
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002925 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00002926 }
2927
Douglas Gregor78205d42010-01-20 21:45:58 +00002928 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002929 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002930
Douglas Gregor78205d42010-01-20 21:45:58 +00002931 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2932 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2933 // and returns different names. NamedDecl returns the class name and
2934 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002935 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002936
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002937 if (isa<UsingDirectiveDecl>(D))
2938 return createCXString("");
2939
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002940 llvm::SmallString<1024> S;
2941 llvm::raw_svector_ostream os(S);
2942 ND->printName(os);
2943
2944 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002945}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002946
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002947CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002948 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00002949 return clang_getTranslationUnitSpelling(
2950 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002951
Steve Narofff334b4e2009-09-02 18:26:48 +00002952 if (clang_isReference(C.kind)) {
2953 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002954 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002955 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002956 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002957 }
2958 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002959 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002960 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002961 }
2962 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002963 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002964 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002965 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002966 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002967 case CXCursor_CXXBaseSpecifier: {
2968 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2969 return createCXString(B->getType().getAsString());
2970 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002971 case CXCursor_TypeRef: {
2972 TypeDecl *Type = getCursorTypeRef(C).first;
2973 assert(Type && "Missing type decl");
2974
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002975 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2976 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002977 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002978 case CXCursor_TemplateRef: {
2979 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002980 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002981
2982 return createCXString(Template->getNameAsString());
2983 }
Douglas Gregor69319002010-08-31 23:48:11 +00002984
2985 case CXCursor_NamespaceRef: {
2986 NamedDecl *NS = getCursorNamespaceRef(C).first;
2987 assert(NS && "Missing namespace decl");
2988
2989 return createCXString(NS->getNameAsString());
2990 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002991
Douglas Gregora67e03f2010-09-09 21:42:20 +00002992 case CXCursor_MemberRef: {
2993 FieldDecl *Field = getCursorMemberRef(C).first;
2994 assert(Field && "Missing member decl");
2995
2996 return createCXString(Field->getNameAsString());
2997 }
2998
Douglas Gregor36897b02010-09-10 00:22:18 +00002999 case CXCursor_LabelRef: {
3000 LabelStmt *Label = getCursorLabelRef(C).first;
3001 assert(Label && "Missing label");
3002
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003003 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003004 }
3005
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003006 case CXCursor_OverloadedDeclRef: {
3007 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3008 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3009 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3010 return createCXString(ND->getNameAsString());
3011 return createCXString("");
3012 }
3013 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3014 return createCXString(E->getName().getAsString());
3015 OverloadedTemplateStorage *Ovl
3016 = Storage.get<OverloadedTemplateStorage*>();
3017 if (Ovl->size() == 0)
3018 return createCXString("");
3019 return createCXString((*Ovl->begin())->getNameAsString());
3020 }
3021
Daniel Dunbaracca7252009-11-30 20:42:49 +00003022 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003023 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003024 }
3025 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003026
3027 if (clang_isExpression(C.kind)) {
3028 Decl *D = getDeclFromExpr(getCursorExpr(C));
3029 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003030 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003031 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003032 }
3033
Douglas Gregor36897b02010-09-10 00:22:18 +00003034 if (clang_isStatement(C.kind)) {
3035 Stmt *S = getCursorStmt(C);
3036 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003037 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003038
3039 return createCXString("");
3040 }
3041
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003042 if (C.kind == CXCursor_MacroInstantiation)
3043 return createCXString(getCursorMacroInstantiation(C)->getName()
3044 ->getNameStart());
3045
Douglas Gregor572feb22010-03-18 18:04:21 +00003046 if (C.kind == CXCursor_MacroDefinition)
3047 return createCXString(getCursorMacroDefinition(C)->getName()
3048 ->getNameStart());
3049
Douglas Gregorecdcb882010-10-20 22:00:55 +00003050 if (C.kind == CXCursor_InclusionDirective)
3051 return createCXString(getCursorInclusionDirective(C)->getFileName());
3052
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003053 if (clang_isDeclaration(C.kind))
3054 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003055
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003056 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003057}
3058
Douglas Gregor358559d2010-10-02 22:49:11 +00003059CXString clang_getCursorDisplayName(CXCursor C) {
3060 if (!clang_isDeclaration(C.kind))
3061 return clang_getCursorSpelling(C);
3062
3063 Decl *D = getCursorDecl(C);
3064 if (!D)
3065 return createCXString("");
3066
3067 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3068 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3069 D = FunTmpl->getTemplatedDecl();
3070
3071 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3072 llvm::SmallString<64> Str;
3073 llvm::raw_svector_ostream OS(Str);
3074 OS << Function->getNameAsString();
3075 if (Function->getPrimaryTemplate())
3076 OS << "<>";
3077 OS << "(";
3078 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3079 if (I)
3080 OS << ", ";
3081 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3082 }
3083
3084 if (Function->isVariadic()) {
3085 if (Function->getNumParams())
3086 OS << ", ";
3087 OS << "...";
3088 }
3089 OS << ")";
3090 return createCXString(OS.str());
3091 }
3092
3093 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3094 llvm::SmallString<64> Str;
3095 llvm::raw_svector_ostream OS(Str);
3096 OS << ClassTemplate->getNameAsString();
3097 OS << "<";
3098 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3099 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3100 if (I)
3101 OS << ", ";
3102
3103 NamedDecl *Param = Params->getParam(I);
3104 if (Param->getIdentifier()) {
3105 OS << Param->getIdentifier()->getName();
3106 continue;
3107 }
3108
3109 // There is no parameter name, which makes this tricky. Try to come up
3110 // with something useful that isn't too long.
3111 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3112 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3113 else if (NonTypeTemplateParmDecl *NTTP
3114 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3115 OS << NTTP->getType().getAsString(Policy);
3116 else
3117 OS << "template<...> class";
3118 }
3119
3120 OS << ">";
3121 return createCXString(OS.str());
3122 }
3123
3124 if (ClassTemplateSpecializationDecl *ClassSpec
3125 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3126 // If the type was explicitly written, use that.
3127 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3128 return createCXString(TSInfo->getType().getAsString(Policy));
3129
3130 llvm::SmallString<64> Str;
3131 llvm::raw_svector_ostream OS(Str);
3132 OS << ClassSpec->getNameAsString();
3133 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003134 ClassSpec->getTemplateArgs().data(),
3135 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003136 Policy);
3137 return createCXString(OS.str());
3138 }
3139
3140 return clang_getCursorSpelling(C);
3141}
3142
Ted Kremeneke68fff62010-02-17 00:41:32 +00003143CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003144 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003145 case CXCursor_FunctionDecl:
3146 return createCXString("FunctionDecl");
3147 case CXCursor_TypedefDecl:
3148 return createCXString("TypedefDecl");
3149 case CXCursor_EnumDecl:
3150 return createCXString("EnumDecl");
3151 case CXCursor_EnumConstantDecl:
3152 return createCXString("EnumConstantDecl");
3153 case CXCursor_StructDecl:
3154 return createCXString("StructDecl");
3155 case CXCursor_UnionDecl:
3156 return createCXString("UnionDecl");
3157 case CXCursor_ClassDecl:
3158 return createCXString("ClassDecl");
3159 case CXCursor_FieldDecl:
3160 return createCXString("FieldDecl");
3161 case CXCursor_VarDecl:
3162 return createCXString("VarDecl");
3163 case CXCursor_ParmDecl:
3164 return createCXString("ParmDecl");
3165 case CXCursor_ObjCInterfaceDecl:
3166 return createCXString("ObjCInterfaceDecl");
3167 case CXCursor_ObjCCategoryDecl:
3168 return createCXString("ObjCCategoryDecl");
3169 case CXCursor_ObjCProtocolDecl:
3170 return createCXString("ObjCProtocolDecl");
3171 case CXCursor_ObjCPropertyDecl:
3172 return createCXString("ObjCPropertyDecl");
3173 case CXCursor_ObjCIvarDecl:
3174 return createCXString("ObjCIvarDecl");
3175 case CXCursor_ObjCInstanceMethodDecl:
3176 return createCXString("ObjCInstanceMethodDecl");
3177 case CXCursor_ObjCClassMethodDecl:
3178 return createCXString("ObjCClassMethodDecl");
3179 case CXCursor_ObjCImplementationDecl:
3180 return createCXString("ObjCImplementationDecl");
3181 case CXCursor_ObjCCategoryImplDecl:
3182 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003183 case CXCursor_CXXMethod:
3184 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003185 case CXCursor_UnexposedDecl:
3186 return createCXString("UnexposedDecl");
3187 case CXCursor_ObjCSuperClassRef:
3188 return createCXString("ObjCSuperClassRef");
3189 case CXCursor_ObjCProtocolRef:
3190 return createCXString("ObjCProtocolRef");
3191 case CXCursor_ObjCClassRef:
3192 return createCXString("ObjCClassRef");
3193 case CXCursor_TypeRef:
3194 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003195 case CXCursor_TemplateRef:
3196 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003197 case CXCursor_NamespaceRef:
3198 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003199 case CXCursor_MemberRef:
3200 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003201 case CXCursor_LabelRef:
3202 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003203 case CXCursor_OverloadedDeclRef:
3204 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003205 case CXCursor_UnexposedExpr:
3206 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003207 case CXCursor_BlockExpr:
3208 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003209 case CXCursor_DeclRefExpr:
3210 return createCXString("DeclRefExpr");
3211 case CXCursor_MemberRefExpr:
3212 return createCXString("MemberRefExpr");
3213 case CXCursor_CallExpr:
3214 return createCXString("CallExpr");
3215 case CXCursor_ObjCMessageExpr:
3216 return createCXString("ObjCMessageExpr");
3217 case CXCursor_UnexposedStmt:
3218 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003219 case CXCursor_LabelStmt:
3220 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003221 case CXCursor_InvalidFile:
3222 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003223 case CXCursor_InvalidCode:
3224 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003225 case CXCursor_NoDeclFound:
3226 return createCXString("NoDeclFound");
3227 case CXCursor_NotImplemented:
3228 return createCXString("NotImplemented");
3229 case CXCursor_TranslationUnit:
3230 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003231 case CXCursor_UnexposedAttr:
3232 return createCXString("UnexposedAttr");
3233 case CXCursor_IBActionAttr:
3234 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003235 case CXCursor_IBOutletAttr:
3236 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003237 case CXCursor_IBOutletCollectionAttr:
3238 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003239 case CXCursor_PreprocessingDirective:
3240 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003241 case CXCursor_MacroDefinition:
3242 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003243 case CXCursor_MacroInstantiation:
3244 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003245 case CXCursor_InclusionDirective:
3246 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003247 case CXCursor_Namespace:
3248 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003249 case CXCursor_LinkageSpec:
3250 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003251 case CXCursor_CXXBaseSpecifier:
3252 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003253 case CXCursor_Constructor:
3254 return createCXString("CXXConstructor");
3255 case CXCursor_Destructor:
3256 return createCXString("CXXDestructor");
3257 case CXCursor_ConversionFunction:
3258 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003259 case CXCursor_TemplateTypeParameter:
3260 return createCXString("TemplateTypeParameter");
3261 case CXCursor_NonTypeTemplateParameter:
3262 return createCXString("NonTypeTemplateParameter");
3263 case CXCursor_TemplateTemplateParameter:
3264 return createCXString("TemplateTemplateParameter");
3265 case CXCursor_FunctionTemplate:
3266 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003267 case CXCursor_ClassTemplate:
3268 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003269 case CXCursor_ClassTemplatePartialSpecialization:
3270 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003271 case CXCursor_NamespaceAlias:
3272 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003273 case CXCursor_UsingDirective:
3274 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003275 case CXCursor_UsingDeclaration:
3276 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003277 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003278
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003279 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003280 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003281}
Steve Naroff89922f82009-08-31 00:59:03 +00003282
Ted Kremeneke68fff62010-02-17 00:41:32 +00003283enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3284 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003285 CXClientData client_data) {
3286 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003287
3288 // If our current best cursor is the construction of a temporary object,
3289 // don't replace that cursor with a type reference, because we want
3290 // clang_getCursor() to point at the constructor.
3291 if (clang_isExpression(BestCursor->kind) &&
3292 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3293 cursor.kind == CXCursor_TypeRef)
3294 return CXChildVisit_Recurse;
3295
Douglas Gregor85fe1562010-12-10 07:23:11 +00003296 // Don't override a preprocessing cursor with another preprocessing
3297 // cursor; we want the outermost preprocessing cursor.
3298 if (clang_isPreprocessing(cursor.kind) &&
3299 clang_isPreprocessing(BestCursor->kind))
3300 return CXChildVisit_Recurse;
3301
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003302 *BestCursor = cursor;
3303 return CXChildVisit_Recurse;
3304}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003305
Douglas Gregorb9790342010-01-22 21:44:22 +00003306CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3307 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003308 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003309
Ted Kremeneka60ed472010-11-16 08:15:36 +00003310 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003311 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3312
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003313 // Translate the given source location to make it point at the beginning of
3314 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003315 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003316
3317 // Guard against an invalid SourceLocation, or we may assert in one
3318 // of the following calls.
3319 if (SLoc.isInvalid())
3320 return clang_getNullCursor();
3321
Douglas Gregor40749ee2010-11-03 00:35:38 +00003322 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003323 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3324 CXXUnit->getASTContext().getLangOptions());
3325
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003326 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3327 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003328 // FIXME: Would be great to have a "hint" cursor, then walk from that
3329 // hint cursor upward until we find a cursor whose source range encloses
3330 // the region of interest, rather than starting from the translation unit.
Ted Kremeneka60ed472010-11-16 08:15:36 +00003331 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3332 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003333 Decl::MaxPCHLevel, true, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003334 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003335 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003336
3337 if (Logging) {
3338 CXFile SearchFile;
3339 unsigned SearchLine, SearchColumn;
3340 CXFile ResultFile;
3341 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003342 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3343 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003344 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3345
3346 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3347 0);
3348 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3349 &ResultColumn, 0);
3350 SearchFileName = clang_getFileName(SearchFile);
3351 ResultFileName = clang_getFileName(ResultFile);
3352 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003353 USR = clang_getCursorUSR(Result);
3354 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003355 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3356 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003357 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3358 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003359 clang_disposeString(SearchFileName);
3360 clang_disposeString(ResultFileName);
3361 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003362 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003363
3364 CXCursor Definition = clang_getCursorDefinition(Result);
3365 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3366 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3367 CXString DefinitionKindSpelling
3368 = clang_getCursorKindSpelling(Definition.kind);
3369 CXFile DefinitionFile;
3370 unsigned DefinitionLine, DefinitionColumn;
3371 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3372 &DefinitionLine, &DefinitionColumn, 0);
3373 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3374 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3375 clang_getCString(DefinitionKindSpelling),
3376 clang_getCString(DefinitionFileName),
3377 DefinitionLine, DefinitionColumn);
3378 clang_disposeString(DefinitionFileName);
3379 clang_disposeString(DefinitionKindSpelling);
3380 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003381 }
3382
Ted Kremeneke68fff62010-02-17 00:41:32 +00003383 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003384}
3385
Ted Kremenek73885552009-11-17 19:28:59 +00003386CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003387 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003388}
3389
3390unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003391 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003392}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003393
Douglas Gregor9ce55842010-11-20 00:09:34 +00003394unsigned clang_hashCursor(CXCursor C) {
3395 unsigned Index = 0;
3396 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3397 Index = 1;
3398
3399 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3400 std::make_pair(C.kind, C.data[Index]));
3401}
3402
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003403unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003404 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3405}
3406
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003407unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003408 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3409}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003410
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003411unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003412 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3413}
3414
Douglas Gregor97b98722010-01-19 23:20:36 +00003415unsigned clang_isExpression(enum CXCursorKind K) {
3416 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3417}
3418
3419unsigned clang_isStatement(enum CXCursorKind K) {
3420 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3421}
3422
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003423unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3424 return K == CXCursor_TranslationUnit;
3425}
3426
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003427unsigned clang_isPreprocessing(enum CXCursorKind K) {
3428 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3429}
3430
Ted Kremenekad6eff62010-03-08 21:17:29 +00003431unsigned clang_isUnexposed(enum CXCursorKind K) {
3432 switch (K) {
3433 case CXCursor_UnexposedDecl:
3434 case CXCursor_UnexposedExpr:
3435 case CXCursor_UnexposedStmt:
3436 case CXCursor_UnexposedAttr:
3437 return true;
3438 default:
3439 return false;
3440 }
3441}
3442
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003443CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003444 return C.kind;
3445}
3446
Douglas Gregor98258af2010-01-18 22:46:11 +00003447CXSourceLocation clang_getCursorLocation(CXCursor C) {
3448 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003449 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003450 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003451 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3452 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003453 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003454 }
3455
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003457 std::pair<ObjCProtocolDecl *, SourceLocation> P
3458 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003459 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003460 }
3461
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003462 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003463 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3464 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003465 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003466 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003467
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003468 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003469 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003470 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003471 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003472
3473 case CXCursor_TemplateRef: {
3474 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3475 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3476 }
3477
Douglas Gregor69319002010-08-31 23:48:11 +00003478 case CXCursor_NamespaceRef: {
3479 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3480 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3481 }
3482
Douglas Gregora67e03f2010-09-09 21:42:20 +00003483 case CXCursor_MemberRef: {
3484 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3485 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3486 }
3487
Ted Kremenek3064ef92010-08-27 21:34:58 +00003488 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003489 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3490 if (!BaseSpec)
3491 return clang_getNullLocation();
3492
3493 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3494 return cxloc::translateSourceLocation(getCursorContext(C),
3495 TSInfo->getTypeLoc().getBeginLoc());
3496
3497 return cxloc::translateSourceLocation(getCursorContext(C),
3498 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003499 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003500
Douglas Gregor36897b02010-09-10 00:22:18 +00003501 case CXCursor_LabelRef: {
3502 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3503 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3504 }
3505
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003506 case CXCursor_OverloadedDeclRef:
3507 return cxloc::translateSourceLocation(getCursorContext(C),
3508 getCursorOverloadedDeclRef(C).second);
3509
Douglas Gregorf46034a2010-01-18 23:41:10 +00003510 default:
3511 // FIXME: Need a way to enumerate all non-reference cases.
3512 llvm_unreachable("Missed a reference kind");
3513 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003514 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003515
3516 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003517 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003518 getLocationFromExpr(getCursorExpr(C)));
3519
Douglas Gregor36897b02010-09-10 00:22:18 +00003520 if (clang_isStatement(C.kind))
3521 return cxloc::translateSourceLocation(getCursorContext(C),
3522 getCursorStmt(C)->getLocStart());
3523
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003524 if (C.kind == CXCursor_PreprocessingDirective) {
3525 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3526 return cxloc::translateSourceLocation(getCursorContext(C), L);
3527 }
Douglas Gregor48072312010-03-18 15:23:44 +00003528
3529 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003530 SourceLocation L
3531 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003532 return cxloc::translateSourceLocation(getCursorContext(C), L);
3533 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003534
3535 if (C.kind == CXCursor_MacroDefinition) {
3536 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3537 return cxloc::translateSourceLocation(getCursorContext(C), L);
3538 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003539
3540 if (C.kind == CXCursor_InclusionDirective) {
3541 SourceLocation L
3542 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3543 return cxloc::translateSourceLocation(getCursorContext(C), L);
3544 }
3545
Ted Kremenek9a700d22010-05-12 06:16:13 +00003546 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003547 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003548
Douglas Gregorf46034a2010-01-18 23:41:10 +00003549 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003550 SourceLocation Loc = D->getLocation();
3551 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3552 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003553 // FIXME: Multiple variables declared in a single declaration
3554 // currently lack the information needed to correctly determine their
3555 // ranges when accounting for the type-specifier. We use context
3556 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3557 // and if so, whether it is the first decl.
3558 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3559 if (!cxcursor::isFirstInDeclGroup(C))
3560 Loc = VD->getLocation();
3561 }
3562
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003563 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003564}
Douglas Gregora7bde202010-01-19 00:34:46 +00003565
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003566} // end extern "C"
3567
3568static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003569 if (clang_isReference(C.kind)) {
3570 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003571 case CXCursor_ObjCSuperClassRef:
3572 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003573
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003574 case CXCursor_ObjCProtocolRef:
3575 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003576
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003577 case CXCursor_ObjCClassRef:
3578 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003579
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003580 case CXCursor_TypeRef:
3581 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003582
3583 case CXCursor_TemplateRef:
3584 return getCursorTemplateRef(C).second;
3585
Douglas Gregor69319002010-08-31 23:48:11 +00003586 case CXCursor_NamespaceRef:
3587 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003588
3589 case CXCursor_MemberRef:
3590 return getCursorMemberRef(C).second;
3591
Ted Kremenek3064ef92010-08-27 21:34:58 +00003592 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003593 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003594
Douglas Gregor36897b02010-09-10 00:22:18 +00003595 case CXCursor_LabelRef:
3596 return getCursorLabelRef(C).second;
3597
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003598 case CXCursor_OverloadedDeclRef:
3599 return getCursorOverloadedDeclRef(C).second;
3600
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003601 default:
3602 // FIXME: Need a way to enumerate all non-reference cases.
3603 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003604 }
3605 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003606
3607 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003608 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003609
3610 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003611 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003612
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003613 if (C.kind == CXCursor_PreprocessingDirective)
3614 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003615
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003616 if (C.kind == CXCursor_MacroInstantiation)
3617 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003618
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003619 if (C.kind == CXCursor_MacroDefinition)
3620 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003621
3622 if (C.kind == CXCursor_InclusionDirective)
3623 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3624
Ted Kremenek007a7c92010-11-01 23:26:51 +00003625 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3626 Decl *D = cxcursor::getCursorDecl(C);
3627 SourceRange R = D->getSourceRange();
3628 // FIXME: Multiple variables declared in a single declaration
3629 // currently lack the information needed to correctly determine their
3630 // ranges when accounting for the type-specifier. We use context
3631 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3632 // and if so, whether it is the first decl.
3633 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3634 if (!cxcursor::isFirstInDeclGroup(C))
3635 R.setBegin(VD->getLocation());
3636 }
3637 return R;
3638 }
Douglas Gregor66537982010-11-17 17:14:07 +00003639 return SourceRange();
3640}
3641
3642/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3643/// the decl-specifier-seq for declarations.
3644static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3645 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3646 Decl *D = cxcursor::getCursorDecl(C);
3647 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003648
Douglas Gregor2494dd02011-03-01 01:34:45 +00003649 // Adjust the start of the location for declarations preceded by
3650 // declaration specifiers.
3651 SourceLocation StartLoc;
3652 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3653 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3654 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3655 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3656 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3657 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3658 }
3659
3660 if (StartLoc.isValid() && R.getBegin().isValid() &&
3661 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3662 R.setBegin(StartLoc);
3663
3664 // FIXME: Multiple variables declared in a single declaration
3665 // currently lack the information needed to correctly determine their
3666 // ranges when accounting for the type-specifier. We use context
3667 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3668 // and if so, whether it is the first decl.
3669 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3670 if (!cxcursor::isFirstInDeclGroup(C))
3671 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003672 }
3673
3674 return R;
3675 }
3676
3677 return getRawCursorExtent(C);
3678}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003679
3680extern "C" {
3681
3682CXSourceRange clang_getCursorExtent(CXCursor C) {
3683 SourceRange R = getRawCursorExtent(C);
3684 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003685 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003686
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003687 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003688}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003689
3690CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003691 if (clang_isInvalid(C.kind))
3692 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003693
Ted Kremeneka60ed472010-11-16 08:15:36 +00003694 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003695 if (clang_isDeclaration(C.kind)) {
3696 Decl *D = getCursorDecl(C);
3697 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003698 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003699 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003700 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003701 if (ObjCForwardProtocolDecl *Protocols
3702 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003703 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003704 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3705 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3706 return MakeCXCursor(Property, tu);
3707
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003708 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003709 }
3710
Douglas Gregor97b98722010-01-19 23:20:36 +00003711 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003712 Expr *E = getCursorExpr(C);
3713 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003714 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003715 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003716
3717 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003718 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003719
Douglas Gregor97b98722010-01-19 23:20:36 +00003720 return clang_getNullCursor();
3721 }
3722
Douglas Gregor36897b02010-09-10 00:22:18 +00003723 if (clang_isStatement(C.kind)) {
3724 Stmt *S = getCursorStmt(C);
3725 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003726 if (LabelDecl *label = Goto->getLabel())
3727 if (LabelStmt *labelS = label->getStmt())
3728 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003729
3730 return clang_getNullCursor();
3731 }
3732
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003733 if (C.kind == CXCursor_MacroInstantiation) {
3734 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003735 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003736 }
3737
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003738 if (!clang_isReference(C.kind))
3739 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003740
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003741 switch (C.kind) {
3742 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003743 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003744
3745 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003746 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003747
3748 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003749 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003750
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003751 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003752 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003753
3754 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003755 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003756
Douglas Gregor69319002010-08-31 23:48:11 +00003757 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003758 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003759
Douglas Gregora67e03f2010-09-09 21:42:20 +00003760 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003761 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003762
Ted Kremenek3064ef92010-08-27 21:34:58 +00003763 case CXCursor_CXXBaseSpecifier: {
3764 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3765 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003766 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003767 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003768
Douglas Gregor36897b02010-09-10 00:22:18 +00003769 case CXCursor_LabelRef:
3770 // FIXME: We end up faking the "parent" declaration here because we
3771 // don't want to make CXCursor larger.
3772 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003773 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3774 .getTranslationUnitDecl(),
3775 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003776
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003777 case CXCursor_OverloadedDeclRef:
3778 return C;
3779
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003780 default:
3781 // We would prefer to enumerate all non-reference cursor kinds here.
3782 llvm_unreachable("Unhandled reference cursor kind");
3783 break;
3784 }
3785 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003786
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003787 return clang_getNullCursor();
3788}
3789
Douglas Gregorb6998662010-01-19 19:34:47 +00003790CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003791 if (clang_isInvalid(C.kind))
3792 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003793
Ted Kremeneka60ed472010-11-16 08:15:36 +00003794 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003795
Douglas Gregorb6998662010-01-19 19:34:47 +00003796 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003797 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003798 C = clang_getCursorReferenced(C);
3799 WasReference = true;
3800 }
3801
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003802 if (C.kind == CXCursor_MacroInstantiation)
3803 return clang_getCursorReferenced(C);
3804
Douglas Gregorb6998662010-01-19 19:34:47 +00003805 if (!clang_isDeclaration(C.kind))
3806 return clang_getNullCursor();
3807
3808 Decl *D = getCursorDecl(C);
3809 if (!D)
3810 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003811
Douglas Gregorb6998662010-01-19 19:34:47 +00003812 switch (D->getKind()) {
3813 // Declaration kinds that don't really separate the notions of
3814 // declaration and definition.
3815 case Decl::Namespace:
3816 case Decl::Typedef:
3817 case Decl::TemplateTypeParm:
3818 case Decl::EnumConstant:
3819 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00003820 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00003821 case Decl::ObjCIvar:
3822 case Decl::ObjCAtDefsField:
3823 case Decl::ImplicitParam:
3824 case Decl::ParmVar:
3825 case Decl::NonTypeTemplateParm:
3826 case Decl::TemplateTemplateParm:
3827 case Decl::ObjCCategoryImpl:
3828 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003829 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003830 case Decl::LinkageSpec:
3831 case Decl::ObjCPropertyImpl:
3832 case Decl::FileScopeAsm:
3833 case Decl::StaticAssert:
3834 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003835 case Decl::Label: // FIXME: Is this right??
Douglas Gregorb6998662010-01-19 19:34:47 +00003836 return C;
3837
3838 // Declaration kinds that don't make any sense here, but are
3839 // nonetheless harmless.
3840 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003841 break;
3842
3843 // Declaration kinds for which the definition is not resolvable.
3844 case Decl::UnresolvedUsingTypename:
3845 case Decl::UnresolvedUsingValue:
3846 break;
3847
3848 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003849 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003850 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003851
3852 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003853 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003854
3855 case Decl::Enum:
3856 case Decl::Record:
3857 case Decl::CXXRecord:
3858 case Decl::ClassTemplateSpecialization:
3859 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003860 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003861 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003862 return clang_getNullCursor();
3863
3864 case Decl::Function:
3865 case Decl::CXXMethod:
3866 case Decl::CXXConstructor:
3867 case Decl::CXXDestructor:
3868 case Decl::CXXConversion: {
3869 const FunctionDecl *Def = 0;
3870 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003871 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003872 return clang_getNullCursor();
3873 }
3874
3875 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003876 // Ask the variable if it has a definition.
3877 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003878 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00003879 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003880 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003881
Douglas Gregorb6998662010-01-19 19:34:47 +00003882 case Decl::FunctionTemplate: {
3883 const FunctionDecl *Def = 0;
3884 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003885 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003886 return clang_getNullCursor();
3887 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003888
Douglas Gregorb6998662010-01-19 19:34:47 +00003889 case Decl::ClassTemplate: {
3890 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003891 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003892 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003893 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003894 return clang_getNullCursor();
3895 }
3896
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003897 case Decl::Using:
3898 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003899 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003900
3901 case Decl::UsingShadow:
3902 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003903 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003904 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003905
3906 case Decl::ObjCMethod: {
3907 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3908 if (Method->isThisDeclarationADefinition())
3909 return C;
3910
3911 // Dig out the method definition in the associated
3912 // @implementation, if we have it.
3913 // FIXME: The ASTs should make finding the definition easier.
3914 if (ObjCInterfaceDecl *Class
3915 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3916 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3917 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3918 Method->isInstanceMethod()))
3919 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003920 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003921
3922 return clang_getNullCursor();
3923 }
3924
3925 case Decl::ObjCCategory:
3926 if (ObjCCategoryImplDecl *Impl
3927 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003928 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003929 return clang_getNullCursor();
3930
3931 case Decl::ObjCProtocol:
3932 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3933 return C;
3934 return clang_getNullCursor();
3935
3936 case Decl::ObjCInterface:
3937 // There are two notions of a "definition" for an Objective-C
3938 // class: the interface and its implementation. When we resolved a
3939 // reference to an Objective-C class, produce the @interface as
3940 // the definition; when we were provided with the interface,
3941 // produce the @implementation as the definition.
3942 if (WasReference) {
3943 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3944 return C;
3945 } else if (ObjCImplementationDecl *Impl
3946 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003947 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003948 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003949
Douglas Gregorb6998662010-01-19 19:34:47 +00003950 case Decl::ObjCProperty:
3951 // FIXME: We don't really know where to find the
3952 // ObjCPropertyImplDecls that implement this property.
3953 return clang_getNullCursor();
3954
3955 case Decl::ObjCCompatibleAlias:
3956 if (ObjCInterfaceDecl *Class
3957 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3958 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003959 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003960
Douglas Gregorb6998662010-01-19 19:34:47 +00003961 return clang_getNullCursor();
3962
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003963 case Decl::ObjCForwardProtocol:
3964 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003965 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003966
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003967 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003968 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003969 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00003970
3971 case Decl::Friend:
3972 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003973 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003974 return clang_getNullCursor();
3975
3976 case Decl::FriendTemplate:
3977 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003978 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00003979 return clang_getNullCursor();
3980 }
3981
3982 return clang_getNullCursor();
3983}
3984
3985unsigned clang_isCursorDefinition(CXCursor C) {
3986 if (!clang_isDeclaration(C.kind))
3987 return 0;
3988
3989 return clang_getCursorDefinition(C) == C;
3990}
3991
Douglas Gregor1a9d0502010-11-19 23:44:15 +00003992CXCursor clang_getCanonicalCursor(CXCursor C) {
3993 if (!clang_isDeclaration(C.kind))
3994 return C;
3995
3996 if (Decl *D = getCursorDecl(C))
3997 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3998
3999 return C;
4000}
4001
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004002unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004003 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004004 return 0;
4005
4006 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4007 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4008 return E->getNumDecls();
4009
4010 if (OverloadedTemplateStorage *S
4011 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4012 return S->size();
4013
4014 Decl *D = Storage.get<Decl*>();
4015 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004016 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004017 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
4018 return Classes->size();
4019 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4020 return Protocols->protocol_size();
4021
4022 return 0;
4023}
4024
4025CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004026 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004027 return clang_getNullCursor();
4028
4029 if (index >= clang_getNumOverloadedDecls(cursor))
4030 return clang_getNullCursor();
4031
Ted Kremeneka60ed472010-11-16 08:15:36 +00004032 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004033 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4034 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004035 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004036
4037 if (OverloadedTemplateStorage *S
4038 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004039 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004040
4041 Decl *D = Storage.get<Decl*>();
4042 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4043 // FIXME: This is, unfortunately, linear time.
4044 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4045 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004046 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004047 }
4048
4049 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004050 return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004051
4052 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004053 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004054
4055 return clang_getNullCursor();
4056}
4057
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004058void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004059 const char **startBuf,
4060 const char **endBuf,
4061 unsigned *startLine,
4062 unsigned *startColumn,
4063 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004064 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004065 assert(getCursorDecl(C) && "CXCursor has null decl");
4066 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004067 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4068 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004069
Steve Naroff4ade6d62009-09-23 17:52:52 +00004070 SourceManager &SM = FD->getASTContext().getSourceManager();
4071 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4072 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4073 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4074 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4075 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4076 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4077}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004078
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004079void clang_enableStackTraces(void) {
4080 llvm::sys::PrintStackTraceOnErrorSignal();
4081}
4082
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004083void clang_executeOnThread(void (*fn)(void*), void *user_data,
4084 unsigned stack_size) {
4085 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4086}
4087
Ted Kremenekfb480492010-01-13 21:46:36 +00004088} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004089
Ted Kremenekfb480492010-01-13 21:46:36 +00004090//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004091// Token-based Operations.
4092//===----------------------------------------------------------------------===//
4093
4094/* CXToken layout:
4095 * int_data[0]: a CXTokenKind
4096 * int_data[1]: starting token location
4097 * int_data[2]: token length
4098 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004099 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004100 * otherwise unused.
4101 */
4102extern "C" {
4103
4104CXTokenKind clang_getTokenKind(CXToken CXTok) {
4105 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4106}
4107
4108CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4109 switch (clang_getTokenKind(CXTok)) {
4110 case CXToken_Identifier:
4111 case CXToken_Keyword:
4112 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004113 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4114 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004115
4116 case CXToken_Literal: {
4117 // We have stashed the starting pointer in the ptr_data field. Use it.
4118 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004119 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004120 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004121
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004122 case CXToken_Punctuation:
4123 case CXToken_Comment:
4124 break;
4125 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004126
4127 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004128 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004129 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004130 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004131 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004132
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004133 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4134 std::pair<FileID, unsigned> LocInfo
4135 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004136 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004137 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004138 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4139 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004140 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004141
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004142 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004143}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004144
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004145CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004146 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004147 if (!CXXUnit)
4148 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004149
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004150 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4151 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4152}
4153
4154CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004155 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004156 if (!CXXUnit)
4157 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004158
4159 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004160 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4161}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004162
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004163void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4164 CXToken **Tokens, unsigned *NumTokens) {
4165 if (Tokens)
4166 *Tokens = 0;
4167 if (NumTokens)
4168 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004169
Ted Kremeneka60ed472010-11-16 08:15:36 +00004170 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004171 if (!CXXUnit || !Tokens || !NumTokens)
4172 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004173
Douglas Gregorbdf60622010-03-05 21:16:25 +00004174 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4175
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004176 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004177 if (R.isInvalid())
4178 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004179
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004180 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4181 std::pair<FileID, unsigned> BeginLocInfo
4182 = SourceMgr.getDecomposedLoc(R.getBegin());
4183 std::pair<FileID, unsigned> EndLocInfo
4184 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004185
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004186 // Cannot tokenize across files.
4187 if (BeginLocInfo.first != EndLocInfo.first)
4188 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004189
4190 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004191 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004192 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004193 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004194 if (Invalid)
4195 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004196
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004197 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4198 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004199 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004200 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004201
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004202 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004203 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004204 llvm::SmallVector<CXToken, 32> CXTokens;
4205 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004206 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004207 do {
4208 // Lex the next token
4209 Lex.LexFromRawLexer(Tok);
4210 if (Tok.is(tok::eof))
4211 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004212
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004213 // Initialize the CXToken.
4214 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004215
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004216 // - Common fields
4217 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4218 CXTok.int_data[2] = Tok.getLength();
4219 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004220
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004221 // - Kind-specific fields
4222 if (Tok.isLiteral()) {
4223 CXTok.int_data[0] = CXToken_Literal;
4224 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004225 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004226 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004227 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004228 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004229
David Chisnall096428b2010-10-13 21:44:48 +00004230 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004231 CXTok.int_data[0] = CXToken_Keyword;
4232 }
4233 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004234 CXTok.int_data[0] = Tok.is(tok::identifier)
4235 ? CXToken_Identifier
4236 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004237 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004238 CXTok.ptr_data = II;
4239 } else if (Tok.is(tok::comment)) {
4240 CXTok.int_data[0] = CXToken_Comment;
4241 CXTok.ptr_data = 0;
4242 } else {
4243 CXTok.int_data[0] = CXToken_Punctuation;
4244 CXTok.ptr_data = 0;
4245 }
4246 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004247 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004248 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004249
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004250 if (CXTokens.empty())
4251 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004252
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004253 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4254 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4255 *NumTokens = CXTokens.size();
4256}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004257
Ted Kremenek6db61092010-05-05 00:55:15 +00004258void clang_disposeTokens(CXTranslationUnit TU,
4259 CXToken *Tokens, unsigned NumTokens) {
4260 free(Tokens);
4261}
4262
4263} // end: extern "C"
4264
4265//===----------------------------------------------------------------------===//
4266// Token annotation APIs.
4267//===----------------------------------------------------------------------===//
4268
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004269typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004270static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4271 CXCursor parent,
4272 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004273namespace {
4274class AnnotateTokensWorker {
4275 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004276 CXToken *Tokens;
4277 CXCursor *Cursors;
4278 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004280 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004281 CursorVisitor AnnotateVis;
4282 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004283 bool HasContextSensitiveKeywords;
4284
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285 bool MoreTokens() const { return TokIdx < NumTokens; }
4286 unsigned NextToken() const { return TokIdx; }
4287 void AdvanceToken() { ++TokIdx; }
4288 SourceLocation GetTokenLoc(unsigned tokI) {
4289 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4290 }
4291
Ted Kremenek6db61092010-05-05 00:55:15 +00004292public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004293 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004294 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004295 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004296 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004297 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004298 AnnotateVis(tu,
4299 AnnotateTokensVisitor, this,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00004300 Decl::MaxPCHLevel, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004301 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4302 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004303
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004304 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004305 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004306 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004307 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004308 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004309 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004310
4311 /// \brief Determine whether the annotator saw any cursors that have
4312 /// context-sensitive keywords.
4313 bool hasContextSensitiveKeywords() const {
4314 return HasContextSensitiveKeywords;
4315 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004316};
4317}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004318
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004319void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4320 // Walk the AST within the region of interest, annotating tokens
4321 // along the way.
4322 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004323
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004324 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4325 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004326 if (Pos != Annotated.end() &&
4327 (clang_isInvalid(Cursors[I].kind) ||
4328 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004329 Cursors[I] = Pos->second;
4330 }
4331
4332 // Finish up annotating any tokens left.
4333 if (!MoreTokens())
4334 return;
4335
4336 const CXCursor &C = clang_getNullCursor();
4337 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4338 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4339 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004340 }
4341}
4342
Ted Kremenek6db61092010-05-05 00:55:15 +00004343enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004344AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004345 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004346 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004347 if (cursorRange.isInvalid())
4348 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004349
4350 if (!HasContextSensitiveKeywords) {
4351 // Objective-C properties can have context-sensitive keywords.
4352 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4353 if (ObjCPropertyDecl *Property
4354 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4355 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4356 }
4357 // Objective-C methods can have context-sensitive keywords.
4358 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4359 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4360 if (ObjCMethodDecl *Method
4361 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4362 if (Method->getObjCDeclQualifier())
4363 HasContextSensitiveKeywords = true;
4364 else {
4365 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4366 PEnd = Method->param_end();
4367 P != PEnd; ++P) {
4368 if ((*P)->getObjCDeclQualifier()) {
4369 HasContextSensitiveKeywords = true;
4370 break;
4371 }
4372 }
4373 }
4374 }
4375 }
4376 // C++ methods can have context-sensitive keywords.
4377 else if (cursor.kind == CXCursor_CXXMethod) {
4378 if (CXXMethodDecl *Method
4379 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4380 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4381 HasContextSensitiveKeywords = true;
4382 }
4383 }
4384 // C++ classes can have context-sensitive keywords.
4385 else if (cursor.kind == CXCursor_StructDecl ||
4386 cursor.kind == CXCursor_ClassDecl ||
4387 cursor.kind == CXCursor_ClassTemplate ||
4388 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4389 if (Decl *D = getCursorDecl(cursor))
4390 if (D->hasAttr<FinalAttr>())
4391 HasContextSensitiveKeywords = true;
4392 }
4393 }
4394
Douglas Gregor4419b672010-10-21 06:10:04 +00004395 if (clang_isPreprocessing(cursor.kind)) {
4396 // For macro instantiations, just note where the beginning of the macro
4397 // instantiation occurs.
4398 if (cursor.kind == CXCursor_MacroInstantiation) {
4399 Annotated[Loc.int_data] = cursor;
4400 return CXChildVisit_Recurse;
4401 }
4402
Douglas Gregor4419b672010-10-21 06:10:04 +00004403 // Items in the preprocessing record are kept separate from items in
4404 // declarations, so we keep a separate token index.
4405 unsigned SavedTokIdx = TokIdx;
4406 TokIdx = PreprocessingTokIdx;
4407
4408 // Skip tokens up until we catch up to the beginning of the preprocessing
4409 // entry.
4410 while (MoreTokens()) {
4411 const unsigned I = NextToken();
4412 SourceLocation TokLoc = GetTokenLoc(I);
4413 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4414 case RangeBefore:
4415 AdvanceToken();
4416 continue;
4417 case RangeAfter:
4418 case RangeOverlap:
4419 break;
4420 }
4421 break;
4422 }
4423
4424 // Look at all of the tokens within this range.
4425 while (MoreTokens()) {
4426 const unsigned I = NextToken();
4427 SourceLocation TokLoc = GetTokenLoc(I);
4428 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4429 case RangeBefore:
4430 assert(0 && "Infeasible");
4431 case RangeAfter:
4432 break;
4433 case RangeOverlap:
4434 Cursors[I] = cursor;
4435 AdvanceToken();
4436 continue;
4437 }
4438 break;
4439 }
4440
4441 // Save the preprocessing token index; restore the non-preprocessing
4442 // token index.
4443 PreprocessingTokIdx = TokIdx;
4444 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004445 return CXChildVisit_Recurse;
4446 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004447
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004448 if (cursorRange.isInvalid())
4449 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004450
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004451 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4452
Ted Kremeneka333c662010-05-12 05:29:33 +00004453 // Adjust the annotated range based specific declarations.
4454 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4455 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004456 Decl *D = cxcursor::getCursorDecl(cursor);
4457 // Don't visit synthesized ObjC methods, since they have no syntatic
4458 // representation in the source.
4459 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4460 if (MD->isSynthesized())
4461 return CXChildVisit_Continue;
4462 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004463
4464 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004465 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004466 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4467 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4468 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4469 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4470 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004471 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004472
4473 if (StartLoc.isValid() && L.isValid() &&
4474 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4475 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004476 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004477
Ted Kremenek3f404602010-08-14 01:14:06 +00004478 // If the location of the cursor occurs within a macro instantiation, record
4479 // the spelling location of the cursor in our annotation map. We can then
4480 // paper over the token labelings during a post-processing step to try and
4481 // get cursor mappings for tokens that are the *arguments* of a macro
4482 // instantiation.
4483 if (L.isMacroID()) {
4484 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4485 // Only invalidate the old annotation if it isn't part of a preprocessing
4486 // directive. Here we assume that the default construction of CXCursor
4487 // results in CXCursor.kind being an initialized value (i.e., 0). If
4488 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004489
Ted Kremenek3f404602010-08-14 01:14:06 +00004490 CXCursor &oldC = Annotated[rawEncoding];
4491 if (!clang_isPreprocessing(oldC.kind))
4492 oldC = cursor;
4493 }
4494
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004495 const enum CXCursorKind K = clang_getCursorKind(parent);
4496 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004497 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4498 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004499
4500 while (MoreTokens()) {
4501 const unsigned I = NextToken();
4502 SourceLocation TokLoc = GetTokenLoc(I);
4503 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4504 case RangeBefore:
4505 Cursors[I] = updateC;
4506 AdvanceToken();
4507 continue;
4508 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004509 case RangeOverlap:
4510 break;
4511 }
4512 break;
4513 }
4514
4515 // Visit children to get their cursor information.
4516 const unsigned BeforeChildren = NextToken();
4517 VisitChildren(cursor);
4518 const unsigned AfterChildren = NextToken();
4519
4520 // Adjust 'Last' to the last token within the extent of the cursor.
4521 while (MoreTokens()) {
4522 const unsigned I = NextToken();
4523 SourceLocation TokLoc = GetTokenLoc(I);
4524 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4525 case RangeBefore:
4526 assert(0 && "Infeasible");
4527 case RangeAfter:
4528 break;
4529 case RangeOverlap:
4530 Cursors[I] = updateC;
4531 AdvanceToken();
4532 continue;
4533 }
4534 break;
4535 }
4536 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004537
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004538 // Scan the tokens that are at the beginning of the cursor, but are not
4539 // capture by the child cursors.
4540
4541 // For AST elements within macros, rely on a post-annotate pass to
4542 // to correctly annotate the tokens with cursors. Otherwise we can
4543 // get confusing results of having tokens that map to cursors that really
4544 // are expanded by an instantiation.
4545 if (L.isMacroID())
4546 cursor = clang_getNullCursor();
4547
4548 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4549 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4550 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004551
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004552 Cursors[I] = cursor;
4553 }
4554 // Scan the tokens that are at the end of the cursor, but are not captured
4555 // but the child cursors.
4556 for (unsigned I = AfterChildren; I != Last; ++I)
4557 Cursors[I] = cursor;
4558
4559 TokIdx = Last;
4560 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004561}
4562
Ted Kremenek6db61092010-05-05 00:55:15 +00004563static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4564 CXCursor parent,
4565 CXClientData client_data) {
4566 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4567}
4568
Ted Kremenekab979612010-11-11 08:05:23 +00004569// This gets run a separate thread to avoid stack blowout.
4570static void runAnnotateTokensWorker(void *UserData) {
4571 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4572}
4573
Ted Kremenek6db61092010-05-05 00:55:15 +00004574extern "C" {
4575
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004576void clang_annotateTokens(CXTranslationUnit TU,
4577 CXToken *Tokens, unsigned NumTokens,
4578 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004579
4580 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004581 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004582
Douglas Gregor4419b672010-10-21 06:10:04 +00004583 // Any token we don't specifically annotate will have a NULL cursor.
4584 CXCursor C = clang_getNullCursor();
4585 for (unsigned I = 0; I != NumTokens; ++I)
4586 Cursors[I] = C;
4587
Ted Kremeneka60ed472010-11-16 08:15:36 +00004588 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00004589 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004590 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004591
Douglas Gregorbdf60622010-03-05 21:16:25 +00004592 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004593
Douglas Gregor0396f462010-03-19 05:22:59 +00004594 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004595 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004596 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4597 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004598 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4599 clang_getTokenLocation(TU,
4600 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004601
Douglas Gregor0396f462010-03-19 05:22:59 +00004602 // A mapping from the source locations found when re-lexing or traversing the
4603 // region of interest to the corresponding cursors.
4604 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004605
4606 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004607 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004608 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4609 std::pair<FileID, unsigned> BeginLocInfo
4610 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4611 std::pair<FileID, unsigned> EndLocInfo
4612 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004613
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004614 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004615 bool Invalid = false;
4616 if (BeginLocInfo.first == EndLocInfo.first &&
4617 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4618 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004619 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4620 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004621 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004622 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004623 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004624
4625 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004626 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004627 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004628 Token Tok;
4629 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004630
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004631 reprocess:
4632 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4633 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004634 // don't see it while preprocessing these tokens later, but keep track
4635 // of all of the token locations inside this preprocessing directive so
4636 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004637 //
4638 // FIXME: Some simple tests here could identify macro definitions and
4639 // #undefs, to provide specific cursor kinds for those.
4640 std::vector<SourceLocation> Locations;
4641 do {
4642 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004643 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004644 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004645
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004646 using namespace cxcursor;
4647 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004648 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4649 Locations.back()),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004650 TU);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004651 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4652 Annotated[Locations[I].getRawEncoding()] = Cursor;
4653 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004654
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004655 if (Tok.isAtStartOfLine())
4656 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004657
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004658 continue;
4659 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004660
Douglas Gregor48072312010-03-18 15:23:44 +00004661 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004662 break;
4663 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004664 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004665
Douglas Gregor0396f462010-03-19 05:22:59 +00004666 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004667 // a specific cursor.
4668 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004669 TU, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004670
4671 // Run the worker within a CrashRecoveryContext.
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004672 // FIXME: We use a ridiculous stack size here because the data-recursion
4673 // algorithm uses a large stack frame than the non-data recursive version,
4674 // and AnnotationTokensWorker currently transforms the data-recursion
4675 // algorithm back into a traditional recursion by explicitly calling
4676 // VisitChildren(). We will need to remove this explicit recursive call.
Ted Kremenekab979612010-11-11 08:05:23 +00004677 llvm::CrashRecoveryContext CRC;
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00004678 if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4679 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00004680 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4681 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004682
4683 // If we ran into any entities that involve context-sensitive keywords,
4684 // take another pass through the tokens to mark them as such.
4685 if (W.hasContextSensitiveKeywords()) {
4686 for (unsigned I = 0; I != NumTokens; ++I) {
4687 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
4688 continue;
4689
4690 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
4691 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4692 if (ObjCPropertyDecl *Property
4693 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
4694 if (Property->getPropertyAttributesAsWritten() != 0 &&
4695 llvm::StringSwitch<bool>(II->getName())
4696 .Case("readonly", true)
4697 .Case("assign", true)
4698 .Case("readwrite", true)
4699 .Case("retain", true)
4700 .Case("copy", true)
4701 .Case("nonatomic", true)
4702 .Case("atomic", true)
4703 .Case("getter", true)
4704 .Case("setter", true)
4705 .Default(false))
4706 Tokens[I].int_data[0] = CXToken_Keyword;
4707 }
4708 continue;
4709 }
4710
4711 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
4712 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
4713 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4714 if (llvm::StringSwitch<bool>(II->getName())
4715 .Case("in", true)
4716 .Case("out", true)
4717 .Case("inout", true)
4718 .Case("oneway", true)
4719 .Case("bycopy", true)
4720 .Case("byref", true)
4721 .Default(false))
4722 Tokens[I].int_data[0] = CXToken_Keyword;
4723 continue;
4724 }
4725
4726 if (Cursors[I].kind == CXCursor_CXXMethod) {
4727 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4728 if (CXXMethodDecl *Method
4729 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) {
4730 if ((Method->hasAttr<FinalAttr>() ||
4731 Method->hasAttr<OverrideAttr>()) &&
4732 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] &&
4733 llvm::StringSwitch<bool>(II->getName())
4734 .Case("final", true)
4735 .Case("override", true)
4736 .Default(false))
4737 Tokens[I].int_data[0] = CXToken_Keyword;
4738 }
4739 continue;
4740 }
4741
4742 if (Cursors[I].kind == CXCursor_ClassDecl ||
4743 Cursors[I].kind == CXCursor_StructDecl ||
4744 Cursors[I].kind == CXCursor_ClassTemplate) {
4745 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
4746 if (II->getName() == "final") {
4747 // We have to be careful with 'final', since it could be the name
4748 // of a member class rather than the context-sensitive keyword.
4749 // So, check whether the cursor associated with this
4750 Decl *D = getCursorDecl(Cursors[I]);
4751 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) {
4752 if ((Record->hasAttr<FinalAttr>()) &&
4753 Record->getIdentifier() != II)
4754 Tokens[I].int_data[0] = CXToken_Keyword;
4755 } else if (ClassTemplateDecl *ClassTemplate
4756 = dyn_cast_or_null<ClassTemplateDecl>(D)) {
4757 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl();
4758 if ((Record->hasAttr<FinalAttr>()) &&
4759 Record->getIdentifier() != II)
4760 Tokens[I].int_data[0] = CXToken_Keyword;
4761 }
4762 }
4763 continue;
4764 }
4765 }
4766 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004767}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004768} // end: extern "C"
4769
4770//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004771// Operations for querying linkage of a cursor.
4772//===----------------------------------------------------------------------===//
4773
4774extern "C" {
4775CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004776 if (!clang_isDeclaration(cursor.kind))
4777 return CXLinkage_Invalid;
4778
Ted Kremenek16b42592010-03-03 06:36:57 +00004779 Decl *D = cxcursor::getCursorDecl(cursor);
4780 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4781 switch (ND->getLinkage()) {
4782 case NoLinkage: return CXLinkage_NoLinkage;
4783 case InternalLinkage: return CXLinkage_Internal;
4784 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4785 case ExternalLinkage: return CXLinkage_External;
4786 };
4787
4788 return CXLinkage_Invalid;
4789}
4790} // end: extern "C"
4791
4792//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004793// Operations for querying language of a cursor.
4794//===----------------------------------------------------------------------===//
4795
4796static CXLanguageKind getDeclLanguage(const Decl *D) {
4797 switch (D->getKind()) {
4798 default:
4799 break;
4800 case Decl::ImplicitParam:
4801 case Decl::ObjCAtDefsField:
4802 case Decl::ObjCCategory:
4803 case Decl::ObjCCategoryImpl:
4804 case Decl::ObjCClass:
4805 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004806 case Decl::ObjCForwardProtocol:
4807 case Decl::ObjCImplementation:
4808 case Decl::ObjCInterface:
4809 case Decl::ObjCIvar:
4810 case Decl::ObjCMethod:
4811 case Decl::ObjCProperty:
4812 case Decl::ObjCPropertyImpl:
4813 case Decl::ObjCProtocol:
4814 return CXLanguage_ObjC;
4815 case Decl::CXXConstructor:
4816 case Decl::CXXConversion:
4817 case Decl::CXXDestructor:
4818 case Decl::CXXMethod:
4819 case Decl::CXXRecord:
4820 case Decl::ClassTemplate:
4821 case Decl::ClassTemplatePartialSpecialization:
4822 case Decl::ClassTemplateSpecialization:
4823 case Decl::Friend:
4824 case Decl::FriendTemplate:
4825 case Decl::FunctionTemplate:
4826 case Decl::LinkageSpec:
4827 case Decl::Namespace:
4828 case Decl::NamespaceAlias:
4829 case Decl::NonTypeTemplateParm:
4830 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004831 case Decl::TemplateTemplateParm:
4832 case Decl::TemplateTypeParm:
4833 case Decl::UnresolvedUsingTypename:
4834 case Decl::UnresolvedUsingValue:
4835 case Decl::Using:
4836 case Decl::UsingDirective:
4837 case Decl::UsingShadow:
4838 return CXLanguage_CPlusPlus;
4839 }
4840
4841 return CXLanguage_C;
4842}
4843
4844extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004845
4846enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4847 if (clang_isDeclaration(cursor.kind))
4848 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4849 if (D->hasAttr<UnavailableAttr>() ||
4850 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4851 return CXAvailability_Available;
4852
4853 if (D->hasAttr<DeprecatedAttr>())
4854 return CXAvailability_Deprecated;
4855 }
4856
4857 return CXAvailability_Available;
4858}
4859
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004860CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4861 if (clang_isDeclaration(cursor.kind))
4862 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4863
4864 return CXLanguage_Invalid;
4865}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004866
4867 /// \brief If the given cursor is the "templated" declaration
4868 /// descibing a class or function template, return the class or
4869 /// function template.
4870static Decl *maybeGetTemplateCursor(Decl *D) {
4871 if (!D)
4872 return 0;
4873
4874 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4875 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4876 return FunTmpl;
4877
4878 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4879 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4880 return ClassTmpl;
4881
4882 return D;
4883}
4884
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004885CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4886 if (clang_isDeclaration(cursor.kind)) {
4887 if (Decl *D = getCursorDecl(cursor)) {
4888 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004889 if (!DC)
4890 return clang_getNullCursor();
4891
4892 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4893 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004894 }
4895 }
4896
4897 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4898 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004899 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004900 }
4901
4902 return clang_getNullCursor();
4903}
4904
4905CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4906 if (clang_isDeclaration(cursor.kind)) {
4907 if (Decl *D = getCursorDecl(cursor)) {
4908 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00004909 if (!DC)
4910 return clang_getNullCursor();
4911
4912 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4913 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004914 }
4915 }
4916
4917 // FIXME: Note that we can't easily compute the lexical context of a
4918 // statement or expression, so we return nothing.
4919 return clang_getNullCursor();
4920}
4921
Douglas Gregor9f592342010-10-01 20:25:15 +00004922static void CollectOverriddenMethods(DeclContext *Ctx,
4923 ObjCMethodDecl *Method,
4924 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4925 if (!Ctx)
4926 return;
4927
4928 // If we have a class or category implementation, jump straight to the
4929 // interface.
4930 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4931 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4932
4933 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4934 if (!Container)
4935 return;
4936
4937 // Check whether we have a matching method at this level.
4938 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4939 Method->isInstanceMethod()))
4940 if (Method != Overridden) {
4941 // We found an override at this level; there is no need to look
4942 // into other protocols or categories.
4943 Methods.push_back(Overridden);
4944 return;
4945 }
4946
4947 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4948 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4949 PEnd = Protocol->protocol_end();
4950 P != PEnd; ++P)
4951 CollectOverriddenMethods(*P, Method, Methods);
4952 }
4953
4954 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4955 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4956 PEnd = Category->protocol_end();
4957 P != PEnd; ++P)
4958 CollectOverriddenMethods(*P, Method, Methods);
4959 }
4960
4961 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4962 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4963 PEnd = Interface->protocol_end();
4964 P != PEnd; ++P)
4965 CollectOverriddenMethods(*P, Method, Methods);
4966
4967 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4968 Category; Category = Category->getNextClassCategory())
4969 CollectOverriddenMethods(Category, Method, Methods);
4970
4971 // We only look into the superclass if we haven't found anything yet.
4972 if (Methods.empty())
4973 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4974 return CollectOverriddenMethods(Super, Method, Methods);
4975 }
4976}
4977
4978void clang_getOverriddenCursors(CXCursor cursor,
4979 CXCursor **overridden,
4980 unsigned *num_overridden) {
4981 if (overridden)
4982 *overridden = 0;
4983 if (num_overridden)
4984 *num_overridden = 0;
4985 if (!overridden || !num_overridden)
4986 return;
4987
4988 if (!clang_isDeclaration(cursor.kind))
4989 return;
4990
4991 Decl *D = getCursorDecl(cursor);
4992 if (!D)
4993 return;
4994
4995 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004996 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00004997 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4998 *num_overridden = CXXMethod->size_overridden_methods();
4999 if (!*num_overridden)
5000 return;
5001
5002 *overridden = new CXCursor [*num_overridden];
5003 unsigned I = 0;
5004 for (CXXMethodDecl::method_iterator
5005 M = CXXMethod->begin_overridden_methods(),
5006 MEnd = CXXMethod->end_overridden_methods();
5007 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005008 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005009 return;
5010 }
5011
5012 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5013 if (!Method)
5014 return;
5015
5016 // Handle Objective-C methods.
5017 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
5018 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5019
5020 if (Methods.empty())
5021 return;
5022
5023 *num_overridden = Methods.size();
5024 *overridden = new CXCursor [Methods.size()];
5025 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005026 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005027}
5028
5029void clang_disposeOverriddenCursors(CXCursor *overridden) {
5030 delete [] overridden;
5031}
5032
Douglas Gregorecdcb882010-10-20 22:00:55 +00005033CXFile clang_getIncludedFile(CXCursor cursor) {
5034 if (cursor.kind != CXCursor_InclusionDirective)
5035 return 0;
5036
5037 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5038 return (void *)ID->getFile();
5039}
5040
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005041} // end: extern "C"
5042
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005043
5044//===----------------------------------------------------------------------===//
5045// C++ AST instrospection.
5046//===----------------------------------------------------------------------===//
5047
5048extern "C" {
5049unsigned clang_CXXMethod_isStatic(CXCursor C) {
5050 if (!clang_isDeclaration(C.kind))
5051 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005052
5053 CXXMethodDecl *Method = 0;
5054 Decl *D = cxcursor::getCursorDecl(C);
5055 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5056 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5057 else
5058 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5059 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005060}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005061
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005062} // end: extern "C"
5063
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005064//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005065// Attribute introspection.
5066//===----------------------------------------------------------------------===//
5067
5068extern "C" {
5069CXType clang_getIBOutletCollectionType(CXCursor C) {
5070 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005071 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005072
5073 IBOutletCollectionAttr *A =
5074 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5075
Douglas Gregor841b2382011-03-06 18:55:32 +00005076 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005077}
5078} // end: extern "C"
5079
5080//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005081// Misc. utility functions.
5082//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005083
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005084/// Default to using an 8 MB stack size on "safety" threads.
5085static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005086
5087namespace clang {
5088
5089bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005090 void (*Fn)(void*), void *UserData,
5091 unsigned Size) {
5092 if (!Size)
5093 Size = GetSafetyThreadStackSize();
5094 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005095 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5096 return CRC.RunSafely(Fn, UserData);
5097}
5098
5099unsigned GetSafetyThreadStackSize() {
5100 return SafetyStackThreadSize;
5101}
5102
5103void SetSafetyThreadStackSize(unsigned Value) {
5104 SafetyStackThreadSize = Value;
5105}
5106
5107}
5108
Ted Kremenek04bb7162010-01-22 22:44:15 +00005109extern "C" {
5110
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005111CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005112 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005113}
5114
5115} // end: extern "C"