blob: 5748d6bdb7b7f15686d799362cbb916ef74b03e2 [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"
Douglas Gregordd3e5542011-05-04 00:14:37 +000033#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000034#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000035#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000036#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000037#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000038#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000039#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000040#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000041#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000042#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000043#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000044#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000045#include "llvm/Support/Mutex.h"
46#include "llvm/Support/Program.h"
47#include "llvm/Support/Signals.h"
48#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000049#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000050
Steve Naroff50398192009-08-28 15:28:48 +000051using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000052using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000053using namespace clang::cxstring;
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000054using namespace clang::cxtu;
Steve Naroff50398192009-08-28 15:28:48 +000055
Argyrios Kyrtzidis9049cf62011-10-12 07:07:33 +000056CXTranslationUnit cxtu::MakeCXTranslationUnit(ASTUnit *TU) {
Ted Kremeneka60ed472010-11-16 08:15:36 +000057 if (!TU)
58 return 0;
59 CXTranslationUnit D = new CXTranslationUnitImpl();
60 D->TUData = TU;
61 D->StringPool = createCXStringPool();
62 return D;
63}
64
Douglas Gregor33e9abd2010-01-22 19:49:59 +000065/// \brief The result of comparing two source ranges.
66enum RangeComparisonResult {
67 /// \brief Either the ranges overlap or one of the ranges is invalid.
68 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000069
Douglas Gregor33e9abd2010-01-22 19:49:59 +000070 /// \brief The first range ends before the second range starts.
71 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072
Douglas Gregor33e9abd2010-01-22 19:49:59 +000073 /// \brief The first range starts after the second range ends.
74 RangeAfter
75};
76
Ted Kremenekf0e23e82010-02-17 00:41:40 +000077/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000078/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000079static RangeComparisonResult RangeCompare(SourceManager &SM,
80 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000081 SourceRange R2) {
82 assert(R1.isValid() && "First range is invalid?");
83 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000084 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000085 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000086 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000088 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000089 return RangeAfter;
90 return RangeOverlap;
91}
92
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000093/// \brief Determine if a source location falls within, before, or after a
94/// a given source range.
95static RangeComparisonResult LocationCompare(SourceManager &SM,
96 SourceLocation L, SourceRange R) {
97 assert(R.isValid() && "First range is invalid?");
98 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000099 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000100 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000101 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
102 return RangeBefore;
103 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
104 return RangeAfter;
105 return RangeOverlap;
106}
107
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000108/// \brief Translate a Clang source range into a CIndex source range.
109///
110/// Clang internally represents ranges where the end location points to the
111/// start of the token at the end. However, for external clients it is more
112/// useful to have a CXSourceRange be a proper half-open interval. This routine
113/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000114CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000115 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000116 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000117 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000118 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000119 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000120 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000121 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000122 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000123 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000124 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000125 }
126
127 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
128 R.getBegin().getRawEncoding(),
129 EndLoc.getRawEncoding() };
130 return Result;
131}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000132
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000133//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000135//===----------------------------------------------------------------------===//
136
Steve Naroff89922f82009-08-31 00:59:03 +0000137namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000138
139class VisitorJob {
140public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000141 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000142 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000143 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000144 ExplicitTemplateArgsVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000145 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000146 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000147 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000148protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000149 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000150 CXCursor parent;
151 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000152 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
153 : parent(C), K(k) {
154 data[0] = d1;
155 data[1] = d2;
156 data[2] = d3;
157 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000158public:
159 Kind getKind() const { return K; }
160 const CXCursor &getParent() const { return parent; }
161 static bool classof(VisitorJob *VJ) { return true; }
162};
163
Chris Lattner5f9e2722011-07-23 10:55:15 +0000164typedef SmallVector<VisitorJob, 10> VisitorWorkList;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000165
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000167class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000168 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000169{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000171 CXTranslationUnit TU;
172 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000173
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000175 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000176
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000177 /// \brief The declaration that serves at the parent of any statement or
178 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000179 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000184 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000185 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000186
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000187 /// \brief Whether we should visit the preprocessing record entries last,
188 /// after visiting other declarations.
189 bool VisitPreprocessorLast;
190
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000191 /// \brief When valid, a source range to which the cursor should restrict
192 /// its search.
193 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000194
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000195 // FIXME: Eventually remove. This part of a hack to support proper
196 // iteration over all Decls contained lexically within an ObjC container.
197 DeclContext::decl_iterator *DI_current;
198 DeclContext::decl_iterator DE_current;
199
Ted Kremenekd1ded662010-11-15 23:31:32 +0000200 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000201 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
202 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000203
Douglas Gregorb1373d02010-01-20 20:59:29 +0000204 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000205 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000206
207 /// \brief Determine whether this particular source range comes before, comes
208 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000209 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000210 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
212
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000213 class SetParentRAII {
214 CXCursor &Parent;
215 Decl *&StmtParent;
216 CXCursor OldParent;
217
218 public:
219 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
220 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
221 {
222 Parent = NewParent;
223 if (clang_isDeclaration(Parent.kind))
224 StmtParent = getCursorDecl(Parent);
225 }
226
227 ~SetParentRAII() {
228 Parent = OldParent;
229 if (clang_isDeclaration(Parent.kind))
230 StmtParent = getCursorDecl(Parent);
231 }
232 };
233
Steve Naroff89922f82009-08-31 00:59:03 +0000234public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000235 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
236 CXClientData ClientData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000237 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000238 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000239 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
240 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor08e0bc12011-09-10 00:09:20 +0000241 VisitPreprocessorLast(VisitPreprocessorLast),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000242 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000243 {
244 Parent.kind = CXCursor_NoDeclFound;
245 Parent.data[0] = 0;
246 Parent.data[1] = 0;
247 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000248 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000249 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000250
Ted Kremenekd1ded662010-11-15 23:31:32 +0000251 ~CursorVisitor() {
252 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000253 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000254 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
255 delete *I;
256 }
257 }
258
Ted Kremeneka60ed472010-11-16 08:15:36 +0000259 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
260 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000261
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000262 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000263
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000264 bool visitPreprocessedEntitiesInRegion();
265
266 template<typename InputIterator>
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000267 bool visitPreprocessedEntities(InputIterator First, InputIterator Last);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000268
Douglas Gregorb1373d02010-01-20 20:59:29 +0000269 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000270
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000271 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000272 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000273 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000274 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000275 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000276 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000277 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000278 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
279 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000280 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000281 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000282 bool VisitClassTemplatePartialSpecializationDecl(
283 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000284 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000285 bool VisitEnumConstantDecl(EnumConstantDecl *D);
286 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
287 bool VisitFunctionDecl(FunctionDecl *ND);
288 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000289 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000290 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000291 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000292 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000293 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
295 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
296 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
297 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000298 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000299 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
300 bool VisitObjCImplDecl(ObjCImplDecl *D);
301 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
302 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000303 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
304 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
305 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000306 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000307 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000308 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000309 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000310 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000311 bool VisitUsingDecl(UsingDecl *D);
312 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
313 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000314
Douglas Gregor01829d32010-08-31 14:41:23 +0000315 // Name visitor
316 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000317 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000318 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000319
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000320 // Template visitors
321 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000322 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000323 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
324
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000325 // Type visitors
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000326#define ABSTRACT_TYPELOC(CLASS, PARENT)
327#define TYPELOC(CLASS, PARENT) \
328 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
329#include "clang/AST/TypeLocNodes.def"
330
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000332 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000333 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
334
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000335 // Data-recursive visitor functions.
336 bool IsInRegionOfInterest(CXCursor C);
337 bool RunVisitorWorkList(VisitorWorkList &WL);
338 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000339 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000340};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000341
Ted Kremenekab188932010-01-05 19:32:54 +0000342} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000343
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000344static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000345static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
346
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000347
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000348RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000349 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000350}
351
Douglas Gregorb1373d02010-01-20 20:59:29 +0000352/// \brief Visit the given cursor and, if requested by the visitor,
353/// its children.
354///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000355/// \param Cursor the cursor to visit.
356///
357/// \param CheckRegionOfInterest if true, then the caller already checked that
358/// this cursor is within the region of interest.
359///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000360/// \returns true if the visitation should be aborted, false if it
361/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363 if (clang_isInvalid(Cursor.kind))
364 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000365
Douglas Gregorb1373d02010-01-20 20:59:29 +0000366 if (clang_isDeclaration(Cursor.kind)) {
367 Decl *D = getCursorDecl(Cursor);
368 assert(D && "Invalid declaration cursor");
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000369 // Ignore implicit declarations, unless it's an objc method because
370 // currently we should report implicit methods for properties when indexing.
371 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 return false;
373 }
374
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000375 // If we have a range of interest, and this cursor doesn't intersect with it,
376 // we're done.
377 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000378 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000379 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000380 return false;
381 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000382
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383 switch (Visitor(Cursor, Parent, ClientData)) {
384 case CXChildVisit_Break:
385 return true;
386
387 case CXChildVisit_Continue:
388 return false;
389
390 case CXChildVisit_Recurse:
391 return VisitChildren(Cursor);
392 }
393
Douglas Gregorfd643772010-01-25 16:45:46 +0000394 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395}
396
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000397bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000398 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000399 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000400
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000401 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000402 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000403 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000404 Entities = PPRec.getPreprocessedEntitiesInRange(MappedRange);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000405 return visitPreprocessedEntities(Entities.first, Entities.second);
406 }
407
Douglas Gregor788f5a12010-03-20 00:41:21 +0000408 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000409 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
410
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000411 if (OnlyLocalDecls)
412 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000413
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000414 return visitPreprocessedEntities(PPRec.begin(), PPRec.end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000415}
416
417template<typename InputIterator>
418bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
419 InputIterator Last) {
420 for (; First != Last; ++First) {
421 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
422 if (Visit(MakeMacroExpansionCursor(ME, TU)))
423 return true;
424
425 continue;
426 }
427
428 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
429 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
430 return true;
431
432 continue;
433 }
434
435 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
436 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
437 return true;
438
439 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000440 }
441 }
442
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000443 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000444}
445
Douglas Gregorb1373d02010-01-20 20:59:29 +0000446/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000447///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000448/// \returns true if the visitation should be aborted, false if it
449/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000450bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000451 if (clang_isReference(Cursor.kind) &&
452 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000453 // By definition, references have no children.
454 return false;
455 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456
457 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000459 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460
Douglas Gregorb1373d02010-01-20 20:59:29 +0000461 if (clang_isDeclaration(Cursor.kind)) {
462 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000463 if (!D)
464 return false;
465
Ted Kremenek539311e2010-02-18 18:47:01 +0000466 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000468
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000469 if (clang_isStatement(Cursor.kind)) {
470 if (Stmt *S = getCursorStmt(Cursor))
471 return Visit(S);
472
473 return false;
474 }
475
476 if (clang_isExpression(Cursor.kind)) {
477 if (Expr *E = getCursorExpr(Cursor))
478 return Visit(E);
479
480 return false;
481 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000484 CXTranslationUnit tu = getCursorTU(Cursor);
485 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000486
487 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
488 for (unsigned I = 0; I != 2; ++I) {
489 if (VisitOrder[I]) {
490 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
491 RegionOfInterest.isInvalid()) {
492 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
493 TLEnd = CXXUnit->top_level_end();
494 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000495 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000496 return true;
497 }
498 } else if (VisitDeclContext(
499 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000500 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000501 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000502 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000503
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000504 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000505 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
506 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000508
Douglas Gregor7b691f332010-01-20 21:13:59 +0000509 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000510 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511
Douglas Gregorc314aa42011-03-02 19:17:03 +0000512 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
513 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
514 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
515 return Visit(BaseTSInfo->getTypeLoc());
516 }
517 }
518 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000519
520 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
521 IBOutletCollectionAttr *A =
522 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
523 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
524 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
525 A->getInterfaceLoc(), TU));
526 }
527
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 return false;
530}
531
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000532bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000533 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
534 if (Visit(TSInfo->getTypeLoc()))
535 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000536
Ted Kremenek664cffd2010-07-22 11:30:19 +0000537 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000538 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000539
540 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000541}
542
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
544 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000545 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000546 if (Range.isInvalid())
547 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000548
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000549 switch (CompareRegionOfInterest(Range)) {
550 case RangeBefore:
551 // This declaration comes before the region of interest; skip it.
552 return llvm::Optional<bool>();
553
554 case RangeAfter:
555 // This declaration comes after the region of interest; we're done.
556 return false;
557
558 case RangeOverlap:
559 // This declaration overlaps the region of interest; visit it.
560 break;
561 }
562 }
563 return true;
564}
565
566bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
567 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
568
569 // FIXME: Eventually remove. This part of a hack to support proper
570 // iteration over all Decls contained lexically within an ObjC container.
571 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
572 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
573
574 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000575 Decl *D = *I;
576 if (D->getLexicalDeclContext() != DC)
577 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000578 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000579 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
580 if (!V.hasValue())
581 continue;
582 if (!V.getValue())
583 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585 return true;
586 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000588}
589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
591 llvm_unreachable("Translation units are visited directly by Visit()");
592 return false;
593}
594
Richard Smith162e1c12011-04-15 14:24:37 +0000595bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
596 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
597 return Visit(TSInfo->getTypeLoc());
598
599 return false;
600}
601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
603 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
604 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000605
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000606 return false;
607}
608
609bool CursorVisitor::VisitTagDecl(TagDecl *D) {
610 return VisitDeclContext(D);
611}
612
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000613bool CursorVisitor::VisitClassTemplateSpecializationDecl(
614 ClassTemplateSpecializationDecl *D) {
615 bool ShouldVisitBody = false;
616 switch (D->getSpecializationKind()) {
617 case TSK_Undeclared:
618 case TSK_ImplicitInstantiation:
619 // Nothing to visit
620 return false;
621
622 case TSK_ExplicitInstantiationDeclaration:
623 case TSK_ExplicitInstantiationDefinition:
624 break;
625
626 case TSK_ExplicitSpecialization:
627 ShouldVisitBody = true;
628 break;
629 }
630
631 // Visit the template arguments used in the specialization.
632 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
633 TypeLoc TL = SpecType->getTypeLoc();
634 if (TemplateSpecializationTypeLoc *TSTLoc
635 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
636 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
637 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
638 return true;
639 }
640 }
641
642 if (ShouldVisitBody && VisitCXXRecordDecl(D))
643 return true;
644
645 return false;
646}
647
Douglas Gregor74dbe642010-08-31 19:31:58 +0000648bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
649 ClassTemplatePartialSpecializationDecl *D) {
650 // FIXME: Visit the "outer" template parameter lists on the TagDecl
651 // before visiting these template parameters.
652 if (VisitTemplateParameters(D->getTemplateParameters()))
653 return true;
654
655 // Visit the partial specialization arguments.
656 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
657 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
658 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
659 return true;
660
661 return VisitCXXRecordDecl(D);
662}
663
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000664bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000665 // Visit the default argument.
666 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
667 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
668 if (Visit(DefArg->getTypeLoc()))
669 return true;
670
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000671 return false;
672}
673
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000674bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
675 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000676 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000677 return false;
678}
679
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000680bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
681 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
682 if (Visit(TSInfo->getTypeLoc()))
683 return true;
684
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000685 // Visit the nested-name-specifier, if present.
686 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
687 if (VisitNestedNameSpecifierLoc(QualifierLoc))
688 return true;
689
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000690 return false;
691}
692
Douglas Gregora67e03f2010-09-09 21:42:20 +0000693/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000694static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
695 CXXCtorInitializer const * const *X
696 = static_cast<CXXCtorInitializer const * const *>(Xp);
697 CXXCtorInitializer const * const *Y
698 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000699
700 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
701 return -1;
702 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
703 return 1;
704 else
705 return 0;
706}
707
Douglas Gregorb1373d02010-01-20 20:59:29 +0000708bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000709 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
710 // Visit the function declaration's syntactic components in the order
711 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000712 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000713 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
714
715 // If we have a function declared directly (without the use of a typedef),
716 // visit just the return type. Otherwise, just visit the function's type
717 // now.
718 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
719 (!FTL && Visit(TL)))
720 return true;
721
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000722 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000723 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
724 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000725 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000726
727 // Visit the declaration name.
728 if (VisitDeclarationNameInfo(ND->getNameInfo()))
729 return true;
730
731 // FIXME: Visit explicitly-specified template arguments!
732
733 // Visit the function parameters, if we have a function type.
734 if (FTL && VisitFunctionTypeLoc(*FTL, true))
735 return true;
736
737 // FIXME: Attributes?
738 }
739
Sean Hunt10620eb2011-05-06 20:44:56 +0000740 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000741 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
742 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000743 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000744 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
745 IEnd = Constructor->init_end();
746 I != IEnd; ++I) {
747 if (!(*I)->isWritten())
748 continue;
749
750 WrittenInits.push_back(*I);
751 }
752
753 // Sort the initializers in source order
754 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000755 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000756
757 // Visit the initializers in source order
758 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000759 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000760 if (Init->isAnyMemberInitializer()) {
761 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000762 Init->getMemberLocation(), TU)))
763 return true;
764 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
765 if (Visit(BaseInfo->getTypeLoc()))
766 return true;
767 }
768
769 // Visit the initializer value.
770 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000771 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000772 return true;
773 }
774 }
775
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000776 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000777 return true;
778 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000779
Douglas Gregorb1373d02010-01-20 20:59:29 +0000780 return false;
781}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000782
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000783bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
784 if (VisitDeclaratorDecl(D))
785 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000788 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000789
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000790 return false;
791}
792
793bool CursorVisitor::VisitVarDecl(VarDecl *D) {
794 if (VisitDeclaratorDecl(D))
795 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000798 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000799
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000800 return false;
801}
802
Douglas Gregor84b51d72010-09-01 20:16:53 +0000803bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
804 if (VisitDeclaratorDecl(D))
805 return true;
806
807 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
808 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000809 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000810
811 return false;
812}
813
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000814bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
815 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
816 // before visiting these template parameters.
817 if (VisitTemplateParameters(D->getTemplateParameters()))
818 return true;
819
820 return VisitFunctionDecl(D->getTemplatedDecl());
821}
822
Douglas Gregor39d6f072010-08-31 19:02:00 +0000823bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
824 // FIXME: Visit the "outer" template parameter lists on the TagDecl
825 // before visiting these template parameters.
826 if (VisitTemplateParameters(D->getTemplateParameters()))
827 return true;
828
829 return VisitCXXRecordDecl(D->getTemplatedDecl());
830}
831
Douglas Gregor84b51d72010-09-01 20:16:53 +0000832bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
833 if (VisitTemplateParameters(D->getTemplateParameters()))
834 return true;
835
836 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
837 VisitTemplateArgumentLoc(D->getDefaultArgument()))
838 return true;
839
840 return false;
841}
842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000844 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
845 if (Visit(TSInfo->getTypeLoc()))
846 return true;
847
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000848 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000849 PEnd = ND->param_end();
850 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000851 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000852 return true;
853 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000854
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000856 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000858
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000859 return false;
860}
861
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000862namespace {
863 struct ContainerDeclsSort {
864 SourceManager &SM;
865 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
866 bool operator()(Decl *A, Decl *B) {
867 SourceLocation L_A = A->getLocStart();
868 SourceLocation L_B = B->getLocStart();
869 assert(L_A.isValid() && L_B.isValid());
870 return SM.isBeforeInTranslationUnit(L_A, L_B);
871 }
872 };
873}
874
Douglas Gregora59e3902010-01-21 23:27:09 +0000875bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000876 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
877 // an @implementation can lexically contain Decls that are not properly
878 // nested in the AST. When we identify such cases, we need to retrofit
879 // this nesting here.
880 if (!DI_current)
881 return VisitDeclContext(D);
882
883 // Scan the Decls that immediately come after the container
884 // in the current DeclContext. If any fall within the
885 // container's lexical region, stash them into a vector
886 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000887 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000888 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000889 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000890 if (EndLoc.isValid()) {
891 DeclContext::decl_iterator next = *DI_current;
892 while (++next != DE_current) {
893 Decl *D_next = *next;
894 if (!D_next)
895 break;
896 SourceLocation L = D_next->getLocStart();
897 if (!L.isValid())
898 break;
899 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
900 *DI_current = next;
901 DeclsInContainer.push_back(D_next);
902 continue;
903 }
904 break;
905 }
906 }
907
908 // The common case.
909 if (DeclsInContainer.empty())
910 return VisitDeclContext(D);
911
912 // Get all the Decls in the DeclContext, and sort them with the
913 // additional ones we've collected. Then visit them.
914 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
915 I!=E; ++I) {
916 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000917 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
918 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000919 continue;
920 DeclsInContainer.push_back(subDecl);
921 }
922
923 // Now sort the Decls so that they appear in lexical order.
924 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
925 ContainerDeclsSort(SM));
926
927 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000928 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000929 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000930 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000931 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
932 if (!V.hasValue())
933 continue;
934 if (!V.getValue())
935 return false;
936 if (Visit(Cursor, true))
937 return true;
938 }
939 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000940}
941
Douglas Gregorb1373d02010-01-20 20:59:29 +0000942bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000943 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
944 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000945 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000946
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000947 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
948 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
949 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000950 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000951 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000952
Douglas Gregora59e3902010-01-21 23:27:09 +0000953 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000954}
955
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000956bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
957 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
958 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
959 E = PID->protocol_end(); I != E; ++I, ++PL)
960 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
961 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000962
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000963 return VisitObjCContainerDecl(PID);
964}
965
Ted Kremenek23173d72010-05-18 21:09:07 +0000966bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000967 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000968 return true;
969
Ted Kremenek23173d72010-05-18 21:09:07 +0000970 // FIXME: This implements a workaround with @property declarations also being
971 // installed in the DeclContext for the @interface. Eventually this code
972 // should be removed.
973 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
974 if (!CDecl || !CDecl->IsClassExtension())
975 return false;
976
977 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
978 if (!ID)
979 return false;
980
981 IdentifierInfo *PropertyId = PD->getIdentifier();
982 ObjCPropertyDecl *prevDecl =
983 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
984
985 if (!prevDecl)
986 return false;
987
988 // Visit synthesized methods since they will be skipped when visiting
989 // the @interface.
990 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000991 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000992 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000993 return true;
994
995 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000996 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000997 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000998 return true;
999
1000 return false;
1001}
1002
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001004 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001005 if (D->getSuperClass() &&
1006 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001007 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001008 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001010
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001011 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1012 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1013 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001014 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001015 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001016
Douglas Gregora59e3902010-01-21 23:27:09 +00001017 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001018}
1019
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001020bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1021 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001022}
1023
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001024bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001025 // 'ID' could be null when dealing with invalid code.
1026 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1027 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1028 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001029
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001030 return VisitObjCImplDecl(D);
1031}
1032
1033bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1034#if 0
1035 // Issue callbacks for super class.
1036 // FIXME: No source location information!
1037 if (D->getSuperClass() &&
1038 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001040 TU)))
1041 return true;
1042#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001044 return VisitObjCImplDecl(D);
1045}
1046
1047bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1048 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1049 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1050 E = D->protocol_end();
1051 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001052 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001053 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001054
1055 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001056}
1057
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001058bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001059 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1060 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001062 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001063}
1064
Douglas Gregora4ffd852010-11-17 01:03:52 +00001065bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1066 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1067 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1068
1069 return false;
1070}
1071
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001072bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1073 return VisitDeclContext(D);
1074}
1075
Douglas Gregor69319002010-08-31 23:48:11 +00001076bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001078 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1079 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001080 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001081
1082 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1083 D->getTargetNameLoc(), TU));
1084}
1085
Douglas Gregor7e242562010-09-01 19:52:22 +00001086bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001088 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1089 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001090 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001091 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001092
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001093 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1094 return true;
1095
Douglas Gregor7e242562010-09-01 19:52:22 +00001096 return VisitDeclarationNameInfo(D->getNameInfo());
1097}
1098
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001099bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001101 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1102 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001103 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001104
1105 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1106 D->getIdentLocation(), TU));
1107}
1108
Douglas Gregor7e242562010-09-01 19:52:22 +00001109bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001111 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1112 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001113 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001114 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001115
Douglas Gregor7e242562010-09-01 19:52:22 +00001116 return VisitDeclarationNameInfo(D->getNameInfo());
1117}
1118
1119bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1120 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001122 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1123 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001124 return true;
1125
Douglas Gregor7e242562010-09-01 19:52:22 +00001126 return false;
1127}
1128
Douglas Gregor01829d32010-08-31 14:41:23 +00001129bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1130 switch (Name.getName().getNameKind()) {
1131 case clang::DeclarationName::Identifier:
1132 case clang::DeclarationName::CXXLiteralOperatorName:
1133 case clang::DeclarationName::CXXOperatorName:
1134 case clang::DeclarationName::CXXUsingDirective:
1135 return false;
1136
1137 case clang::DeclarationName::CXXConstructorName:
1138 case clang::DeclarationName::CXXDestructorName:
1139 case clang::DeclarationName::CXXConversionFunctionName:
1140 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1141 return Visit(TSInfo->getTypeLoc());
1142 return false;
1143
1144 case clang::DeclarationName::ObjCZeroArgSelector:
1145 case clang::DeclarationName::ObjCOneArgSelector:
1146 case clang::DeclarationName::ObjCMultiArgSelector:
1147 // FIXME: Per-identifier location info?
1148 return false;
1149 }
1150
1151 return false;
1152}
1153
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001154bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1155 SourceRange Range) {
1156 // FIXME: This whole routine is a hack to work around the lack of proper
1157 // source information in nested-name-specifiers (PR5791). Since we do have
1158 // a beginning source location, we can visit the first component of the
1159 // nested-name-specifier, if it's a single-token component.
1160 if (!NNS)
1161 return false;
1162
1163 // Get the first component in the nested-name-specifier.
1164 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1165 NNS = Prefix;
1166
1167 switch (NNS->getKind()) {
1168 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001169 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1170 TU));
1171
Douglas Gregor14aba762011-02-24 02:36:08 +00001172 case NestedNameSpecifier::NamespaceAlias:
1173 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1174 Range.getBegin(), TU));
1175
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001176 case NestedNameSpecifier::TypeSpec: {
1177 // If the type has a form where we know that the beginning of the source
1178 // range matches up with a reference cursor. Visit the appropriate reference
1179 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001180 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001181 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1182 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1183 if (const TagType *Tag = dyn_cast<TagType>(T))
1184 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1185 if (const TemplateSpecializationType *TST
1186 = dyn_cast<TemplateSpecializationType>(T))
1187 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1188 break;
1189 }
1190
1191 case NestedNameSpecifier::TypeSpecWithTemplate:
1192 case NestedNameSpecifier::Global:
1193 case NestedNameSpecifier::Identifier:
1194 break;
1195 }
1196
1197 return false;
1198}
1199
Douglas Gregordc355712011-02-25 00:36:19 +00001200bool
1201CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001202 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001203 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1204 Qualifiers.push_back(Qualifier);
1205
1206 while (!Qualifiers.empty()) {
1207 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1208 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1209 switch (NNS->getKind()) {
1210 case NestedNameSpecifier::Namespace:
1211 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001212 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001213 TU)))
1214 return true;
1215
1216 break;
1217
1218 case NestedNameSpecifier::NamespaceAlias:
1219 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001220 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001221 TU)))
1222 return true;
1223
1224 break;
1225
1226 case NestedNameSpecifier::TypeSpec:
1227 case NestedNameSpecifier::TypeSpecWithTemplate:
1228 if (Visit(Q.getTypeLoc()))
1229 return true;
1230
1231 break;
1232
1233 case NestedNameSpecifier::Global:
1234 case NestedNameSpecifier::Identifier:
1235 break;
1236 }
1237 }
1238
1239 return false;
1240}
1241
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001242bool CursorVisitor::VisitTemplateParameters(
1243 const TemplateParameterList *Params) {
1244 if (!Params)
1245 return false;
1246
1247 for (TemplateParameterList::const_iterator P = Params->begin(),
1248 PEnd = Params->end();
1249 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001250 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001251 return true;
1252 }
1253
1254 return false;
1255}
1256
Douglas Gregor0b36e612010-08-31 20:37:03 +00001257bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1258 switch (Name.getKind()) {
1259 case TemplateName::Template:
1260 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1261
1262 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001263 // Visit the overloaded template set.
1264 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1265 return true;
1266
Douglas Gregor0b36e612010-08-31 20:37:03 +00001267 return false;
1268
1269 case TemplateName::DependentTemplate:
1270 // FIXME: Visit nested-name-specifier.
1271 return false;
1272
1273 case TemplateName::QualifiedTemplate:
1274 // FIXME: Visit nested-name-specifier.
1275 return Visit(MakeCursorTemplateRef(
1276 Name.getAsQualifiedTemplateName()->getDecl(),
1277 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001278
1279 case TemplateName::SubstTemplateTemplateParm:
1280 return Visit(MakeCursorTemplateRef(
1281 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1282 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001283
1284 case TemplateName::SubstTemplateTemplateParmPack:
1285 return Visit(MakeCursorTemplateRef(
1286 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1287 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001288 }
1289
1290 return false;
1291}
1292
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001293bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1294 switch (TAL.getArgument().getKind()) {
1295 case TemplateArgument::Null:
1296 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001297 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298 return false;
1299
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300 case TemplateArgument::Type:
1301 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1302 return Visit(TSInfo->getTypeLoc());
1303 return false;
1304
1305 case TemplateArgument::Declaration:
1306 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001307 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001308 return false;
1309
1310 case TemplateArgument::Expression:
1311 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001312 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001313 return false;
1314
1315 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001316 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001317 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1318 return true;
1319
Douglas Gregora7fc9012011-01-05 18:58:31 +00001320 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001321 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001322 }
1323
1324 return false;
1325}
1326
Ted Kremeneka0536d82010-05-07 01:04:29 +00001327bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1328 return VisitDeclContext(D);
1329}
1330
Douglas Gregor01829d32010-08-31 14:41:23 +00001331bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1332 return Visit(TL.getUnqualifiedLoc());
1333}
1334
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001336 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001337
1338 // Some builtin types (such as Objective-C's "id", "sel", and
1339 // "Class") have associated declarations. Create cursors for those.
1340 QualType VisitType;
1341 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001342 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001343 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001344 case BuiltinType::Char_U:
1345 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001346 case BuiltinType::Char16:
1347 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001348 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001349 case BuiltinType::UInt:
1350 case BuiltinType::ULong:
1351 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001352 case BuiltinType::UInt128:
1353 case BuiltinType::Char_S:
1354 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001355 case BuiltinType::WChar_U:
1356 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001357 case BuiltinType::Short:
1358 case BuiltinType::Int:
1359 case BuiltinType::Long:
1360 case BuiltinType::LongLong:
1361 case BuiltinType::Int128:
1362 case BuiltinType::Float:
1363 case BuiltinType::Double:
1364 case BuiltinType::LongDouble:
1365 case BuiltinType::NullPtr:
1366 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001367 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001368 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001369 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001371
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001372 case BuiltinType::ObjCId:
1373 VisitType = Context.getObjCIdType();
1374 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001375
1376 case BuiltinType::ObjCClass:
1377 VisitType = Context.getObjCClassType();
1378 break;
1379
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001380 case BuiltinType::ObjCSel:
1381 VisitType = Context.getObjCSelType();
1382 break;
1383 }
1384
1385 if (!VisitType.isNull()) {
1386 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001387 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001388 TU));
1389 }
1390
1391 return false;
1392}
1393
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001394bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001395 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001396}
1397
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001398bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1399 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1400}
1401
1402bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001403 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001404 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001405
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001406 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1407}
1408
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001409bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001410 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001411}
1412
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001413bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1414 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1415 return true;
1416
John McCallc12c5bb2010-05-15 11:32:37 +00001417 return false;
1418}
1419
1420bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1421 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1422 return true;
1423
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001424 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1425 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1426 TU)))
1427 return true;
1428 }
1429
1430 return false;
1431}
1432
1433bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001434 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001435}
1436
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001437bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1438 return Visit(TL.getInnerLoc());
1439}
1440
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001441bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1442 return Visit(TL.getPointeeLoc());
1443}
1444
1445bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1446 return Visit(TL.getPointeeLoc());
1447}
1448
1449bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1450 return Visit(TL.getPointeeLoc());
1451}
1452
1453bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455}
1456
1457bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001458 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001459}
1460
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001461bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1462 return Visit(TL.getModifiedLoc());
1463}
1464
Douglas Gregor01829d32010-08-31 14:41:23 +00001465bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1466 bool SkipResultType) {
1467 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001468 return true;
1469
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001470 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001471 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001472 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001473 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001474
1475 return false;
1476}
1477
1478bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1479 if (Visit(TL.getElementLoc()))
1480 return true;
1481
1482 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001483 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001484
1485 return false;
1486}
1487
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001488bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1489 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001490 // Visit the template name.
1491 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1492 TL.getTemplateNameLoc()))
1493 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001494
1495 // Visit the template arguments.
1496 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1497 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1498 return true;
1499
1500 return false;
1501}
1502
Douglas Gregor2332c112010-01-21 20:48:56 +00001503bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1504 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1505}
1506
1507bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1508 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1509 return Visit(TSInfo->getTypeLoc());
1510
1511 return false;
1512}
1513
Sean Huntca63c202011-05-24 22:41:36 +00001514bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1515 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1516 return Visit(TSInfo->getTypeLoc());
1517
1518 return false;
1519}
1520
Douglas Gregor2494dd02011-03-01 01:34:45 +00001521bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1522 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1523 return true;
1524
1525 return false;
1526}
1527
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001528bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1529 DependentTemplateSpecializationTypeLoc TL) {
1530 // Visit the nested-name-specifier, if there is one.
1531 if (TL.getQualifierLoc() &&
1532 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1533 return true;
1534
1535 // Visit the template arguments.
1536 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1537 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1538 return true;
1539
1540 return false;
1541}
1542
Douglas Gregor9e876872011-03-01 18:12:44 +00001543bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1544 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1545 return true;
1546
1547 return Visit(TL.getNamedTypeLoc());
1548}
1549
Douglas Gregor7536dd52010-12-20 02:24:11 +00001550bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1551 return Visit(TL.getPatternLoc());
1552}
1553
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001554bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1555 if (Expr *E = TL.getUnderlyingExpr())
1556 return Visit(MakeCXCursor(E, StmtParent, TU));
1557
1558 return false;
1559}
1560
1561bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1562 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1563}
1564
Eli Friedmanb001de72011-10-06 23:00:33 +00001565bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1566 return Visit(TL.getValueLoc());
1567}
1568
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001569#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1570bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1571 return Visit##PARENT##Loc(TL); \
1572}
1573
1574DEFAULT_TYPELOC_IMPL(Complex, Type)
1575DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1576DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1577DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1578DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1579DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1580DEFAULT_TYPELOC_IMPL(Vector, Type)
1581DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1582DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1583DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1584DEFAULT_TYPELOC_IMPL(Record, TagType)
1585DEFAULT_TYPELOC_IMPL(Enum, TagType)
1586DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1587DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1588DEFAULT_TYPELOC_IMPL(Auto, Type)
1589
Ted Kremenek3064ef92010-08-27 21:34:58 +00001590bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001591 // Visit the nested-name-specifier, if present.
1592 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1593 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1594 return true;
1595
John McCall5e1cdac2011-10-07 06:10:15 +00001596 if (D->isCompleteDefinition()) {
Ted Kremenek3064ef92010-08-27 21:34:58 +00001597 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1598 E = D->bases_end(); I != E; ++I) {
1599 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1600 return true;
1601 }
1602 }
1603
1604 return VisitTagDecl(D);
1605}
1606
Ted Kremenek09dfa372010-02-18 05:46:33 +00001607bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001608 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1609 i != e; ++i)
1610 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001611 return true;
1612
1613 return false;
1614}
1615
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001616//===----------------------------------------------------------------------===//
1617// Data-recursive visitor methods.
1618//===----------------------------------------------------------------------===//
1619
Ted Kremenek28a71942010-11-13 00:36:47 +00001620namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001621#define DEF_JOB(NAME, DATA, KIND)\
1622class NAME : public VisitorJob {\
1623public:\
1624 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1625 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001626 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001627};
1628
1629DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1630DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001631DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001632DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001633DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001634 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001635DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001636#undef DEF_JOB
1637
1638class DeclVisit : public VisitorJob {
1639public:
1640 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1641 VisitorJob(parent, VisitorJob::DeclVisitKind,
1642 d, isFirst ? (void*) 1 : (void*) 0) {}
1643 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001644 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001645 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001646 Decl *get() const { return static_cast<Decl*>(data[0]); }
1647 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001648};
Ted Kremenek035dc412010-11-13 00:36:50 +00001649class TypeLocVisit : public VisitorJob {
1650public:
1651 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1652 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1653 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1654
1655 static bool classof(const VisitorJob *VJ) {
1656 return VJ->getKind() == TypeLocVisitKind;
1657 }
1658
Ted Kremenek82f3c502010-11-15 22:23:26 +00001659 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001660 QualType T = QualType::getFromOpaquePtr(data[0]);
1661 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001662 }
1663};
1664
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001665class LabelRefVisit : public VisitorJob {
1666public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001667 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1668 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001669 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001670
1671 static bool classof(const VisitorJob *VJ) {
1672 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1673 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001674 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001675 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001676 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001677};
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);
John Wiegley21ff2e52011-04-28 00:16:57 +00001771 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001772 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001773 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001774 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001775 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001776
Ted Kremenek28a71942010-11-13 00:36:47 +00001777private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001778 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001779 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001780 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001781 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001782 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001783 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001784 void AddTypeLoc(TypeSourceInfo *TI);
1785 void EnqueueChildren(Stmt *S);
1786};
1787} // end anonyous namespace
1788
Ted Kremenekf64d8032010-11-18 00:02:32 +00001789void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1790 // 'S' should always be non-null, since it comes from the
1791 // statement we are visiting.
1792 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1793}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001794
1795void
1796EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1797 if (Qualifier)
1798 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1799}
1800
Ted Kremenek28a71942010-11-13 00:36:47 +00001801void EnqueueVisitor::AddStmt(Stmt *S) {
1802 if (S)
1803 WL.push_back(StmtVisit(S, Parent));
1804}
Ted Kremenek035dc412010-11-13 00:36:50 +00001805void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001806 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001807 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001808}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001809void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001810 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001811 if (A)
1812 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001813 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001814}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001815void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1816 if (D)
1817 WL.push_back(MemberRefVisit(D, L, Parent));
1818}
Ted Kremenek28a71942010-11-13 00:36:47 +00001819void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1820 if (TI)
1821 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1822 }
1823void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001824 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001825 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001826 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001827 }
1828 if (size == WL.size())
1829 return;
1830 // Now reverse the entries we just added. This will match the DFS
1831 // ordering performed by the worklist.
1832 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1833 std::reverse(I, E);
1834}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001835void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1836 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1837}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001838void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1839 AddDecl(B->getBlockDecl());
1840}
Ted Kremenek28a71942010-11-13 00:36:47 +00001841void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1842 EnqueueChildren(E);
1843 AddTypeLoc(E->getTypeSourceInfo());
1844}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001845void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1846 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1847 E = S->body_rend(); I != E; ++I) {
1848 AddStmt(*I);
1849 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001850}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001851void EnqueueVisitor::
1852VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1853 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1854 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001855 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1856 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001857 if (!E->isImplicitAccess())
1858 AddStmt(E->getBase());
1859}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001860void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1861 // Enqueue the initializer or constructor arguments.
1862 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1863 AddStmt(E->getConstructorArg(I-1));
1864 // Enqueue the array size, if any.
1865 AddStmt(E->getArraySize());
1866 // Enqueue the allocated type.
1867 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1868 // Enqueue the placement arguments.
1869 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1870 AddStmt(E->getPlacementArg(I-1));
1871}
Ted Kremenek28a71942010-11-13 00:36:47 +00001872void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001873 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1874 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001875 AddStmt(CE->getCallee());
1876 AddStmt(CE->getArg(0));
1877}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001878void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1879 // Visit the name of the type being destroyed.
1880 AddTypeLoc(E->getDestroyedTypeInfo());
1881 // Visit the scope type that looks disturbingly like the nested-name-specifier
1882 // but isn't.
1883 AddTypeLoc(E->getScopeTypeInfo());
1884 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001885 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1886 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001887 // Visit base expression.
1888 AddStmt(E->getBase());
1889}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001890void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1891 AddTypeLoc(E->getTypeSourceInfo());
1892}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001893void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1894 EnqueueChildren(E);
1895 AddTypeLoc(E->getTypeSourceInfo());
1896}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001897void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1898 EnqueueChildren(E);
1899 if (E->isTypeOperand())
1900 AddTypeLoc(E->getTypeOperandSourceInfo());
1901}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001902
1903void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1904 *E) {
1905 EnqueueChildren(E);
1906 AddTypeLoc(E->getTypeSourceInfo());
1907}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001908void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1909 EnqueueChildren(E);
1910 if (E->isTypeOperand())
1911 AddTypeLoc(E->getTypeOperandSourceInfo());
1912}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001913void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001914 if (DR->hasExplicitTemplateArgs()) {
1915 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1916 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001917 WL.push_back(DeclRefExprParts(DR, Parent));
1918}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001919void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1920 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1921 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001922 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001923}
Ted Kremenek035dc412010-11-13 00:36:50 +00001924void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1925 unsigned size = WL.size();
1926 bool isFirst = true;
1927 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1928 D != DEnd; ++D) {
1929 AddDecl(*D, isFirst);
1930 isFirst = false;
1931 }
1932 if (size == WL.size())
1933 return;
1934 // Now reverse the entries we just added. This will match the DFS
1935 // ordering performed by the worklist.
1936 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1937 std::reverse(I, E);
1938}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001939void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1940 AddStmt(E->getInit());
1941 typedef DesignatedInitExpr::Designator Designator;
1942 for (DesignatedInitExpr::reverse_designators_iterator
1943 D = E->designators_rbegin(), DEnd = E->designators_rend();
1944 D != DEnd; ++D) {
1945 if (D->isFieldDesignator()) {
1946 if (FieldDecl *Field = D->getField())
1947 AddMemberRef(Field, D->getFieldLoc());
1948 continue;
1949 }
1950 if (D->isArrayDesignator()) {
1951 AddStmt(E->getArrayIndex(*D));
1952 continue;
1953 }
1954 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1955 AddStmt(E->getArrayRangeEnd(*D));
1956 AddStmt(E->getArrayRangeStart(*D));
1957 }
1958}
Ted Kremenek28a71942010-11-13 00:36:47 +00001959void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1960 EnqueueChildren(E);
1961 AddTypeLoc(E->getTypeInfoAsWritten());
1962}
1963void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1964 AddStmt(FS->getBody());
1965 AddStmt(FS->getInc());
1966 AddStmt(FS->getCond());
1967 AddDecl(FS->getConditionVariable());
1968 AddStmt(FS->getInit());
1969}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001970void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1971 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1972}
Ted Kremenek28a71942010-11-13 00:36:47 +00001973void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1974 AddStmt(If->getElse());
1975 AddStmt(If->getThen());
1976 AddStmt(If->getCond());
1977 AddDecl(If->getConditionVariable());
1978}
1979void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1980 // We care about the syntactic form of the initializer list, only.
1981 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1982 IE = Syntactic;
1983 EnqueueChildren(IE);
1984}
1985void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001986 WL.push_back(MemberExprParts(M, Parent));
1987
1988 // If the base of the member access expression is an implicit 'this', don't
1989 // visit it.
1990 // FIXME: If we ever want to show these implicit accesses, this will be
1991 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001992 if (!M->isImplicitAccess())
1993 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001994}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001995void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1996 AddTypeLoc(E->getEncodedTypeSourceInfo());
1997}
Ted Kremenek28a71942010-11-13 00:36:47 +00001998void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1999 EnqueueChildren(M);
2000 AddTypeLoc(M->getClassReceiverTypeInfo());
2001}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002002void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2003 // Visit the components of the offsetof expression.
2004 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2005 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2006 const OffsetOfNode &Node = E->getComponent(I-1);
2007 switch (Node.getKind()) {
2008 case OffsetOfNode::Array:
2009 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2010 break;
2011 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002012 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002013 break;
2014 case OffsetOfNode::Identifier:
2015 case OffsetOfNode::Base:
2016 continue;
2017 }
2018 }
2019 // Visit the type into which we're computing the offset.
2020 AddTypeLoc(E->getTypeSourceInfo());
2021}
Ted Kremenek28a71942010-11-13 00:36:47 +00002022void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002023 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002024 WL.push_back(OverloadExprParts(E, Parent));
2025}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002026void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2027 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002028 EnqueueChildren(E);
2029 if (E->isArgumentType())
2030 AddTypeLoc(E->getArgumentTypeInfo());
2031}
Ted Kremenek28a71942010-11-13 00:36:47 +00002032void EnqueueVisitor::VisitStmt(Stmt *S) {
2033 EnqueueChildren(S);
2034}
2035void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2036 AddStmt(S->getBody());
2037 AddStmt(S->getCond());
2038 AddDecl(S->getConditionVariable());
2039}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002040
Ted Kremenek28a71942010-11-13 00:36:47 +00002041void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2042 AddStmt(W->getBody());
2043 AddStmt(W->getCond());
2044 AddDecl(W->getConditionVariable());
2045}
John Wiegley21ff2e52011-04-28 00:16:57 +00002046
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002047void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2048 AddTypeLoc(E->getQueriedTypeSourceInfo());
2049}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002050
2051void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002052 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002053 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002054}
2055
John Wiegley21ff2e52011-04-28 00:16:57 +00002056void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2057 AddTypeLoc(E->getQueriedTypeSourceInfo());
2058}
2059
John Wiegley55262202011-04-25 06:54:41 +00002060void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2061 EnqueueChildren(E);
2062}
2063
Ted Kremenek28a71942010-11-13 00:36:47 +00002064void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2065 VisitOverloadExpr(U);
2066 if (!U->isImplicitAccess())
2067 AddStmt(U->getBase());
2068}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002069void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2070 AddStmt(E->getSubExpr());
2071 AddTypeLoc(E->getWrittenTypeInfo());
2072}
Douglas Gregor94d96292011-01-19 20:34:17 +00002073void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2074 WL.push_back(SizeOfPackExprParts(E, Parent));
2075}
Ted Kremenek60458782010-11-12 21:34:16 +00002076
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002077void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002078 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002079}
2080
2081bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2082 if (RegionOfInterest.isValid()) {
2083 SourceRange Range = getRawCursorExtent(C);
2084 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2085 return false;
2086 }
2087 return true;
2088}
2089
2090bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2091 while (!WL.empty()) {
2092 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002093 VisitorJob LI = WL.back();
2094 WL.pop_back();
2095
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002096 // Set the Parent field, then back to its old value once we're done.
2097 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2098
2099 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002100 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002101 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002102 if (!D)
2103 continue;
2104
2105 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002106 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2107 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002108 return true;
2109
2110 continue;
2111 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002112 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002113 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002114 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2115 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2116 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2117 Arg != ArgEnd; ++Arg) {
2118 if (VisitTemplateArgumentLoc(*Arg))
2119 return true;
2120 }
2121 continue;
2122 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002123 case VisitorJob::TypeLocVisitKind: {
2124 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002125 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002126 return true;
2127 continue;
2128 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002129 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002130 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002131 if (LabelStmt *stmt = LS->getStmt()) {
2132 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2133 TU))) {
2134 return true;
2135 }
2136 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002137 continue;
2138 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002139
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002140 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2141 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2142 if (VisitNestedNameSpecifierLoc(V->get()))
2143 return true;
2144 continue;
2145 }
2146
Ted Kremenekf64d8032010-11-18 00:02:32 +00002147 case VisitorJob::DeclarationNameInfoVisitKind: {
2148 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2149 ->get()))
2150 return true;
2151 continue;
2152 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002153 case VisitorJob::MemberRefVisitKind: {
2154 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2155 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2156 return true;
2157 continue;
2158 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002159 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002160 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002161 if (!S)
2162 continue;
2163
Ted Kremenekf1107452010-11-12 18:26:56 +00002164 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002165 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002166 if (!IsInRegionOfInterest(Cursor))
2167 continue;
2168 switch (Visitor(Cursor, Parent, ClientData)) {
2169 case CXChildVisit_Break: return true;
2170 case CXChildVisit_Continue: break;
2171 case CXChildVisit_Recurse:
2172 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002173 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002174 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002175 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002176 }
2177 case VisitorJob::MemberExprPartsKind: {
2178 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002179 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002180
2181 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002182 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2183 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002184 return true;
2185
2186 // Visit the declaration name.
2187 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2188 return true;
2189
2190 // Visit the explicitly-specified template arguments, if any.
2191 if (M->hasExplicitTemplateArgs()) {
2192 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2193 *ArgEnd = Arg + M->getNumTemplateArgs();
2194 Arg != ArgEnd; ++Arg) {
2195 if (VisitTemplateArgumentLoc(*Arg))
2196 return true;
2197 }
2198 }
2199 continue;
2200 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002201 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002202 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002203 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002204 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2205 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002206 return true;
2207 // Visit declaration name.
2208 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2209 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002210 continue;
2211 }
Ted Kremenek60458782010-11-12 21:34:16 +00002212 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002213 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002214 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002215 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2216 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002217 return true;
2218 // Visit the declaration name.
2219 if (VisitDeclarationNameInfo(O->getNameInfo()))
2220 return true;
2221 // Visit the overloaded declaration reference.
2222 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2223 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002224 continue;
2225 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002226 case VisitorJob::SizeOfPackExprPartsKind: {
2227 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2228 NamedDecl *Pack = E->getPack();
2229 if (isa<TemplateTypeParmDecl>(Pack)) {
2230 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2231 E->getPackLoc(), TU)))
2232 return true;
2233
2234 continue;
2235 }
2236
2237 if (isa<TemplateTemplateParmDecl>(Pack)) {
2238 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2239 E->getPackLoc(), TU)))
2240 return true;
2241
2242 continue;
2243 }
2244
2245 // Non-type template parameter packs and function parameter packs are
2246 // treated like DeclRefExpr cursors.
2247 continue;
2248 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002249 }
2250 }
2251 return false;
2252}
2253
Ted Kremenekcdba6592010-11-18 00:42:18 +00002254bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002255 VisitorWorkList *WL = 0;
2256 if (!WorkListFreeList.empty()) {
2257 WL = WorkListFreeList.back();
2258 WL->clear();
2259 WorkListFreeList.pop_back();
2260 }
2261 else {
2262 WL = new VisitorWorkList();
2263 WorkListCache.push_back(WL);
2264 }
2265 EnqueueWorkList(*WL, S);
2266 bool result = RunVisitorWorkList(*WL);
2267 WorkListFreeList.push_back(WL);
2268 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002269}
2270
Francois Pichet48a8d142011-07-25 22:00:44 +00002271namespace {
2272typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2273RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2274 const DeclarationNameInfo &NI,
2275 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002276 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002277 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2278 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2279 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2280
2281 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2282
2283 RefNamePieces Pieces;
2284
2285 if (WantQualifier && QLoc.isValid())
2286 Pieces.push_back(QLoc);
2287
2288 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2289 Pieces.push_back(NI.getLoc());
2290
2291 if (WantTemplateArgs && TemplateArgs)
2292 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2293 TemplateArgs->RAngleLoc));
2294
2295 if (Kind == DeclarationName::CXXOperatorName) {
2296 Pieces.push_back(SourceLocation::getFromRawEncoding(
2297 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2298 Pieces.push_back(SourceLocation::getFromRawEncoding(
2299 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2300 }
2301
2302 if (WantSinglePiece) {
2303 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2304 Pieces.clear();
2305 Pieces.push_back(R);
2306 }
2307
2308 return Pieces;
2309}
2310}
2311
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002312//===----------------------------------------------------------------------===//
2313// Misc. API hooks.
2314//===----------------------------------------------------------------------===//
2315
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002316static llvm::sys::Mutex EnableMultithreadingMutex;
2317static bool EnabledMultithreading;
2318
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002319extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002320CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2321 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002322 // Disable pretty stack trace functionality, which will otherwise be a very
2323 // poor citizen of the world and set up all sorts of signal handlers.
2324 llvm::DisablePrettyStackTrace = true;
2325
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002326 // We use crash recovery to make some of our APIs more reliable, implicitly
2327 // enable it.
2328 llvm::CrashRecoveryContext::Enable();
2329
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002330 // Enable support for multithreading in LLVM.
2331 {
2332 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2333 if (!EnabledMultithreading) {
2334 llvm::llvm_start_multithreaded();
2335 EnabledMultithreading = true;
2336 }
2337 }
2338
Douglas Gregora030b7c2010-01-22 20:35:53 +00002339 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002340 if (excludeDeclarationsFromPCH)
2341 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002342 if (displayDiagnostics)
2343 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002344 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002345}
2346
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002347void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002348 if (CIdx)
2349 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002350}
2351
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002352void clang_toggleCrashRecovery(unsigned isEnabled) {
2353 if (isEnabled)
2354 llvm::CrashRecoveryContext::Enable();
2355 else
2356 llvm::CrashRecoveryContext::Disable();
2357}
2358
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002359CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002360 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002361 if (!CIdx)
2362 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002363
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002364 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002365 FileSystemOptions FileSystemOpts;
2366 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002367
David Blaikied6471f72011-09-25 23:23:43 +00002368 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002369 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002370 CXXIdx->getOnlyLocalDecls(),
2371 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002372 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002373}
2374
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002375unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002376 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002377 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002378}
2379
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002380CXTranslationUnit
2381clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2382 const char *source_filename,
2383 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002384 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002385 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002386 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002387 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002388 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002389 return clang_parseTranslationUnit(CIdx, source_filename,
2390 command_line_args, num_command_line_args,
2391 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002392 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002393}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002394
2395struct ParseTranslationUnitInfo {
2396 CXIndex CIdx;
2397 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002398 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002399 int num_command_line_args;
2400 struct CXUnsavedFile *unsaved_files;
2401 unsigned num_unsaved_files;
2402 unsigned options;
2403 CXTranslationUnit result;
2404};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002405static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002406 ParseTranslationUnitInfo *PTUI =
2407 static_cast<ParseTranslationUnitInfo*>(UserData);
2408 CXIndex CIdx = PTUI->CIdx;
2409 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002410 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002411 int num_command_line_args = PTUI->num_command_line_args;
2412 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2413 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2414 unsigned options = PTUI->options;
2415 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002416
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002417 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002418 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002420 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2421
Douglas Gregor44c181a2010-07-23 00:33:23 +00002422 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002423 // FIXME: Add a flag for modules.
2424 TranslationUnitKind TUKind
2425 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002426 bool CacheCodeCompetionResults
2427 = options & CXTranslationUnit_CacheCompletionResults;
2428
Douglas Gregor5352ac02010-01-28 00:27:43 +00002429 // Configure the diagnostics.
2430 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002431 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002432 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2433 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002434
Ted Kremenek25a11e12011-03-22 01:15:24 +00002435 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002436 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2437 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002438 DiagCleanup(Diags.getPtr());
2439
2440 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2441 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2442
2443 // Recover resources if we crash before exiting this function.
2444 llvm::CrashRecoveryContextCleanupRegistrar<
2445 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2446
Douglas Gregor4db64a42010-01-23 00:14:00 +00002447 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002448 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002449 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002450 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002451 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2452 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002453 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002454
Ted Kremenek25a11e12011-03-22 01:15:24 +00002455 llvm::OwningPtr<std::vector<const char *> >
2456 Args(new std::vector<const char*>());
2457
2458 // Recover resources if we crash before exiting this method.
2459 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2460 ArgsCleanup(Args.get());
2461
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002462 // Since the Clang C library is primarily used by batch tools dealing with
2463 // (often very broken) source code, where spell-checking can have a
2464 // significant negative impact on performance (particularly when
2465 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002466 // Only do this if we haven't found a spell-checking-related argument.
2467 bool FoundSpellCheckingArgument = false;
2468 for (int I = 0; I != num_command_line_args; ++I) {
2469 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2470 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2471 FoundSpellCheckingArgument = true;
2472 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002473 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002474 }
2475 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002476 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002477
Ted Kremenek25a11e12011-03-22 01:15:24 +00002478 Args->insert(Args->end(), command_line_args,
2479 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002480
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002481 // The 'source_filename' argument is optional. If the caller does not
2482 // specify it then it is assumed that the source file is specified
2483 // in the actual argument list.
2484 // Put the source file after command_line_args otherwise if '-x' flag is
2485 // present it will be unused.
2486 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002487 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002488
Douglas Gregor44c181a2010-07-23 00:33:23 +00002489 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002490 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002491 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002492 Args->push_back("-Xclang");
2493 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002494 NestedMacroExpansions
2495 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002496 }
2497
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002498 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002499 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002500 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2501 /* vector::data() not portable */,
2502 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002503 Diags,
2504 CXXIdx->getClangResourcesPath(),
2505 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002506 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002507 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002508 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002509 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002510 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002511 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002512 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002513 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002514
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002515 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002516 // Make sure to check that 'Unit' is non-NULL.
2517 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2518 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2519 DEnd = Unit->stored_diag_end();
2520 D != DEnd; ++D) {
2521 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2522 CXString Msg = clang_formatDiagnostic(&Diag,
2523 clang_defaultDiagnosticDisplayOptions());
2524 fprintf(stderr, "%s\n", clang_getCString(Msg));
2525 clang_disposeString(Msg);
2526 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002527#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002528 // On Windows, force a flush, since there may be multiple copies of
2529 // stderr and stdout in the file system, all with different buffers
2530 // but writing to the same device.
2531 fflush(stderr);
2532#endif
2533 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002534 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002535
Ted Kremeneka60ed472010-11-16 08:15:36 +00002536 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002537}
2538CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2539 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002540 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002541 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002542 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002543 unsigned num_unsaved_files,
2544 unsigned options) {
2545 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002546 num_command_line_args, unsaved_files,
2547 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002548 llvm::CrashRecoveryContext CRC;
2549
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002550 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002551 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2552 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2553 fprintf(stderr, " 'command_line_args' : [");
2554 for (int i = 0; i != num_command_line_args; ++i) {
2555 if (i)
2556 fprintf(stderr, ", ");
2557 fprintf(stderr, "'%s'", command_line_args[i]);
2558 }
2559 fprintf(stderr, "],\n");
2560 fprintf(stderr, " 'unsaved_files' : [");
2561 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2562 if (i)
2563 fprintf(stderr, ", ");
2564 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2565 unsaved_files[i].Length);
2566 }
2567 fprintf(stderr, "],\n");
2568 fprintf(stderr, " 'options' : %d,\n", options);
2569 fprintf(stderr, "}\n");
2570
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002571 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002572 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2573 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002574 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002575
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002576 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002577}
2578
Douglas Gregor19998442010-08-13 15:35:05 +00002579unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2580 return CXSaveTranslationUnit_None;
2581}
2582
2583int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2584 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002585 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002586 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002587
Douglas Gregor39c411f2011-07-06 16:43:36 +00002588 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002589 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2590 PrintLibclangResourceUsage(TU);
2591 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002592}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002593
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002594void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002595 if (CTUnit) {
2596 // If the translation unit has been marked as unsafe to free, just discard
2597 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002598 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002599 return;
2600
Ted Kremeneka60ed472010-11-16 08:15:36 +00002601 delete static_cast<ASTUnit *>(CTUnit->TUData);
2602 disposeCXStringPool(CTUnit->StringPool);
2603 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002604 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002605}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002606
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002607unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2608 return CXReparse_None;
2609}
2610
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002611struct ReparseTranslationUnitInfo {
2612 CXTranslationUnit TU;
2613 unsigned num_unsaved_files;
2614 struct CXUnsavedFile *unsaved_files;
2615 unsigned options;
2616 int result;
2617};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002618
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002619static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002620 ReparseTranslationUnitInfo *RTUI =
2621 static_cast<ReparseTranslationUnitInfo*>(UserData);
2622 CXTranslationUnit TU = RTUI->TU;
2623 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2624 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2625 unsigned options = RTUI->options;
2626 (void) options;
2627 RTUI->result = 1;
2628
Douglas Gregorabc563f2010-07-19 21:46:24 +00002629 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002630 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002631
Ted Kremeneka60ed472010-11-16 08:15:36 +00002632 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002633 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002634
Ted Kremenek25a11e12011-03-22 01:15:24 +00002635 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2636 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2637
2638 // Recover resources if we crash before exiting this function.
2639 llvm::CrashRecoveryContextCleanupRegistrar<
2640 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2641
Douglas Gregorabc563f2010-07-19 21:46:24 +00002642 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002643 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002644 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002645 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002646 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2647 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002648 }
2649
Ted Kremenek4ee99262011-03-22 20:16:19 +00002650 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2651 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002652 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002653}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002654
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002655int clang_reparseTranslationUnit(CXTranslationUnit TU,
2656 unsigned num_unsaved_files,
2657 struct CXUnsavedFile *unsaved_files,
2658 unsigned options) {
2659 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2660 options, 0 };
2661 llvm::CrashRecoveryContext CRC;
2662
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002663 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002664 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002665 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002666 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002667 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2668 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002669
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002670 return RTUI.result;
2671}
2672
Douglas Gregordf95a132010-08-09 20:45:32 +00002673
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002674CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002675 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002676 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002677
Ted Kremeneka60ed472010-11-16 08:15:36 +00002678 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002679 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002680}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002681
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002682CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002683 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002684 return Result;
2685}
2686
Ted Kremenekfb480492010-01-13 21:46:36 +00002687} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002688
Ted Kremenekfb480492010-01-13 21:46:36 +00002689//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002690// CXSourceLocation and CXSourceRange Operations.
2691//===----------------------------------------------------------------------===//
2692
Douglas Gregorb9790342010-01-22 21:44:22 +00002693extern "C" {
2694CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002695 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002696 return Result;
2697}
2698
2699unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002700 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2701 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2702 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002703}
2704
2705CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2706 CXFile file,
2707 unsigned line,
2708 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002709 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002710 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002711
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002712 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002713 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Argyrios Kyrtzidis57165be2011-10-10 21:57:15 +00002714 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002715 const FileEntry *File = static_cast<const FileEntry *>(file);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002716 SourceLocation SLoc = CXXUnit->getLocation(File, line, column);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002717 if (SLoc.isInvalid()) {
2718 if (Logging)
2719 llvm::errs() << "clang_getLocation(\"" << File->getName()
2720 << "\", " << line << ", " << column << ") = invalid\n";
2721 return clang_getNullLocation();
2722 }
2723
2724 if (Logging)
2725 llvm::errs() << "clang_getLocation(\"" << File->getName()
2726 << "\", " << line << ", " << column << ") = "
2727 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002728
2729 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2730}
2731
2732CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2733 CXFile file,
2734 unsigned offset) {
2735 if (!tu || !file)
2736 return clang_getNullLocation();
2737
Ted Kremeneka60ed472010-11-16 08:15:36 +00002738 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002739 SourceLocation SLoc
2740 = CXXUnit->getLocation(static_cast<const FileEntry *>(file), offset);
David Chisnall83889a72010-10-15 17:07:39 +00002741 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002742
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002743 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002744}
2745
Douglas Gregor5352ac02010-01-28 00:27:43 +00002746CXSourceRange clang_getNullRange() {
2747 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2748 return Result;
2749}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002750
Douglas Gregor5352ac02010-01-28 00:27:43 +00002751CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2752 if (begin.ptr_data[0] != end.ptr_data[0] ||
2753 begin.ptr_data[1] != end.ptr_data[1])
2754 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002755
2756 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002757 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002758 return Result;
2759}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002760
2761unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2762{
2763 return range1.ptr_data[0] == range2.ptr_data[0]
2764 && range1.ptr_data[1] == range2.ptr_data[1]
2765 && range1.begin_int_data == range2.begin_int_data
2766 && range1.end_int_data == range2.end_int_data;
2767}
Argyrios Kyrtzidisde5db642011-09-28 18:14:21 +00002768
2769int clang_Range_isNull(CXSourceRange range) {
2770 return clang_equalRanges(range, clang_getNullRange());
2771}
2772
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002773} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002774
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002775static void createNullLocation(CXFile *file, unsigned *line,
2776 unsigned *column, unsigned *offset) {
2777 if (file)
2778 *file = 0;
2779 if (line)
2780 *line = 0;
2781 if (column)
2782 *column = 0;
2783 if (offset)
2784 *offset = 0;
2785 return;
2786}
2787
2788extern "C" {
Chandler Carruth20174222011-08-31 16:53:37 +00002789void clang_getExpansionLocation(CXSourceLocation location,
2790 CXFile *file,
2791 unsigned *line,
2792 unsigned *column,
2793 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002794 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2795
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002796 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002797 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002798 return;
2799 }
2800
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002801 const SourceManager &SM =
2802 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth20174222011-08-31 16:53:37 +00002803 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002804
Chandler Carruthcea731a2011-07-14 16:07:57 +00002805 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002806 // This can manifest in invalid code.
Chandler Carruth20174222011-08-31 16:53:37 +00002807 FileID fileID = SM.getFileID(ExpansionLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002808 bool Invalid = false;
2809 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2810 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002811 createNullLocation(file, line, column, offset);
2812 return;
2813 }
2814
Douglas Gregor1db19de2010-01-19 21:36:55 +00002815 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002816 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002817 if (line)
Chandler Carruth20174222011-08-31 16:53:37 +00002818 *line = SM.getExpansionLineNumber(ExpansionLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002819 if (column)
Chandler Carruth20174222011-08-31 16:53:37 +00002820 *column = SM.getExpansionColumnNumber(ExpansionLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002821 if (offset)
Chandler Carruth20174222011-08-31 16:53:37 +00002822 *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2823}
2824
Argyrios Kyrtzidise6be34d2011-09-13 21:49:08 +00002825void clang_getPresumedLocation(CXSourceLocation location,
2826 CXString *filename,
2827 unsigned *line,
2828 unsigned *column) {
2829 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2830
2831 if (!location.ptr_data[0] || Loc.isInvalid()) {
2832 if (filename)
2833 *filename = createCXString("");
2834 if (line)
2835 *line = 0;
2836 if (column)
2837 *column = 0;
2838 }
2839 else {
2840 const SourceManager &SM =
2841 *static_cast<const SourceManager*>(location.ptr_data[0]);
2842 PresumedLoc PreLoc = SM.getPresumedLoc(Loc);
2843
2844 if (filename)
2845 *filename = createCXString(PreLoc.getFilename());
2846 if (line)
2847 *line = PreLoc.getLine();
2848 if (column)
2849 *column = PreLoc.getColumn();
2850 }
2851}
2852
Chandler Carruth20174222011-08-31 16:53:37 +00002853void clang_getInstantiationLocation(CXSourceLocation location,
2854 CXFile *file,
2855 unsigned *line,
2856 unsigned *column,
2857 unsigned *offset) {
2858 // Redirect to new API.
2859 clang_getExpansionLocation(location, file, line, column, offset);
Douglas Gregore69517c2010-01-26 03:07:15 +00002860}
2861
Douglas Gregora9b06d42010-11-09 06:24:54 +00002862void clang_getSpellingLocation(CXSourceLocation location,
2863 CXFile *file,
2864 unsigned *line,
2865 unsigned *column,
2866 unsigned *offset) {
2867 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2868
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002869 if (!location.ptr_data[0] || Loc.isInvalid())
2870 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002871
2872 const SourceManager &SM =
2873 *static_cast<const SourceManager*>(location.ptr_data[0]);
2874 SourceLocation SpellLoc = Loc;
2875 if (SpellLoc.isMacroID()) {
2876 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2877 if (SimpleSpellingLoc.isFileID() &&
2878 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2879 SpellLoc = SimpleSpellingLoc;
2880 else
Chandler Carruth40278532011-07-25 16:49:02 +00002881 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002882 }
2883
2884 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2885 FileID FID = LocInfo.first;
2886 unsigned FileOffset = LocInfo.second;
2887
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002888 if (FID.isInvalid())
2889 return createNullLocation(file, line, column, offset);
2890
Douglas Gregora9b06d42010-11-09 06:24:54 +00002891 if (file)
2892 *file = (void *)SM.getFileEntryForID(FID);
2893 if (line)
2894 *line = SM.getLineNumber(FID, FileOffset);
2895 if (column)
2896 *column = SM.getColumnNumber(FID, FileOffset);
2897 if (offset)
2898 *offset = FileOffset;
2899}
2900
Douglas Gregor1db19de2010-01-19 21:36:55 +00002901CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002902 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002903 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002904 return Result;
2905}
2906
2907CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002908 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002909 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002910 return Result;
2911}
2912
Douglas Gregorb9790342010-01-22 21:44:22 +00002913} // end: extern "C"
2914
Douglas Gregor1db19de2010-01-19 21:36:55 +00002915//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002916// CXFile Operations.
2917//===----------------------------------------------------------------------===//
2918
2919extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002920CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002921 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002922 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002923
Steve Naroff88145032009-10-27 14:35:18 +00002924 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002925 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002926}
2927
2928time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002929 if (!SFile)
2930 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002931
Steve Naroff88145032009-10-27 14:35:18 +00002932 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2933 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002934}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002935
Douglas Gregorb9790342010-01-22 21:44:22 +00002936CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2937 if (!tu)
2938 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002939
Ted Kremeneka60ed472010-11-16 08:15:36 +00002940 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002941
Douglas Gregorb9790342010-01-22 21:44:22 +00002942 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002943 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002944}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002945
Douglas Gregordd3e5542011-05-04 00:14:37 +00002946unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2947 if (!tu || !file)
2948 return 0;
2949
2950 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2951 FileEntry *FEnt = static_cast<FileEntry *>(file);
2952 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2953 .isFileMultipleIncludeGuarded(FEnt);
2954}
2955
Ted Kremenekfb480492010-01-13 21:46:36 +00002956} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002957
Ted Kremenekfb480492010-01-13 21:46:36 +00002958//===----------------------------------------------------------------------===//
2959// CXCursor Operations.
2960//===----------------------------------------------------------------------===//
2961
Ted Kremenekfb480492010-01-13 21:46:36 +00002962static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002963 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002964 return getDeclFromExpr(CE->getSubExpr());
2965
Ted Kremenekfb480492010-01-13 21:46:36 +00002966 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2967 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002968 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2969 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002970 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2971 return ME->getMemberDecl();
2972 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2973 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002974 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002975 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002976
Ted Kremenekfb480492010-01-13 21:46:36 +00002977 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2978 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002979 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002980 if (!CE->isElidable())
2981 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002982 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2983 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002984
Douglas Gregordb1314e2010-10-01 21:11:22 +00002985 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2986 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002987 if (SubstNonTypeTemplateParmPackExpr *NTTP
2988 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2989 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002990 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2991 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2992 isa<ParmVarDecl>(SizeOfPack->getPack()))
2993 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002994
Ted Kremenekfb480492010-01-13 21:46:36 +00002995 return 0;
2996}
2997
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002998static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002999 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3000 return getLocationFromExpr(CE->getSubExpr());
3001
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003002 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3003 return /*FIXME:*/Msg->getLeftLoc();
3004 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3005 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003006 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3007 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003008 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3009 return Member->getMemberLoc();
3010 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3011 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003012 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3013 return SizeOfPack->getPackLoc();
3014
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003015 return E->getLocStart();
3016}
3017
Ted Kremenekfb480492010-01-13 21:46:36 +00003018extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003019
3020unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003021 CXCursorVisitor visitor,
3022 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003023 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003024 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003025 return CursorVis.VisitChildren(parent);
3026}
3027
David Chisnall3387c652010-11-03 14:12:26 +00003028#ifndef __has_feature
3029#define __has_feature(x) 0
3030#endif
3031#if __has_feature(blocks)
3032typedef enum CXChildVisitResult
3033 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3034
3035static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3036 CXClientData client_data) {
3037 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3038 return block(cursor, parent);
3039}
3040#else
3041// If we are compiled with a compiler that doesn't have native blocks support,
3042// define and call the block manually, so the
3043typedef struct _CXChildVisitResult
3044{
3045 void *isa;
3046 int flags;
3047 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003048 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3049 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003050} *CXCursorVisitorBlock;
3051
3052static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3053 CXClientData client_data) {
3054 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3055 return block->invoke(block, cursor, parent);
3056}
3057#endif
3058
3059
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003060unsigned clang_visitChildrenWithBlock(CXCursor parent,
3061 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003062 return clang_visitChildren(parent, visitWithBlock, block);
3063}
3064
Douglas Gregor78205d42010-01-20 21:45:58 +00003065static CXString getDeclSpelling(Decl *D) {
3066 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003067 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003068 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003069 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3070 return createCXString(Property->getIdentifier()->getName());
3071
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003072 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003073 }
3074
Douglas Gregor78205d42010-01-20 21:45:58 +00003075 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003076 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003077
Douglas Gregor78205d42010-01-20 21:45:58 +00003078 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3079 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3080 // and returns different names. NamedDecl returns the class name and
3081 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003082 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003083
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003084 if (isa<UsingDirectiveDecl>(D))
3085 return createCXString("");
3086
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003087 llvm::SmallString<1024> S;
3088 llvm::raw_svector_ostream os(S);
3089 ND->printName(os);
3090
3091 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003092}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003093
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003094CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003095 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003096 return clang_getTranslationUnitSpelling(
3097 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003098
Steve Narofff334b4e2009-09-02 18:26:48 +00003099 if (clang_isReference(C.kind)) {
3100 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003101 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003102 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003103 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003104 }
3105 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003106 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003107 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003108 }
3109 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003110 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003111 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003112 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003113 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003114 case CXCursor_CXXBaseSpecifier: {
3115 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3116 return createCXString(B->getType().getAsString());
3117 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003118 case CXCursor_TypeRef: {
3119 TypeDecl *Type = getCursorTypeRef(C).first;
3120 assert(Type && "Missing type decl");
3121
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003122 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3123 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003124 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003125 case CXCursor_TemplateRef: {
3126 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003127 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003128
3129 return createCXString(Template->getNameAsString());
3130 }
Douglas Gregor69319002010-08-31 23:48:11 +00003131
3132 case CXCursor_NamespaceRef: {
3133 NamedDecl *NS = getCursorNamespaceRef(C).first;
3134 assert(NS && "Missing namespace decl");
3135
3136 return createCXString(NS->getNameAsString());
3137 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003138
Douglas Gregora67e03f2010-09-09 21:42:20 +00003139 case CXCursor_MemberRef: {
3140 FieldDecl *Field = getCursorMemberRef(C).first;
3141 assert(Field && "Missing member decl");
3142
3143 return createCXString(Field->getNameAsString());
3144 }
3145
Douglas Gregor36897b02010-09-10 00:22:18 +00003146 case CXCursor_LabelRef: {
3147 LabelStmt *Label = getCursorLabelRef(C).first;
3148 assert(Label && "Missing label");
3149
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003150 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003151 }
3152
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003153 case CXCursor_OverloadedDeclRef: {
3154 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3155 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3156 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3157 return createCXString(ND->getNameAsString());
3158 return createCXString("");
3159 }
3160 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3161 return createCXString(E->getName().getAsString());
3162 OverloadedTemplateStorage *Ovl
3163 = Storage.get<OverloadedTemplateStorage*>();
3164 if (Ovl->size() == 0)
3165 return createCXString("");
3166 return createCXString((*Ovl->begin())->getNameAsString());
3167 }
3168
Daniel Dunbaracca7252009-11-30 20:42:49 +00003169 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003170 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003171 }
3172 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003173
3174 if (clang_isExpression(C.kind)) {
3175 Decl *D = getDeclFromExpr(getCursorExpr(C));
3176 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003177 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003178 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003179 }
3180
Douglas Gregor36897b02010-09-10 00:22:18 +00003181 if (clang_isStatement(C.kind)) {
3182 Stmt *S = getCursorStmt(C);
3183 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003184 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003185
3186 return createCXString("");
3187 }
3188
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003189 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003190 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003191 ->getNameStart());
3192
Douglas Gregor572feb22010-03-18 18:04:21 +00003193 if (C.kind == CXCursor_MacroDefinition)
3194 return createCXString(getCursorMacroDefinition(C)->getName()
3195 ->getNameStart());
3196
Douglas Gregorecdcb882010-10-20 22:00:55 +00003197 if (C.kind == CXCursor_InclusionDirective)
3198 return createCXString(getCursorInclusionDirective(C)->getFileName());
3199
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003200 if (clang_isDeclaration(C.kind))
3201 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003202
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003203 if (C.kind == CXCursor_AnnotateAttr) {
3204 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3205 return createCXString(AA->getAnnotation());
3206 }
3207
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003208 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003209}
3210
Douglas Gregor358559d2010-10-02 22:49:11 +00003211CXString clang_getCursorDisplayName(CXCursor C) {
3212 if (!clang_isDeclaration(C.kind))
3213 return clang_getCursorSpelling(C);
3214
3215 Decl *D = getCursorDecl(C);
3216 if (!D)
3217 return createCXString("");
3218
Douglas Gregor30c42402011-09-27 22:38:19 +00003219 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003220 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3221 D = FunTmpl->getTemplatedDecl();
3222
3223 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3224 llvm::SmallString<64> Str;
3225 llvm::raw_svector_ostream OS(Str);
3226 OS << Function->getNameAsString();
3227 if (Function->getPrimaryTemplate())
3228 OS << "<>";
3229 OS << "(";
3230 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3231 if (I)
3232 OS << ", ";
3233 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3234 }
3235
3236 if (Function->isVariadic()) {
3237 if (Function->getNumParams())
3238 OS << ", ";
3239 OS << "...";
3240 }
3241 OS << ")";
3242 return createCXString(OS.str());
3243 }
3244
3245 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3246 llvm::SmallString<64> Str;
3247 llvm::raw_svector_ostream OS(Str);
3248 OS << ClassTemplate->getNameAsString();
3249 OS << "<";
3250 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3251 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3252 if (I)
3253 OS << ", ";
3254
3255 NamedDecl *Param = Params->getParam(I);
3256 if (Param->getIdentifier()) {
3257 OS << Param->getIdentifier()->getName();
3258 continue;
3259 }
3260
3261 // There is no parameter name, which makes this tricky. Try to come up
3262 // with something useful that isn't too long.
3263 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3264 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3265 else if (NonTypeTemplateParmDecl *NTTP
3266 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3267 OS << NTTP->getType().getAsString(Policy);
3268 else
3269 OS << "template<...> class";
3270 }
3271
3272 OS << ">";
3273 return createCXString(OS.str());
3274 }
3275
3276 if (ClassTemplateSpecializationDecl *ClassSpec
3277 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3278 // If the type was explicitly written, use that.
3279 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3280 return createCXString(TSInfo->getType().getAsString(Policy));
3281
3282 llvm::SmallString<64> Str;
3283 llvm::raw_svector_ostream OS(Str);
3284 OS << ClassSpec->getNameAsString();
3285 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003286 ClassSpec->getTemplateArgs().data(),
3287 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003288 Policy);
3289 return createCXString(OS.str());
3290 }
3291
3292 return clang_getCursorSpelling(C);
3293}
3294
Ted Kremeneke68fff62010-02-17 00:41:32 +00003295CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003296 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003297 case CXCursor_FunctionDecl:
3298 return createCXString("FunctionDecl");
3299 case CXCursor_TypedefDecl:
3300 return createCXString("TypedefDecl");
3301 case CXCursor_EnumDecl:
3302 return createCXString("EnumDecl");
3303 case CXCursor_EnumConstantDecl:
3304 return createCXString("EnumConstantDecl");
3305 case CXCursor_StructDecl:
3306 return createCXString("StructDecl");
3307 case CXCursor_UnionDecl:
3308 return createCXString("UnionDecl");
3309 case CXCursor_ClassDecl:
3310 return createCXString("ClassDecl");
3311 case CXCursor_FieldDecl:
3312 return createCXString("FieldDecl");
3313 case CXCursor_VarDecl:
3314 return createCXString("VarDecl");
3315 case CXCursor_ParmDecl:
3316 return createCXString("ParmDecl");
3317 case CXCursor_ObjCInterfaceDecl:
3318 return createCXString("ObjCInterfaceDecl");
3319 case CXCursor_ObjCCategoryDecl:
3320 return createCXString("ObjCCategoryDecl");
3321 case CXCursor_ObjCProtocolDecl:
3322 return createCXString("ObjCProtocolDecl");
3323 case CXCursor_ObjCPropertyDecl:
3324 return createCXString("ObjCPropertyDecl");
3325 case CXCursor_ObjCIvarDecl:
3326 return createCXString("ObjCIvarDecl");
3327 case CXCursor_ObjCInstanceMethodDecl:
3328 return createCXString("ObjCInstanceMethodDecl");
3329 case CXCursor_ObjCClassMethodDecl:
3330 return createCXString("ObjCClassMethodDecl");
3331 case CXCursor_ObjCImplementationDecl:
3332 return createCXString("ObjCImplementationDecl");
3333 case CXCursor_ObjCCategoryImplDecl:
3334 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003335 case CXCursor_CXXMethod:
3336 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003337 case CXCursor_UnexposedDecl:
3338 return createCXString("UnexposedDecl");
3339 case CXCursor_ObjCSuperClassRef:
3340 return createCXString("ObjCSuperClassRef");
3341 case CXCursor_ObjCProtocolRef:
3342 return createCXString("ObjCProtocolRef");
3343 case CXCursor_ObjCClassRef:
3344 return createCXString("ObjCClassRef");
3345 case CXCursor_TypeRef:
3346 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003347 case CXCursor_TemplateRef:
3348 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003349 case CXCursor_NamespaceRef:
3350 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003351 case CXCursor_MemberRef:
3352 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003353 case CXCursor_LabelRef:
3354 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003355 case CXCursor_OverloadedDeclRef:
3356 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003357 case CXCursor_IntegerLiteral:
3358 return createCXString("IntegerLiteral");
3359 case CXCursor_FloatingLiteral:
3360 return createCXString("FloatingLiteral");
3361 case CXCursor_ImaginaryLiteral:
3362 return createCXString("ImaginaryLiteral");
3363 case CXCursor_StringLiteral:
3364 return createCXString("StringLiteral");
3365 case CXCursor_CharacterLiteral:
3366 return createCXString("CharacterLiteral");
3367 case CXCursor_ParenExpr:
3368 return createCXString("ParenExpr");
3369 case CXCursor_UnaryOperator:
3370 return createCXString("UnaryOperator");
3371 case CXCursor_ArraySubscriptExpr:
3372 return createCXString("ArraySubscriptExpr");
3373 case CXCursor_BinaryOperator:
3374 return createCXString("BinaryOperator");
3375 case CXCursor_CompoundAssignOperator:
3376 return createCXString("CompoundAssignOperator");
3377 case CXCursor_ConditionalOperator:
3378 return createCXString("ConditionalOperator");
3379 case CXCursor_CStyleCastExpr:
3380 return createCXString("CStyleCastExpr");
3381 case CXCursor_CompoundLiteralExpr:
3382 return createCXString("CompoundLiteralExpr");
3383 case CXCursor_InitListExpr:
3384 return createCXString("InitListExpr");
3385 case CXCursor_AddrLabelExpr:
3386 return createCXString("AddrLabelExpr");
3387 case CXCursor_StmtExpr:
3388 return createCXString("StmtExpr");
3389 case CXCursor_GenericSelectionExpr:
3390 return createCXString("GenericSelectionExpr");
3391 case CXCursor_GNUNullExpr:
3392 return createCXString("GNUNullExpr");
3393 case CXCursor_CXXStaticCastExpr:
3394 return createCXString("CXXStaticCastExpr");
3395 case CXCursor_CXXDynamicCastExpr:
3396 return createCXString("CXXDynamicCastExpr");
3397 case CXCursor_CXXReinterpretCastExpr:
3398 return createCXString("CXXReinterpretCastExpr");
3399 case CXCursor_CXXConstCastExpr:
3400 return createCXString("CXXConstCastExpr");
3401 case CXCursor_CXXFunctionalCastExpr:
3402 return createCXString("CXXFunctionalCastExpr");
3403 case CXCursor_CXXTypeidExpr:
3404 return createCXString("CXXTypeidExpr");
3405 case CXCursor_CXXBoolLiteralExpr:
3406 return createCXString("CXXBoolLiteralExpr");
3407 case CXCursor_CXXNullPtrLiteralExpr:
3408 return createCXString("CXXNullPtrLiteralExpr");
3409 case CXCursor_CXXThisExpr:
3410 return createCXString("CXXThisExpr");
3411 case CXCursor_CXXThrowExpr:
3412 return createCXString("CXXThrowExpr");
3413 case CXCursor_CXXNewExpr:
3414 return createCXString("CXXNewExpr");
3415 case CXCursor_CXXDeleteExpr:
3416 return createCXString("CXXDeleteExpr");
3417 case CXCursor_UnaryExpr:
3418 return createCXString("UnaryExpr");
3419 case CXCursor_ObjCStringLiteral:
3420 return createCXString("ObjCStringLiteral");
3421 case CXCursor_ObjCEncodeExpr:
3422 return createCXString("ObjCEncodeExpr");
3423 case CXCursor_ObjCSelectorExpr:
3424 return createCXString("ObjCSelectorExpr");
3425 case CXCursor_ObjCProtocolExpr:
3426 return createCXString("ObjCProtocolExpr");
3427 case CXCursor_ObjCBridgedCastExpr:
3428 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003429 case CXCursor_BlockExpr:
3430 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003431 case CXCursor_PackExpansionExpr:
3432 return createCXString("PackExpansionExpr");
3433 case CXCursor_SizeOfPackExpr:
3434 return createCXString("SizeOfPackExpr");
3435 case CXCursor_UnexposedExpr:
3436 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003437 case CXCursor_DeclRefExpr:
3438 return createCXString("DeclRefExpr");
3439 case CXCursor_MemberRefExpr:
3440 return createCXString("MemberRefExpr");
3441 case CXCursor_CallExpr:
3442 return createCXString("CallExpr");
3443 case CXCursor_ObjCMessageExpr:
3444 return createCXString("ObjCMessageExpr");
3445 case CXCursor_UnexposedStmt:
3446 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003447 case CXCursor_DeclStmt:
3448 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003449 case CXCursor_LabelStmt:
3450 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003451 case CXCursor_CompoundStmt:
3452 return createCXString("CompoundStmt");
3453 case CXCursor_CaseStmt:
3454 return createCXString("CaseStmt");
3455 case CXCursor_DefaultStmt:
3456 return createCXString("DefaultStmt");
3457 case CXCursor_IfStmt:
3458 return createCXString("IfStmt");
3459 case CXCursor_SwitchStmt:
3460 return createCXString("SwitchStmt");
3461 case CXCursor_WhileStmt:
3462 return createCXString("WhileStmt");
3463 case CXCursor_DoStmt:
3464 return createCXString("DoStmt");
3465 case CXCursor_ForStmt:
3466 return createCXString("ForStmt");
3467 case CXCursor_GotoStmt:
3468 return createCXString("GotoStmt");
3469 case CXCursor_IndirectGotoStmt:
3470 return createCXString("IndirectGotoStmt");
3471 case CXCursor_ContinueStmt:
3472 return createCXString("ContinueStmt");
3473 case CXCursor_BreakStmt:
3474 return createCXString("BreakStmt");
3475 case CXCursor_ReturnStmt:
3476 return createCXString("ReturnStmt");
3477 case CXCursor_AsmStmt:
3478 return createCXString("AsmStmt");
3479 case CXCursor_ObjCAtTryStmt:
3480 return createCXString("ObjCAtTryStmt");
3481 case CXCursor_ObjCAtCatchStmt:
3482 return createCXString("ObjCAtCatchStmt");
3483 case CXCursor_ObjCAtFinallyStmt:
3484 return createCXString("ObjCAtFinallyStmt");
3485 case CXCursor_ObjCAtThrowStmt:
3486 return createCXString("ObjCAtThrowStmt");
3487 case CXCursor_ObjCAtSynchronizedStmt:
3488 return createCXString("ObjCAtSynchronizedStmt");
3489 case CXCursor_ObjCAutoreleasePoolStmt:
3490 return createCXString("ObjCAutoreleasePoolStmt");
3491 case CXCursor_ObjCForCollectionStmt:
3492 return createCXString("ObjCForCollectionStmt");
3493 case CXCursor_CXXCatchStmt:
3494 return createCXString("CXXCatchStmt");
3495 case CXCursor_CXXTryStmt:
3496 return createCXString("CXXTryStmt");
3497 case CXCursor_CXXForRangeStmt:
3498 return createCXString("CXXForRangeStmt");
3499 case CXCursor_SEHTryStmt:
3500 return createCXString("SEHTryStmt");
3501 case CXCursor_SEHExceptStmt:
3502 return createCXString("SEHExceptStmt");
3503 case CXCursor_SEHFinallyStmt:
3504 return createCXString("SEHFinallyStmt");
3505 case CXCursor_NullStmt:
3506 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003507 case CXCursor_InvalidFile:
3508 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003509 case CXCursor_InvalidCode:
3510 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003511 case CXCursor_NoDeclFound:
3512 return createCXString("NoDeclFound");
3513 case CXCursor_NotImplemented:
3514 return createCXString("NotImplemented");
3515 case CXCursor_TranslationUnit:
3516 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003517 case CXCursor_UnexposedAttr:
3518 return createCXString("UnexposedAttr");
3519 case CXCursor_IBActionAttr:
3520 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003521 case CXCursor_IBOutletAttr:
3522 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003523 case CXCursor_IBOutletCollectionAttr:
3524 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003525 case CXCursor_CXXFinalAttr:
3526 return createCXString("attribute(final)");
3527 case CXCursor_CXXOverrideAttr:
3528 return createCXString("attribute(override)");
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00003529 case CXCursor_AnnotateAttr:
3530 return createCXString("attribute(annotate)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003531 case CXCursor_PreprocessingDirective:
3532 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003533 case CXCursor_MacroDefinition:
3534 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003535 case CXCursor_MacroExpansion:
3536 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003537 case CXCursor_InclusionDirective:
3538 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003539 case CXCursor_Namespace:
3540 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003541 case CXCursor_LinkageSpec:
3542 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003543 case CXCursor_CXXBaseSpecifier:
3544 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003545 case CXCursor_Constructor:
3546 return createCXString("CXXConstructor");
3547 case CXCursor_Destructor:
3548 return createCXString("CXXDestructor");
3549 case CXCursor_ConversionFunction:
3550 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003551 case CXCursor_TemplateTypeParameter:
3552 return createCXString("TemplateTypeParameter");
3553 case CXCursor_NonTypeTemplateParameter:
3554 return createCXString("NonTypeTemplateParameter");
3555 case CXCursor_TemplateTemplateParameter:
3556 return createCXString("TemplateTemplateParameter");
3557 case CXCursor_FunctionTemplate:
3558 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003559 case CXCursor_ClassTemplate:
3560 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003561 case CXCursor_ClassTemplatePartialSpecialization:
3562 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003563 case CXCursor_NamespaceAlias:
3564 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003565 case CXCursor_UsingDirective:
3566 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003567 case CXCursor_UsingDeclaration:
3568 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003569 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003570 return createCXString("TypeAliasDecl");
3571 case CXCursor_ObjCSynthesizeDecl:
3572 return createCXString("ObjCSynthesizeDecl");
3573 case CXCursor_ObjCDynamicDecl:
3574 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003575 case CXCursor_CXXAccessSpecifier:
3576 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003577 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003578
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003579 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003580 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003581}
Steve Naroff89922f82009-08-31 00:59:03 +00003582
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003583struct GetCursorData {
3584 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003585 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003586 CXCursor &BestCursor;
3587
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003588 GetCursorData(SourceManager &SM,
3589 SourceLocation tokenBegin, CXCursor &outputCursor)
3590 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3591 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3592 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003593};
3594
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003595static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3596 CXCursor parent,
3597 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003598 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3599 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003600
3601 // If we point inside a macro argument we should provide info of what the
3602 // token is so use the actual cursor, don't replace it with a macro expansion
3603 // cursor.
3604 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3605 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003606
3607 if (clang_isDeclaration(cursor.kind)) {
3608 // Avoid having the implicit methods override the property decls.
3609 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3610 if (MD->isImplicit())
3611 return CXChildVisit_Break;
3612 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003613
3614 if (clang_isExpression(cursor.kind) &&
3615 clang_isDeclaration(BestCursor->kind)) {
3616 Decl *D = getCursorDecl(*BestCursor);
3617
3618 // Avoid having the cursor of an expression replace the declaration cursor
3619 // when the expression source range overlaps the declaration range.
3620 // This can happen for C++ constructor expressions whose range generally
3621 // include the variable declaration, e.g.:
3622 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3623 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3624 D->getLocation() == Data->TokenBeginLoc)
3625 return CXChildVisit_Break;
3626 }
3627
Douglas Gregor93798e22010-11-05 21:11:19 +00003628 // If our current best cursor is the construction of a temporary object,
3629 // don't replace that cursor with a type reference, because we want
3630 // clang_getCursor() to point at the constructor.
3631 if (clang_isExpression(BestCursor->kind) &&
3632 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003633 cursor.kind == CXCursor_TypeRef) {
3634 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3635 // as having the actual point on the type reference.
3636 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003637 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003638 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003639
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003640 *BestCursor = cursor;
3641 return CXChildVisit_Recurse;
3642}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003643
Douglas Gregorb9790342010-01-22 21:44:22 +00003644CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3645 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003646 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003647
Ted Kremeneka60ed472010-11-16 08:15:36 +00003648 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003649 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3650
Ted Kremeneka297de22010-01-25 22:34:44 +00003651 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003652 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003653
Douglas Gregor40749ee2010-11-03 00:35:38 +00003654 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003655 if (Logging) {
3656 CXFile SearchFile;
3657 unsigned SearchLine, SearchColumn;
3658 CXFile ResultFile;
3659 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003660 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3661 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003662 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3663
Chandler Carruth20174222011-08-31 16:53:37 +00003664 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3665 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3666 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003667 SearchFileName = clang_getFileName(SearchFile);
3668 ResultFileName = clang_getFileName(ResultFile);
3669 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003670 USR = clang_getCursorUSR(Result);
3671 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003672 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3673 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003674 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3675 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003676 clang_disposeString(SearchFileName);
3677 clang_disposeString(ResultFileName);
3678 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003679 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003680
3681 CXCursor Definition = clang_getCursorDefinition(Result);
3682 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3683 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3684 CXString DefinitionKindSpelling
3685 = clang_getCursorKindSpelling(Definition.kind);
3686 CXFile DefinitionFile;
3687 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003688 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3689 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003690 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3691 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3692 clang_getCString(DefinitionKindSpelling),
3693 clang_getCString(DefinitionFileName),
3694 DefinitionLine, DefinitionColumn);
3695 clang_disposeString(DefinitionFileName);
3696 clang_disposeString(DefinitionKindSpelling);
3697 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003698 }
3699
Ted Kremeneke68fff62010-02-17 00:41:32 +00003700 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003701}
3702
Ted Kremenek73885552009-11-17 19:28:59 +00003703CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003704 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003705}
3706
3707unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003708 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003709}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003710
Douglas Gregor9ce55842010-11-20 00:09:34 +00003711unsigned clang_hashCursor(CXCursor C) {
3712 unsigned Index = 0;
3713 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3714 Index = 1;
3715
3716 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3717 std::make_pair(C.kind, C.data[Index]));
3718}
3719
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003720unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003721 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3722}
3723
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003724unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003725 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3726}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003727
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003728unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003729 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3730}
3731
Douglas Gregor97b98722010-01-19 23:20:36 +00003732unsigned clang_isExpression(enum CXCursorKind K) {
3733 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3734}
3735
3736unsigned clang_isStatement(enum CXCursorKind K) {
3737 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3738}
3739
Douglas Gregor8be80e12011-07-06 03:00:34 +00003740unsigned clang_isAttribute(enum CXCursorKind K) {
3741 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3742}
3743
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003744unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3745 return K == CXCursor_TranslationUnit;
3746}
3747
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003748unsigned clang_isPreprocessing(enum CXCursorKind K) {
3749 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3750}
3751
Ted Kremenekad6eff62010-03-08 21:17:29 +00003752unsigned clang_isUnexposed(enum CXCursorKind K) {
3753 switch (K) {
3754 case CXCursor_UnexposedDecl:
3755 case CXCursor_UnexposedExpr:
3756 case CXCursor_UnexposedStmt:
3757 case CXCursor_UnexposedAttr:
3758 return true;
3759 default:
3760 return false;
3761 }
3762}
3763
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003764CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003765 return C.kind;
3766}
3767
Douglas Gregor98258af2010-01-18 22:46:11 +00003768CXSourceLocation clang_getCursorLocation(CXCursor C) {
3769 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003770 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003771 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003772 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3773 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003774 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003775 }
3776
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003777 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003778 std::pair<ObjCProtocolDecl *, SourceLocation> P
3779 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003780 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003781 }
3782
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003783 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003784 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3785 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003786 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003787 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003788
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003789 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003790 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003791 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003792 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003793
3794 case CXCursor_TemplateRef: {
3795 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3796 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3797 }
3798
Douglas Gregor69319002010-08-31 23:48:11 +00003799 case CXCursor_NamespaceRef: {
3800 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3801 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3802 }
3803
Douglas Gregora67e03f2010-09-09 21:42:20 +00003804 case CXCursor_MemberRef: {
3805 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3806 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3807 }
3808
Ted Kremenek3064ef92010-08-27 21:34:58 +00003809 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003810 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3811 if (!BaseSpec)
3812 return clang_getNullLocation();
3813
3814 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3815 return cxloc::translateSourceLocation(getCursorContext(C),
3816 TSInfo->getTypeLoc().getBeginLoc());
3817
3818 return cxloc::translateSourceLocation(getCursorContext(C),
3819 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003820 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003821
Douglas Gregor36897b02010-09-10 00:22:18 +00003822 case CXCursor_LabelRef: {
3823 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3824 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3825 }
3826
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003827 case CXCursor_OverloadedDeclRef:
3828 return cxloc::translateSourceLocation(getCursorContext(C),
3829 getCursorOverloadedDeclRef(C).second);
3830
Douglas Gregorf46034a2010-01-18 23:41:10 +00003831 default:
3832 // FIXME: Need a way to enumerate all non-reference cases.
3833 llvm_unreachable("Missed a reference kind");
3834 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003835 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003836
3837 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003838 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003839 getLocationFromExpr(getCursorExpr(C)));
3840
Douglas Gregor36897b02010-09-10 00:22:18 +00003841 if (clang_isStatement(C.kind))
3842 return cxloc::translateSourceLocation(getCursorContext(C),
3843 getCursorStmt(C)->getLocStart());
3844
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003845 if (C.kind == CXCursor_PreprocessingDirective) {
3846 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3847 return cxloc::translateSourceLocation(getCursorContext(C), L);
3848 }
Douglas Gregor48072312010-03-18 15:23:44 +00003849
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003850 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003851 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003852 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003853 return cxloc::translateSourceLocation(getCursorContext(C), L);
3854 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003855
3856 if (C.kind == CXCursor_MacroDefinition) {
3857 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3858 return cxloc::translateSourceLocation(getCursorContext(C), L);
3859 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003860
3861 if (C.kind == CXCursor_InclusionDirective) {
3862 SourceLocation L
3863 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3864 return cxloc::translateSourceLocation(getCursorContext(C), L);
3865 }
3866
Ted Kremenek9a700d22010-05-12 06:16:13 +00003867 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003868 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003869
Douglas Gregorf46034a2010-01-18 23:41:10 +00003870 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003871 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003872 // FIXME: Multiple variables declared in a single declaration
3873 // currently lack the information needed to correctly determine their
3874 // ranges when accounting for the type-specifier. We use context
3875 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3876 // and if so, whether it is the first decl.
3877 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3878 if (!cxcursor::isFirstInDeclGroup(C))
3879 Loc = VD->getLocation();
3880 }
3881
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003882 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003883}
Douglas Gregora7bde202010-01-19 00:34:46 +00003884
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003885} // end extern "C"
3886
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003887CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3888 assert(TU);
3889
3890 // Guard against an invalid SourceLocation, or we may assert in one
3891 // of the following calls.
3892 if (SLoc.isInvalid())
3893 return clang_getNullCursor();
3894
3895 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3896
3897 // Translate the given source location to make it point at the beginning of
3898 // the token under the cursor.
3899 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3900 CXXUnit->getASTContext().getLangOptions());
3901
3902 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3903 if (SLoc.isValid()) {
3904 // FIXME: Would be great to have a "hint" cursor, then walk from that
3905 // hint cursor upward until we find a cursor whose source range encloses
3906 // the region of interest, rather than starting from the translation unit.
3907 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
3908 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3909 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3910 /*VisitPreprocessorLast=*/true,
3911 SourceLocation(SLoc));
3912 CursorVis.VisitChildren(Parent);
3913 }
3914
3915 return Result;
3916}
3917
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003918static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003919 if (clang_isReference(C.kind)) {
3920 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003921 case CXCursor_ObjCSuperClassRef:
3922 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003923
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003924 case CXCursor_ObjCProtocolRef:
3925 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003926
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003927 case CXCursor_ObjCClassRef:
3928 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003929
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003930 case CXCursor_TypeRef:
3931 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003932
3933 case CXCursor_TemplateRef:
3934 return getCursorTemplateRef(C).second;
3935
Douglas Gregor69319002010-08-31 23:48:11 +00003936 case CXCursor_NamespaceRef:
3937 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003938
3939 case CXCursor_MemberRef:
3940 return getCursorMemberRef(C).second;
3941
Ted Kremenek3064ef92010-08-27 21:34:58 +00003942 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003943 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003944
Douglas Gregor36897b02010-09-10 00:22:18 +00003945 case CXCursor_LabelRef:
3946 return getCursorLabelRef(C).second;
3947
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003948 case CXCursor_OverloadedDeclRef:
3949 return getCursorOverloadedDeclRef(C).second;
3950
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003951 default:
3952 // FIXME: Need a way to enumerate all non-reference cases.
3953 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003954 }
3955 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003956
3957 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003958 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003959
3960 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003961 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003962
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003963 if (clang_isAttribute(C.kind))
3964 return getCursorAttr(C)->getRange();
3965
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003966 if (C.kind == CXCursor_PreprocessingDirective)
3967 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003968
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003969 if (C.kind == CXCursor_MacroExpansion) {
3970 ASTUnit *TU = getCursorASTUnit(C);
3971 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3972 return TU->mapRangeFromPreamble(Range);
3973 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003974
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003975 if (C.kind == CXCursor_MacroDefinition) {
3976 ASTUnit *TU = getCursorASTUnit(C);
3977 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3978 return TU->mapRangeFromPreamble(Range);
3979 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003980
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003981 if (C.kind == CXCursor_InclusionDirective) {
3982 ASTUnit *TU = getCursorASTUnit(C);
3983 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3984 return TU->mapRangeFromPreamble(Range);
3985 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003986
Ted Kremenek007a7c92010-11-01 23:26:51 +00003987 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3988 Decl *D = cxcursor::getCursorDecl(C);
3989 SourceRange R = D->getSourceRange();
3990 // FIXME: Multiple variables declared in a single declaration
3991 // currently lack the information needed to correctly determine their
3992 // ranges when accounting for the type-specifier. We use context
3993 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3994 // and if so, whether it is the first decl.
3995 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3996 if (!cxcursor::isFirstInDeclGroup(C))
3997 R.setBegin(VD->getLocation());
3998 }
3999 return R;
4000 }
Douglas Gregor66537982010-11-17 17:14:07 +00004001 return SourceRange();
4002}
4003
4004/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4005/// the decl-specifier-seq for declarations.
4006static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4007 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4008 Decl *D = cxcursor::getCursorDecl(C);
4009 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004010
Douglas Gregor2494dd02011-03-01 01:34:45 +00004011 // Adjust the start of the location for declarations preceded by
4012 // declaration specifiers.
4013 SourceLocation StartLoc;
4014 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4015 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4016 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4017 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4018 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4019 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4020 }
4021
4022 if (StartLoc.isValid() && R.getBegin().isValid() &&
4023 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4024 R.setBegin(StartLoc);
4025
4026 // FIXME: Multiple variables declared in a single declaration
4027 // currently lack the information needed to correctly determine their
4028 // ranges when accounting for the type-specifier. We use context
4029 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4030 // and if so, whether it is the first decl.
4031 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4032 if (!cxcursor::isFirstInDeclGroup(C))
4033 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004034 }
4035
4036 return R;
4037 }
4038
4039 return getRawCursorExtent(C);
4040}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004041
4042extern "C" {
4043
4044CXSourceRange clang_getCursorExtent(CXCursor C) {
4045 SourceRange R = getRawCursorExtent(C);
4046 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004047 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004048
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004049 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004050}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004051
4052CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004053 if (clang_isInvalid(C.kind))
4054 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004055
Ted Kremeneka60ed472010-11-16 08:15:36 +00004056 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004057 if (clang_isDeclaration(C.kind)) {
4058 Decl *D = getCursorDecl(C);
4059 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004060 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004061 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004062 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004063 if (ObjCForwardProtocolDecl *Protocols
4064 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004065 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004066 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004067 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4068 return MakeCXCursor(Property, tu);
4069
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004070 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004071 }
4072
Douglas Gregor97b98722010-01-19 23:20:36 +00004073 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004074 Expr *E = getCursorExpr(C);
4075 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004076 if (D) {
4077 CXCursor declCursor = MakeCXCursor(D, tu);
4078 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4079 declCursor);
4080 return declCursor;
4081 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004082
4083 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004084 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004085
Douglas Gregor97b98722010-01-19 23:20:36 +00004086 return clang_getNullCursor();
4087 }
4088
Douglas Gregor36897b02010-09-10 00:22:18 +00004089 if (clang_isStatement(C.kind)) {
4090 Stmt *S = getCursorStmt(C);
4091 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004092 if (LabelDecl *label = Goto->getLabel())
4093 if (LabelStmt *labelS = label->getStmt())
4094 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004095
4096 return clang_getNullCursor();
4097 }
4098
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004099 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004100 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004101 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004102 }
4103
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004104 if (!clang_isReference(C.kind))
4105 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004106
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004107 switch (C.kind) {
4108 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004109 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004110
4111 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004112 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004113
4114 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004115 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004116
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004117 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004118 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004119
4120 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004121 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004122
Douglas Gregor69319002010-08-31 23:48:11 +00004123 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004124 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004125
Douglas Gregora67e03f2010-09-09 21:42:20 +00004126 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004127 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004128
Ted Kremenek3064ef92010-08-27 21:34:58 +00004129 case CXCursor_CXXBaseSpecifier: {
4130 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4131 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004132 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004133 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004134
Douglas Gregor36897b02010-09-10 00:22:18 +00004135 case CXCursor_LabelRef:
4136 // FIXME: We end up faking the "parent" declaration here because we
4137 // don't want to make CXCursor larger.
4138 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004139 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4140 .getTranslationUnitDecl(),
4141 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004142
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004143 case CXCursor_OverloadedDeclRef:
4144 return C;
4145
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004146 default:
4147 // We would prefer to enumerate all non-reference cursor kinds here.
4148 llvm_unreachable("Unhandled reference cursor kind");
4149 break;
4150 }
4151 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004152
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004153 return clang_getNullCursor();
4154}
4155
Douglas Gregorb6998662010-01-19 19:34:47 +00004156CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004157 if (clang_isInvalid(C.kind))
4158 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004159
Ted Kremeneka60ed472010-11-16 08:15:36 +00004160 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004161
Douglas Gregorb6998662010-01-19 19:34:47 +00004162 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004163 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004164 C = clang_getCursorReferenced(C);
4165 WasReference = true;
4166 }
4167
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004168 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004169 return clang_getCursorReferenced(C);
4170
Douglas Gregorb6998662010-01-19 19:34:47 +00004171 if (!clang_isDeclaration(C.kind))
4172 return clang_getNullCursor();
4173
4174 Decl *D = getCursorDecl(C);
4175 if (!D)
4176 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004177
Douglas Gregorb6998662010-01-19 19:34:47 +00004178 switch (D->getKind()) {
4179 // Declaration kinds that don't really separate the notions of
4180 // declaration and definition.
4181 case Decl::Namespace:
4182 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004183 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004184 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004185 case Decl::TemplateTypeParm:
4186 case Decl::EnumConstant:
4187 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004188 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004189 case Decl::ObjCIvar:
4190 case Decl::ObjCAtDefsField:
4191 case Decl::ImplicitParam:
4192 case Decl::ParmVar:
4193 case Decl::NonTypeTemplateParm:
4194 case Decl::TemplateTemplateParm:
4195 case Decl::ObjCCategoryImpl:
4196 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004197 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004198 case Decl::LinkageSpec:
4199 case Decl::ObjCPropertyImpl:
4200 case Decl::FileScopeAsm:
4201 case Decl::StaticAssert:
4202 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004203 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004204 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004205 return C;
4206
4207 // Declaration kinds that don't make any sense here, but are
4208 // nonetheless harmless.
4209 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004210 break;
4211
4212 // Declaration kinds for which the definition is not resolvable.
4213 case Decl::UnresolvedUsingTypename:
4214 case Decl::UnresolvedUsingValue:
4215 break;
4216
4217 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004218 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004219 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004220
4221 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004222 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004223
4224 case Decl::Enum:
4225 case Decl::Record:
4226 case Decl::CXXRecord:
4227 case Decl::ClassTemplateSpecialization:
4228 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004229 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004230 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004231 return clang_getNullCursor();
4232
4233 case Decl::Function:
4234 case Decl::CXXMethod:
4235 case Decl::CXXConstructor:
4236 case Decl::CXXDestructor:
4237 case Decl::CXXConversion: {
4238 const FunctionDecl *Def = 0;
4239 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004240 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004241 return clang_getNullCursor();
4242 }
4243
4244 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004245 // Ask the variable if it has a definition.
4246 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004247 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004248 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004249 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004250
Douglas Gregorb6998662010-01-19 19:34:47 +00004251 case Decl::FunctionTemplate: {
4252 const FunctionDecl *Def = 0;
4253 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004254 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004255 return clang_getNullCursor();
4256 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004257
Douglas Gregorb6998662010-01-19 19:34:47 +00004258 case Decl::ClassTemplate: {
4259 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004260 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004261 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004262 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004263 return clang_getNullCursor();
4264 }
4265
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004266 case Decl::Using:
4267 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004268 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004269
4270 case Decl::UsingShadow:
4271 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004272 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004273 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004274
4275 case Decl::ObjCMethod: {
4276 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4277 if (Method->isThisDeclarationADefinition())
4278 return C;
4279
4280 // Dig out the method definition in the associated
4281 // @implementation, if we have it.
4282 // FIXME: The ASTs should make finding the definition easier.
4283 if (ObjCInterfaceDecl *Class
4284 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4285 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4286 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4287 Method->isInstanceMethod()))
4288 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004289 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004290
4291 return clang_getNullCursor();
4292 }
4293
4294 case Decl::ObjCCategory:
4295 if (ObjCCategoryImplDecl *Impl
4296 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004297 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004298 return clang_getNullCursor();
4299
4300 case Decl::ObjCProtocol:
4301 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4302 return C;
4303 return clang_getNullCursor();
4304
4305 case Decl::ObjCInterface:
4306 // There are two notions of a "definition" for an Objective-C
4307 // class: the interface and its implementation. When we resolved a
4308 // reference to an Objective-C class, produce the @interface as
4309 // the definition; when we were provided with the interface,
4310 // produce the @implementation as the definition.
4311 if (WasReference) {
4312 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4313 return C;
4314 } else if (ObjCImplementationDecl *Impl
4315 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004316 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004317 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004318
Douglas Gregorb6998662010-01-19 19:34:47 +00004319 case Decl::ObjCProperty:
4320 // FIXME: We don't really know where to find the
4321 // ObjCPropertyImplDecls that implement this property.
4322 return clang_getNullCursor();
4323
4324 case Decl::ObjCCompatibleAlias:
4325 if (ObjCInterfaceDecl *Class
4326 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4327 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004328 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004329
Douglas Gregorb6998662010-01-19 19:34:47 +00004330 return clang_getNullCursor();
4331
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004332 case Decl::ObjCForwardProtocol:
4333 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004334 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004335
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004336 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004337 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004338 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004339
4340 case Decl::Friend:
4341 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004342 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004343 return clang_getNullCursor();
4344
4345 case Decl::FriendTemplate:
4346 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004347 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004348 return clang_getNullCursor();
4349 }
4350
4351 return clang_getNullCursor();
4352}
4353
4354unsigned clang_isCursorDefinition(CXCursor C) {
4355 if (!clang_isDeclaration(C.kind))
4356 return 0;
4357
4358 return clang_getCursorDefinition(C) == C;
4359}
4360
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004361CXCursor clang_getCanonicalCursor(CXCursor C) {
4362 if (!clang_isDeclaration(C.kind))
4363 return C;
4364
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004365 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004366 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4367 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4368 return MakeCXCursor(CatD, getCursorTU(C));
4369
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004370 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4371 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4372 return MakeCXCursor(IFD, getCursorTU(C));
4373
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004374 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004375 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004376
4377 return C;
4378}
4379
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004380unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004381 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004382 return 0;
4383
4384 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4385 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4386 return E->getNumDecls();
4387
4388 if (OverloadedTemplateStorage *S
4389 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4390 return S->size();
4391
4392 Decl *D = Storage.get<Decl*>();
4393 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004394 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004395 if (isa<ObjCClassDecl>(D))
4396 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004397 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4398 return Protocols->protocol_size();
4399
4400 return 0;
4401}
4402
4403CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004404 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004405 return clang_getNullCursor();
4406
4407 if (index >= clang_getNumOverloadedDecls(cursor))
4408 return clang_getNullCursor();
4409
Ted Kremeneka60ed472010-11-16 08:15:36 +00004410 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004411 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4412 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004413 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004414
4415 if (OverloadedTemplateStorage *S
4416 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004417 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004418
4419 Decl *D = Storage.get<Decl*>();
4420 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4421 // FIXME: This is, unfortunately, linear time.
4422 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4423 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004424 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004425 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004426 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004427 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004428 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004429 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004430
4431 return clang_getNullCursor();
4432}
4433
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004434void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004435 const char **startBuf,
4436 const char **endBuf,
4437 unsigned *startLine,
4438 unsigned *startColumn,
4439 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004440 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004441 assert(getCursorDecl(C) && "CXCursor has null decl");
4442 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004443 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4444 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004445
Steve Naroff4ade6d62009-09-23 17:52:52 +00004446 SourceManager &SM = FD->getASTContext().getSourceManager();
4447 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4448 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4449 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4450 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4451 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4452 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4453}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004454
Douglas Gregor430d7a12011-07-25 17:48:11 +00004455
4456CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4457 unsigned PieceIndex) {
4458 RefNamePieces Pieces;
4459
4460 switch (C.kind) {
4461 case CXCursor_MemberRefExpr:
4462 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4463 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4464 E->getQualifierLoc().getSourceRange());
4465 break;
4466
4467 case CXCursor_DeclRefExpr:
4468 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4469 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4470 E->getQualifierLoc().getSourceRange(),
4471 E->getExplicitTemplateArgsOpt());
4472 break;
4473
4474 case CXCursor_CallExpr:
4475 if (CXXOperatorCallExpr *OCE =
4476 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4477 Expr *Callee = OCE->getCallee();
4478 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4479 Callee = ICE->getSubExpr();
4480
4481 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4482 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4483 DRE->getQualifierLoc().getSourceRange());
4484 }
4485 break;
4486
4487 default:
4488 break;
4489 }
4490
4491 if (Pieces.empty()) {
4492 if (PieceIndex == 0)
4493 return clang_getCursorExtent(C);
4494 } else if (PieceIndex < Pieces.size()) {
4495 SourceRange R = Pieces[PieceIndex];
4496 if (R.isValid())
4497 return cxloc::translateSourceRange(getCursorContext(C), R);
4498 }
4499
4500 return clang_getNullRange();
4501}
4502
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004503void clang_enableStackTraces(void) {
4504 llvm::sys::PrintStackTraceOnErrorSignal();
4505}
4506
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004507void clang_executeOnThread(void (*fn)(void*), void *user_data,
4508 unsigned stack_size) {
4509 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4510}
4511
Ted Kremenekfb480492010-01-13 21:46:36 +00004512} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004513
Ted Kremenekfb480492010-01-13 21:46:36 +00004514//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004515// Token-based Operations.
4516//===----------------------------------------------------------------------===//
4517
4518/* CXToken layout:
4519 * int_data[0]: a CXTokenKind
4520 * int_data[1]: starting token location
4521 * int_data[2]: token length
4522 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004523 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004524 * otherwise unused.
4525 */
4526extern "C" {
4527
4528CXTokenKind clang_getTokenKind(CXToken CXTok) {
4529 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4530}
4531
4532CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4533 switch (clang_getTokenKind(CXTok)) {
4534 case CXToken_Identifier:
4535 case CXToken_Keyword:
4536 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004537 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4538 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004539
4540 case CXToken_Literal: {
4541 // We have stashed the starting pointer in the ptr_data field. Use it.
4542 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004543 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004544 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004545
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004546 case CXToken_Punctuation:
4547 case CXToken_Comment:
4548 break;
4549 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004550
4551 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004552 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004553 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004554 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004555 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004556
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004557 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4558 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004559 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004560 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004561 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004562 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4563 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004564 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004565
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004566 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004567}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004568
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004569CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004570 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004571 if (!CXXUnit)
4572 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004573
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004574 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4575 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4576}
4577
4578CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004579 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004580 if (!CXXUnit)
4581 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004582
4583 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004584 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4585}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004586
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004587static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4588 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004589 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4590 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004591 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004592 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004593 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004594
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004595 // Cannot tokenize across files.
4596 if (BeginLocInfo.first != EndLocInfo.first)
4597 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004598
4599 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004600 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004601 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004602 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004603 if (Invalid)
4604 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004605
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004606 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4607 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004608 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004609 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004610
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004611 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004612 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004613 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004614 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004615 do {
4616 // Lex the next token
4617 Lex.LexFromRawLexer(Tok);
4618 if (Tok.is(tok::eof))
4619 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004620
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004621 // Initialize the CXToken.
4622 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004623
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004624 // - Common fields
4625 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4626 CXTok.int_data[2] = Tok.getLength();
4627 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004628
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004629 // - Kind-specific fields
4630 if (Tok.isLiteral()) {
4631 CXTok.int_data[0] = CXToken_Literal;
4632 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004633 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004634 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004635 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004636 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004637
David Chisnall096428b2010-10-13 21:44:48 +00004638 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004639 CXTok.int_data[0] = CXToken_Keyword;
4640 }
4641 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004642 CXTok.int_data[0] = Tok.is(tok::identifier)
4643 ? CXToken_Identifier
4644 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004645 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004646 CXTok.ptr_data = II;
4647 } else if (Tok.is(tok::comment)) {
4648 CXTok.int_data[0] = CXToken_Comment;
4649 CXTok.ptr_data = 0;
4650 } else {
4651 CXTok.int_data[0] = CXToken_Punctuation;
4652 CXTok.ptr_data = 0;
4653 }
4654 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004655 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004656 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004657}
4658
4659void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4660 CXToken **Tokens, unsigned *NumTokens) {
4661 if (Tokens)
4662 *Tokens = 0;
4663 if (NumTokens)
4664 *NumTokens = 0;
4665
4666 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4667 if (!CXXUnit || !Tokens || !NumTokens)
4668 return;
4669
4670 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4671
4672 SourceRange R = cxloc::translateCXSourceRange(Range);
4673 if (R.isInvalid())
4674 return;
4675
4676 SmallVector<CXToken, 32> CXTokens;
4677 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004678
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004679 if (CXTokens.empty())
4680 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004681
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004682 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4683 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4684 *NumTokens = CXTokens.size();
4685}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004686
Ted Kremenek6db61092010-05-05 00:55:15 +00004687void clang_disposeTokens(CXTranslationUnit TU,
4688 CXToken *Tokens, unsigned NumTokens) {
4689 free(Tokens);
4690}
4691
4692} // end: extern "C"
4693
4694//===----------------------------------------------------------------------===//
4695// Token annotation APIs.
4696//===----------------------------------------------------------------------===//
4697
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004698typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004699static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4700 CXCursor parent,
4701 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004702namespace {
4703class AnnotateTokensWorker {
4704 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004705 CXToken *Tokens;
4706 CXCursor *Cursors;
4707 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004708 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004709 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004710 CursorVisitor AnnotateVis;
4711 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004712 bool HasContextSensitiveKeywords;
4713
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004714 bool MoreTokens() const { return TokIdx < NumTokens; }
4715 unsigned NextToken() const { return TokIdx; }
4716 void AdvanceToken() { ++TokIdx; }
4717 SourceLocation GetTokenLoc(unsigned tokI) {
4718 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4719 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004720 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004721 return Tokens[tokI].int_data[3] != 0;
4722 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004723 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004724 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4725 }
4726
4727 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004728 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4729 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004730
Ted Kremenek6db61092010-05-05 00:55:15 +00004731public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004732 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004733 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004734 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004735 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004736 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004737 AnnotateVis(tu,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00004738 AnnotateTokensVisitor, this, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004739 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4740 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004741
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004742 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004743 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004744 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004745 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004746 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004747 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004748
4749 /// \brief Determine whether the annotator saw any cursors that have
4750 /// context-sensitive keywords.
4751 bool hasContextSensitiveKeywords() const {
4752 return HasContextSensitiveKeywords;
4753 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004754};
4755}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004756
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004757void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4758 // Walk the AST within the region of interest, annotating tokens
4759 // along the way.
4760 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004761
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004762 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4763 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004764 if (Pos != Annotated.end() &&
4765 (clang_isInvalid(Cursors[I].kind) ||
4766 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004767 Cursors[I] = Pos->second;
4768 }
4769
4770 // Finish up annotating any tokens left.
4771 if (!MoreTokens())
4772 return;
4773
4774 const CXCursor &C = clang_getNullCursor();
4775 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4776 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4777 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004778 }
4779}
4780
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004781/// \brief It annotates and advances tokens with a cursor until the comparison
4782//// between the cursor location and the source range is the same as
4783/// \arg compResult.
4784///
4785/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4786/// Pass RangeOverlap to annotate tokens inside a range.
4787void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4788 RangeComparisonResult compResult,
4789 SourceRange range) {
4790 while (MoreTokens()) {
4791 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004792 if (isFunctionMacroToken(I))
4793 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004794
4795 SourceLocation TokLoc = GetTokenLoc(I);
4796 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4797 Cursors[I] = updateC;
4798 AdvanceToken();
4799 continue;
4800 }
4801 break;
4802 }
4803}
4804
4805/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004806void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4807 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004808 RangeComparisonResult compResult,
4809 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004810 assert(MoreTokens());
4811 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004812 "Should be called only for macro arg tokens");
4813
4814 // This works differently than annotateAndAdvanceTokens; because expanded
4815 // macro arguments can have arbitrary translation-unit source order, we do not
4816 // advance the token index one by one until a token fails the range test.
4817 // We only advance once past all of the macro arg tokens if all of them
4818 // pass the range test. If one of them fails we keep the token index pointing
4819 // at the start of the macro arg tokens so that the failing token will be
4820 // annotated by a subsequent annotation try.
4821
4822 bool atLeastOneCompFail = false;
4823
4824 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004825 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4826 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004827 if (TokLoc.isFileID())
4828 continue; // not macro arg token, it's parens or comma.
4829 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4830 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4831 Cursors[I] = updateC;
4832 } else
4833 atLeastOneCompFail = true;
4834 }
4835
4836 if (!atLeastOneCompFail)
4837 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4838}
4839
Ted Kremenek6db61092010-05-05 00:55:15 +00004840enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004841AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004842 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004843 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004844 if (cursorRange.isInvalid())
4845 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004846
4847 if (!HasContextSensitiveKeywords) {
4848 // Objective-C properties can have context-sensitive keywords.
4849 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4850 if (ObjCPropertyDecl *Property
4851 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4852 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4853 }
4854 // Objective-C methods can have context-sensitive keywords.
4855 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4856 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4857 if (ObjCMethodDecl *Method
4858 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4859 if (Method->getObjCDeclQualifier())
4860 HasContextSensitiveKeywords = true;
4861 else {
4862 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4863 PEnd = Method->param_end();
4864 P != PEnd; ++P) {
4865 if ((*P)->getObjCDeclQualifier()) {
4866 HasContextSensitiveKeywords = true;
4867 break;
4868 }
4869 }
4870 }
4871 }
4872 }
4873 // C++ methods can have context-sensitive keywords.
4874 else if (cursor.kind == CXCursor_CXXMethod) {
4875 if (CXXMethodDecl *Method
4876 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4877 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4878 HasContextSensitiveKeywords = true;
4879 }
4880 }
4881 // C++ classes can have context-sensitive keywords.
4882 else if (cursor.kind == CXCursor_StructDecl ||
4883 cursor.kind == CXCursor_ClassDecl ||
4884 cursor.kind == CXCursor_ClassTemplate ||
4885 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4886 if (Decl *D = getCursorDecl(cursor))
4887 if (D->hasAttr<FinalAttr>())
4888 HasContextSensitiveKeywords = true;
4889 }
4890 }
4891
Douglas Gregor4419b672010-10-21 06:10:04 +00004892 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004893 // For macro expansions, just note where the beginning of the macro
4894 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004895 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004896 Annotated[Loc.int_data] = cursor;
4897 return CXChildVisit_Recurse;
4898 }
4899
Douglas Gregor4419b672010-10-21 06:10:04 +00004900 // Items in the preprocessing record are kept separate from items in
4901 // declarations, so we keep a separate token index.
4902 unsigned SavedTokIdx = TokIdx;
4903 TokIdx = PreprocessingTokIdx;
4904
4905 // Skip tokens up until we catch up to the beginning of the preprocessing
4906 // entry.
4907 while (MoreTokens()) {
4908 const unsigned I = NextToken();
4909 SourceLocation TokLoc = GetTokenLoc(I);
4910 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4911 case RangeBefore:
4912 AdvanceToken();
4913 continue;
4914 case RangeAfter:
4915 case RangeOverlap:
4916 break;
4917 }
4918 break;
4919 }
4920
4921 // Look at all of the tokens within this range.
4922 while (MoreTokens()) {
4923 const unsigned I = NextToken();
4924 SourceLocation TokLoc = GetTokenLoc(I);
4925 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4926 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004927 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004928 case RangeAfter:
4929 break;
4930 case RangeOverlap:
4931 Cursors[I] = cursor;
4932 AdvanceToken();
4933 continue;
4934 }
4935 break;
4936 }
4937
4938 // Save the preprocessing token index; restore the non-preprocessing
4939 // token index.
4940 PreprocessingTokIdx = TokIdx;
4941 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004942 return CXChildVisit_Recurse;
4943 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004944
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004945 if (cursorRange.isInvalid())
4946 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004947
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004948 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4949
Ted Kremeneka333c662010-05-12 05:29:33 +00004950 // Adjust the annotated range based specific declarations.
4951 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4952 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004953 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004954
4955 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004956 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004957 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4958 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4959 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4960 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4961 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004962 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004963
4964 if (StartLoc.isValid() && L.isValid() &&
4965 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4966 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004967 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004968
Ted Kremenek3f404602010-08-14 01:14:06 +00004969 // If the location of the cursor occurs within a macro instantiation, record
4970 // the spelling location of the cursor in our annotation map. We can then
4971 // paper over the token labelings during a post-processing step to try and
4972 // get cursor mappings for tokens that are the *arguments* of a macro
4973 // instantiation.
4974 if (L.isMacroID()) {
4975 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4976 // Only invalidate the old annotation if it isn't part of a preprocessing
4977 // directive. Here we assume that the default construction of CXCursor
4978 // results in CXCursor.kind being an initialized value (i.e., 0). If
4979 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004980
Ted Kremenek3f404602010-08-14 01:14:06 +00004981 CXCursor &oldC = Annotated[rawEncoding];
4982 if (!clang_isPreprocessing(oldC.kind))
4983 oldC = cursor;
4984 }
4985
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004986 const enum CXCursorKind K = clang_getCursorKind(parent);
4987 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004988 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4989 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004990
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004991 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004992
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004993 // Avoid having the cursor of an expression "overwrite" the annotation of the
4994 // variable declaration that it belongs to.
4995 // This can happen for C++ constructor expressions whose range generally
4996 // include the variable declaration, e.g.:
4997 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4998 if (clang_isExpression(cursorK)) {
4999 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00005000 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00005001 const unsigned I = NextToken();
5002 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5003 E->getLocStart() == D->getLocation() &&
5004 E->getLocStart() == GetTokenLoc(I)) {
5005 Cursors[I] = updateC;
5006 AdvanceToken();
5007 }
5008 }
5009 }
5010
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005011 // Visit children to get their cursor information.
5012 const unsigned BeforeChildren = NextToken();
5013 VisitChildren(cursor);
5014 const unsigned AfterChildren = NextToken();
5015
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005016 // Scan the tokens that are at the end of the cursor, but are not captured
5017 // but the child cursors.
5018 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005019
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005020 // Scan the tokens that are at the beginning of the cursor, but are not
5021 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005022 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5023 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5024 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005025
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005026 Cursors[I] = cursor;
5027 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005028
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005029 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005030}
5031
Ted Kremenek6db61092010-05-05 00:55:15 +00005032static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5033 CXCursor parent,
5034 CXClientData client_data) {
5035 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5036}
5037
Ted Kremenek6628a612011-03-18 22:51:30 +00005038namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005039
5040/// \brief Uses the macro expansions in the preprocessing record to find
5041/// and mark tokens that are macro arguments. This info is used by the
5042/// AnnotateTokensWorker.
5043class MarkMacroArgTokensVisitor {
5044 SourceManager &SM;
5045 CXToken *Tokens;
5046 unsigned NumTokens;
5047 unsigned CurIdx;
5048
5049public:
5050 MarkMacroArgTokensVisitor(SourceManager &SM,
5051 CXToken *tokens, unsigned numTokens)
5052 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5053
5054 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5055 if (cursor.kind != CXCursor_MacroExpansion)
5056 return CXChildVisit_Continue;
5057
5058 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5059 if (macroRange.getBegin() == macroRange.getEnd())
5060 return CXChildVisit_Continue; // it's not a function macro.
5061
5062 for (; CurIdx < NumTokens; ++CurIdx) {
5063 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5064 macroRange.getBegin()))
5065 break;
5066 }
5067
5068 if (CurIdx == NumTokens)
5069 return CXChildVisit_Break;
5070
5071 for (; CurIdx < NumTokens; ++CurIdx) {
5072 SourceLocation tokLoc = getTokenLoc(CurIdx);
5073 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5074 break;
5075
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005076 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005077 }
5078
5079 if (CurIdx == NumTokens)
5080 return CXChildVisit_Break;
5081
5082 return CXChildVisit_Continue;
5083 }
5084
5085private:
5086 SourceLocation getTokenLoc(unsigned tokI) {
5087 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5088 }
5089
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005090 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005091 // The third field is reserved and currently not used. Use it here
5092 // to mark macro arg expanded tokens with their expanded locations.
5093 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5094 }
5095};
5096
5097} // end anonymous namespace
5098
5099static CXChildVisitResult
5100MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5101 CXClientData client_data) {
5102 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5103 parent);
5104}
5105
5106namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005107 struct clang_annotateTokens_Data {
5108 CXTranslationUnit TU;
5109 ASTUnit *CXXUnit;
5110 CXToken *Tokens;
5111 unsigned NumTokens;
5112 CXCursor *Cursors;
5113 };
5114}
5115
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005116static void annotatePreprocessorTokens(CXTranslationUnit TU,
5117 SourceRange RegionOfInterest,
5118 AnnotateTokensData &Annotated) {
5119 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5120
5121 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5122 std::pair<FileID, unsigned> BeginLocInfo
5123 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5124 std::pair<FileID, unsigned> EndLocInfo
5125 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5126
5127 if (BeginLocInfo.first != EndLocInfo.first)
5128 return;
5129
5130 StringRef Buffer;
5131 bool Invalid = false;
5132 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5133 if (Buffer.empty() || Invalid)
5134 return;
5135
5136 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5137 CXXUnit->getASTContext().getLangOptions(),
5138 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5139 Buffer.end());
5140 Lex.SetCommentRetentionState(true);
5141
5142 // Lex tokens in raw mode until we hit the end of the range, to avoid
5143 // entering #includes or expanding macros.
5144 while (true) {
5145 Token Tok;
5146 Lex.LexFromRawLexer(Tok);
5147
5148 reprocess:
5149 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5150 // We have found a preprocessing directive. Gobble it up so that we
5151 // don't see it while preprocessing these tokens later, but keep track
5152 // of all of the token locations inside this preprocessing directive so
5153 // that we can annotate them appropriately.
5154 //
5155 // FIXME: Some simple tests here could identify macro definitions and
5156 // #undefs, to provide specific cursor kinds for those.
5157 SmallVector<SourceLocation, 32> Locations;
5158 do {
5159 Locations.push_back(Tok.getLocation());
5160 Lex.LexFromRawLexer(Tok);
5161 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5162
5163 using namespace cxcursor;
5164 CXCursor Cursor
5165 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5166 Locations.back()),
5167 TU);
5168 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5169 Annotated[Locations[I].getRawEncoding()] = Cursor;
5170 }
5171
5172 if (Tok.isAtStartOfLine())
5173 goto reprocess;
5174
5175 continue;
5176 }
5177
5178 if (Tok.is(tok::eof))
5179 break;
5180 }
5181}
5182
Ted Kremenekab979612010-11-11 08:05:23 +00005183// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005184static void clang_annotateTokensImpl(void *UserData) {
5185 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5186 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5187 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5188 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5189 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5190
5191 // Determine the region of interest, which contains all of the tokens.
5192 SourceRange RegionOfInterest;
5193 RegionOfInterest.setBegin(
5194 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5195 RegionOfInterest.setEnd(
5196 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5197 Tokens[NumTokens-1])));
5198
5199 // A mapping from the source locations found when re-lexing or traversing the
5200 // region of interest to the corresponding cursors.
5201 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005202
Ted Kremenek6628a612011-03-18 22:51:30 +00005203 // Relex the tokens within the source range to look for preprocessing
5204 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005205 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005206
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005207 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5208 // Search and mark tokens that are macro argument expansions.
5209 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5210 Tokens, NumTokens);
5211 CursorVisitor MacroArgMarker(TU,
5212 MarkMacroArgTokensVisitorDelegate, &Visitor,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00005213 true, RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005214 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5215 }
5216
Ted Kremenek6628a612011-03-18 22:51:30 +00005217 // Annotate all of the source locations in the region of interest that map to
5218 // a specific cursor.
5219 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5220 TU, RegionOfInterest);
5221
5222 // FIXME: We use a ridiculous stack size here because the data-recursion
5223 // algorithm uses a large stack frame than the non-data recursive version,
5224 // and AnnotationTokensWorker currently transforms the data-recursion
5225 // algorithm back into a traditional recursion by explicitly calling
5226 // VisitChildren(). We will need to remove this explicit recursive call.
5227 W.AnnotateTokens();
5228
5229 // If we ran into any entities that involve context-sensitive keywords,
5230 // take another pass through the tokens to mark them as such.
5231 if (W.hasContextSensitiveKeywords()) {
5232 for (unsigned I = 0; I != NumTokens; ++I) {
5233 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5234 continue;
5235
5236 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5237 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5238 if (ObjCPropertyDecl *Property
5239 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5240 if (Property->getPropertyAttributesAsWritten() != 0 &&
5241 llvm::StringSwitch<bool>(II->getName())
5242 .Case("readonly", true)
5243 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005244 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005245 .Case("readwrite", true)
5246 .Case("retain", true)
5247 .Case("copy", true)
5248 .Case("nonatomic", true)
5249 .Case("atomic", true)
5250 .Case("getter", true)
5251 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005252 .Case("strong", true)
5253 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005254 .Default(false))
5255 Tokens[I].int_data[0] = CXToken_Keyword;
5256 }
5257 continue;
5258 }
5259
5260 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5261 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5262 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5263 if (llvm::StringSwitch<bool>(II->getName())
5264 .Case("in", true)
5265 .Case("out", true)
5266 .Case("inout", true)
5267 .Case("oneway", true)
5268 .Case("bycopy", true)
5269 .Case("byref", true)
5270 .Default(false))
5271 Tokens[I].int_data[0] = CXToken_Keyword;
5272 continue;
5273 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005274
5275 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5276 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5277 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005278 continue;
5279 }
5280 }
5281 }
Ted Kremenekab979612010-11-11 08:05:23 +00005282}
5283
Ted Kremenek6db61092010-05-05 00:55:15 +00005284extern "C" {
5285
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005286void clang_annotateTokens(CXTranslationUnit TU,
5287 CXToken *Tokens, unsigned NumTokens,
5288 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005289
5290 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005291 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005292
Douglas Gregor4419b672010-10-21 06:10:04 +00005293 // Any token we don't specifically annotate will have a NULL cursor.
5294 CXCursor C = clang_getNullCursor();
5295 for (unsigned I = 0; I != NumTokens; ++I)
5296 Cursors[I] = C;
5297
Ted Kremeneka60ed472010-11-16 08:15:36 +00005298 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005299 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005300 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005301
Douglas Gregorbdf60622010-03-05 21:16:25 +00005302 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005303
5304 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005305 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005306 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005307 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005308 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5309 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005310}
Ted Kremenek6628a612011-03-18 22:51:30 +00005311
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005312} // end: extern "C"
5313
5314//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005315// Operations for querying linkage of a cursor.
5316//===----------------------------------------------------------------------===//
5317
5318extern "C" {
5319CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005320 if (!clang_isDeclaration(cursor.kind))
5321 return CXLinkage_Invalid;
5322
Ted Kremenek16b42592010-03-03 06:36:57 +00005323 Decl *D = cxcursor::getCursorDecl(cursor);
5324 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5325 switch (ND->getLinkage()) {
5326 case NoLinkage: return CXLinkage_NoLinkage;
5327 case InternalLinkage: return CXLinkage_Internal;
5328 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5329 case ExternalLinkage: return CXLinkage_External;
5330 };
5331
5332 return CXLinkage_Invalid;
5333}
5334} // end: extern "C"
5335
5336//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005337// Operations for querying language of a cursor.
5338//===----------------------------------------------------------------------===//
5339
5340static CXLanguageKind getDeclLanguage(const Decl *D) {
5341 switch (D->getKind()) {
5342 default:
5343 break;
5344 case Decl::ImplicitParam:
5345 case Decl::ObjCAtDefsField:
5346 case Decl::ObjCCategory:
5347 case Decl::ObjCCategoryImpl:
5348 case Decl::ObjCClass:
5349 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005350 case Decl::ObjCForwardProtocol:
5351 case Decl::ObjCImplementation:
5352 case Decl::ObjCInterface:
5353 case Decl::ObjCIvar:
5354 case Decl::ObjCMethod:
5355 case Decl::ObjCProperty:
5356 case Decl::ObjCPropertyImpl:
5357 case Decl::ObjCProtocol:
5358 return CXLanguage_ObjC;
5359 case Decl::CXXConstructor:
5360 case Decl::CXXConversion:
5361 case Decl::CXXDestructor:
5362 case Decl::CXXMethod:
5363 case Decl::CXXRecord:
5364 case Decl::ClassTemplate:
5365 case Decl::ClassTemplatePartialSpecialization:
5366 case Decl::ClassTemplateSpecialization:
5367 case Decl::Friend:
5368 case Decl::FriendTemplate:
5369 case Decl::FunctionTemplate:
5370 case Decl::LinkageSpec:
5371 case Decl::Namespace:
5372 case Decl::NamespaceAlias:
5373 case Decl::NonTypeTemplateParm:
5374 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005375 case Decl::TemplateTemplateParm:
5376 case Decl::TemplateTypeParm:
5377 case Decl::UnresolvedUsingTypename:
5378 case Decl::UnresolvedUsingValue:
5379 case Decl::Using:
5380 case Decl::UsingDirective:
5381 case Decl::UsingShadow:
5382 return CXLanguage_CPlusPlus;
5383 }
5384
5385 return CXLanguage_C;
5386}
5387
5388extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005389
5390enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5391 if (clang_isDeclaration(cursor.kind))
5392 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005393 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005394 return CXAvailability_Available;
5395
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005396 switch (D->getAvailability()) {
5397 case AR_Available:
5398 case AR_NotYetIntroduced:
5399 return CXAvailability_Available;
5400
5401 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005402 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005403
5404 case AR_Unavailable:
5405 return CXAvailability_NotAvailable;
5406 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005407 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005408
Douglas Gregor58ddb602010-08-23 23:00:57 +00005409 return CXAvailability_Available;
5410}
5411
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005412CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5413 if (clang_isDeclaration(cursor.kind))
5414 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5415
5416 return CXLanguage_Invalid;
5417}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005418
5419 /// \brief If the given cursor is the "templated" declaration
5420 /// descibing a class or function template, return the class or
5421 /// function template.
5422static Decl *maybeGetTemplateCursor(Decl *D) {
5423 if (!D)
5424 return 0;
5425
5426 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5427 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5428 return FunTmpl;
5429
5430 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5431 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5432 return ClassTmpl;
5433
5434 return D;
5435}
5436
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005437CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5438 if (clang_isDeclaration(cursor.kind)) {
5439 if (Decl *D = getCursorDecl(cursor)) {
5440 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005441 if (!DC)
5442 return clang_getNullCursor();
5443
5444 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5445 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005446 }
5447 }
5448
5449 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5450 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005451 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005452 }
5453
5454 return clang_getNullCursor();
5455}
5456
5457CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5458 if (clang_isDeclaration(cursor.kind)) {
5459 if (Decl *D = getCursorDecl(cursor)) {
5460 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005461 if (!DC)
5462 return clang_getNullCursor();
5463
5464 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5465 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005466 }
5467 }
5468
5469 // FIXME: Note that we can't easily compute the lexical context of a
5470 // statement or expression, so we return nothing.
5471 return clang_getNullCursor();
5472}
5473
Douglas Gregor9f592342010-10-01 20:25:15 +00005474void clang_getOverriddenCursors(CXCursor cursor,
5475 CXCursor **overridden,
5476 unsigned *num_overridden) {
5477 if (overridden)
5478 *overridden = 0;
5479 if (num_overridden)
5480 *num_overridden = 0;
5481 if (!overridden || !num_overridden)
5482 return;
5483
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005484 SmallVector<CXCursor, 8> Overridden;
5485 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005486
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005487 *num_overridden = Overridden.size();
5488 *overridden = new CXCursor [Overridden.size()];
5489 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005490}
5491
5492void clang_disposeOverriddenCursors(CXCursor *overridden) {
5493 delete [] overridden;
5494}
5495
Douglas Gregorecdcb882010-10-20 22:00:55 +00005496CXFile clang_getIncludedFile(CXCursor cursor) {
5497 if (cursor.kind != CXCursor_InclusionDirective)
5498 return 0;
5499
5500 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5501 return (void *)ID->getFile();
5502}
5503
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005504} // end: extern "C"
5505
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005506
5507//===----------------------------------------------------------------------===//
5508// C++ AST instrospection.
5509//===----------------------------------------------------------------------===//
5510
5511extern "C" {
5512unsigned clang_CXXMethod_isStatic(CXCursor C) {
5513 if (!clang_isDeclaration(C.kind))
5514 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005515
5516 CXXMethodDecl *Method = 0;
5517 Decl *D = cxcursor::getCursorDecl(C);
5518 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5519 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5520 else
5521 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5522 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005523}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005524
Douglas Gregor211924b2011-05-12 15:17:24 +00005525unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5526 if (!clang_isDeclaration(C.kind))
5527 return 0;
5528
5529 CXXMethodDecl *Method = 0;
5530 Decl *D = cxcursor::getCursorDecl(C);
5531 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5532 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5533 else
5534 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5535 return (Method && Method->isVirtual()) ? 1 : 0;
5536}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005537} // end: extern "C"
5538
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005539//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005540// Attribute introspection.
5541//===----------------------------------------------------------------------===//
5542
5543extern "C" {
5544CXType clang_getIBOutletCollectionType(CXCursor C) {
5545 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005546 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005547
5548 IBOutletCollectionAttr *A =
5549 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5550
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005551 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005552}
5553} // end: extern "C"
5554
5555//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005556// Inspecting memory usage.
5557//===----------------------------------------------------------------------===//
5558
Ted Kremenekf7870022011-04-20 16:41:07 +00005559typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005560
Ted Kremenekf7870022011-04-20 16:41:07 +00005561static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5562 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005563 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005564 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005565 entries.push_back(entry);
5566}
5567
5568extern "C" {
5569
Ted Kremenekf7870022011-04-20 16:41:07 +00005570const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005571 const char *str = "";
5572 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005573 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005574 str = "ASTContext: expressions, declarations, and types";
5575 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005576 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005577 str = "ASTContext: identifiers";
5578 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005579 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005580 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005581 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005582 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005583 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005584 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005585 case CXTUResourceUsage_SourceManagerContentCache:
5586 str = "SourceManager: content cache allocator";
5587 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005588 case CXTUResourceUsage_AST_SideTables:
5589 str = "ASTContext: side tables";
5590 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005591 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5592 str = "SourceManager: malloc'ed memory buffers";
5593 break;
5594 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5595 str = "SourceManager: mmap'ed memory buffers";
5596 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005597 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5598 str = "ExternalASTSource: malloc'ed memory buffers";
5599 break;
5600 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5601 str = "ExternalASTSource: mmap'ed memory buffers";
5602 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005603 case CXTUResourceUsage_Preprocessor:
5604 str = "Preprocessor: malloc'ed memory";
5605 break;
5606 case CXTUResourceUsage_PreprocessingRecord:
5607 str = "Preprocessor: PreprocessingRecord";
5608 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005609 case CXTUResourceUsage_SourceManager_DataStructures:
5610 str = "SourceManager: data structures and tables";
5611 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005612 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5613 str = "Preprocessor: header search tables";
5614 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005615 }
5616 return str;
5617}
5618
Ted Kremenekf7870022011-04-20 16:41:07 +00005619CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005620 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005621 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005622 return usage;
5623 }
5624
5625 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5626 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5627 ASTContext &astContext = astUnit->getASTContext();
5628
5629 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005630 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005631 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005632
5633 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005634 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005635 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5636
5637 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005638 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005639 (unsigned long) astContext.Selectors.getTotalMemory());
5640
Ted Kremenekba29bd22011-04-28 04:53:38 +00005641 // How much memory is used by ASTContext's side tables?
5642 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5643 (unsigned long) astContext.getSideTableAllocatedMemory());
5644
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005645 // How much memory is used for caching global code completion results?
5646 unsigned long completionBytes = 0;
5647 if (GlobalCodeCompletionAllocator *completionAllocator =
5648 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005649 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005650 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005651 createCXTUResourceUsageEntry(*entries,
5652 CXTUResourceUsage_GlobalCompletionResults,
5653 completionBytes);
5654
5655 // How much memory is being used by SourceManager's content cache?
5656 createCXTUResourceUsageEntry(*entries,
5657 CXTUResourceUsage_SourceManagerContentCache,
5658 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005659
5660 // How much memory is being used by the MemoryBuffer's in SourceManager?
5661 const SourceManager::MemoryBufferSizes &srcBufs =
5662 astUnit->getSourceManager().getMemoryBufferSizes();
5663
5664 createCXTUResourceUsageEntry(*entries,
5665 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5666 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005667 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005668 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5669 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005670 createCXTUResourceUsageEntry(*entries,
5671 CXTUResourceUsage_SourceManager_DataStructures,
5672 (unsigned long) astContext.getSourceManager()
5673 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005674
5675 // How much memory is being used by the ExternalASTSource?
5676 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5677 const ExternalASTSource::MemoryBufferSizes &sizes =
5678 esrc->getMemoryBufferSizes();
5679
5680 createCXTUResourceUsageEntry(*entries,
5681 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5682 (unsigned long) sizes.malloc_bytes);
5683 createCXTUResourceUsageEntry(*entries,
5684 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5685 (unsigned long) sizes.mmap_bytes);
5686 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005687
5688 // How much memory is being used by the Preprocessor?
5689 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005690 createCXTUResourceUsageEntry(*entries,
5691 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005692 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005693
5694 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5695 createCXTUResourceUsageEntry(*entries,
5696 CXTUResourceUsage_PreprocessingRecord,
5697 pRec->getTotalMemory());
5698 }
5699
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005700 createCXTUResourceUsageEntry(*entries,
5701 CXTUResourceUsage_Preprocessor_HeaderSearch,
5702 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005703
Ted Kremenekf7870022011-04-20 16:41:07 +00005704 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005705 (unsigned) entries->size(),
5706 entries->size() ? &(*entries)[0] : 0 };
5707 entries.take();
5708 return usage;
5709}
5710
Ted Kremenekf7870022011-04-20 16:41:07 +00005711void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005712 if (usage.data)
5713 delete (MemUsageEntries*) usage.data;
5714}
5715
5716} // end extern "C"
5717
Douglas Gregor6df78732011-05-05 20:27:22 +00005718void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5719 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5720 for (unsigned I = 0; I != Usage.numEntries; ++I)
5721 fprintf(stderr, " %s: %lu\n",
5722 clang_getTUResourceUsageName(Usage.entries[I].kind),
5723 Usage.entries[I].amount);
5724
5725 clang_disposeCXTUResourceUsage(Usage);
5726}
5727
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005728//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005729// Misc. utility functions.
5730//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005731
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005732/// Default to using an 8 MB stack size on "safety" threads.
5733static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005734
5735namespace clang {
5736
5737bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005738 void (*Fn)(void*), void *UserData,
5739 unsigned Size) {
5740 if (!Size)
5741 Size = GetSafetyThreadStackSize();
5742 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005743 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5744 return CRC.RunSafely(Fn, UserData);
5745}
5746
5747unsigned GetSafetyThreadStackSize() {
5748 return SafetyStackThreadSize;
5749}
5750
5751void SetSafetyThreadStackSize(unsigned Value) {
5752 SafetyStackThreadSize = Value;
5753}
5754
5755}
5756
Ted Kremenek04bb7162010-01-22 22:44:15 +00005757extern "C" {
5758
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005759CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005760 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005761}
5762
5763} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005764