blob: 5916d5c3374f31cd829a9c6bbdb59b088fa52212 [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;
Steve Naroff50398192009-08-28 15:28:48 +000054
Ted Kremeneka60ed472010-11-16 08:15:36 +000055static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
56 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
61 return D;
62}
63
Douglas Gregor33e9abd2010-01-22 19:49:59 +000064/// \brief The result of comparing two source ranges.
65enum RangeComparisonResult {
66 /// \brief Either the ranges overlap or one of the ranges is invalid.
67 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000068
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 /// \brief The first range ends before the second range starts.
70 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000071
Douglas Gregor33e9abd2010-01-22 19:49:59 +000072 /// \brief The first range starts after the second range ends.
73 RangeAfter
74};
75
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000078static RangeComparisonResult RangeCompare(SourceManager &SM,
79 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000080 SourceRange R2) {
81 assert(R1.isValid() && "First range is invalid?");
82 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000083 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000084 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000085 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000086 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000087 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000088 return RangeAfter;
89 return RangeOverlap;
90}
91
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000092/// \brief Determine if a source location falls within, before, or after a
93/// a given source range.
94static RangeComparisonResult LocationCompare(SourceManager &SM,
95 SourceLocation L, SourceRange R) {
96 assert(R.isValid() && "First range is invalid?");
97 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000098 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000099 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000100 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
101 return RangeBefore;
102 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
103 return RangeAfter;
104 return RangeOverlap;
105}
106
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107/// \brief Translate a Clang source range into a CIndex source range.
108///
109/// Clang internally represents ranges where the end location points to the
110/// start of the token at the end. However, for external clients it is more
111/// useful to have a CXSourceRange be a proper half-open interval. This routine
112/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000113CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000117 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000119 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000120 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000121 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000122 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000123 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000124 }
125
126 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
127 R.getBegin().getRawEncoding(),
128 EndLoc.getRawEncoding() };
129 return Result;
130}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000131
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000133// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000134//===----------------------------------------------------------------------===//
135
Steve Naroff89922f82009-08-31 00:59:03 +0000136namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000137
138class VisitorJob {
139public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000140 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000141 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000142 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000143 ExplicitTemplateArgsVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000144 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000145 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000146 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000148 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000149 CXCursor parent;
150 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000151 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
152 : parent(C), K(k) {
153 data[0] = d1;
154 data[1] = d2;
155 data[2] = d3;
156 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000157public:
158 Kind getKind() const { return K; }
159 const CXCursor &getParent() const { return parent; }
160 static bool classof(VisitorJob *VJ) { return true; }
161};
162
Chris Lattner5f9e2722011-07-23 10:55:15 +0000163typedef SmallVector<VisitorJob, 10> VisitorWorkList;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000164
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000167 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000168{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000169 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000170 CXTranslationUnit TU;
171 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176 /// \brief The declaration that serves at the parent of any statement or
177 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000178 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000183 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000186 /// \brief Whether we should visit the preprocessing record entries last,
187 /// after visiting other declarations.
188 bool VisitPreprocessorLast;
189
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 /// \brief When valid, a source range to which the cursor should restrict
191 /// its search.
192 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000194 // FIXME: Eventually remove. This part of a hack to support proper
195 // iteration over all Decls contained lexically within an ObjC container.
196 DeclContext::decl_iterator *DI_current;
197 DeclContext::decl_iterator DE_current;
198
Ted Kremenekd1ded662010-11-15 23:31:32 +0000199 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000200 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
201 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
206 /// \brief Determine whether this particular source range comes before, comes
207 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000209 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
211
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000212 class SetParentRAII {
213 CXCursor &Parent;
214 Decl *&StmtParent;
215 CXCursor OldParent;
216
217 public:
218 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
219 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
220 {
221 Parent = NewParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225
226 ~SetParentRAII() {
227 Parent = OldParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231 };
232
Steve Naroff89922f82009-08-31 00:59:03 +0000233public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000234 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
235 CXClientData ClientData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000236 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000238 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
239 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor08e0bc12011-09-10 00:09:20 +0000240 VisitPreprocessorLast(VisitPreprocessorLast),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000241 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 {
243 Parent.kind = CXCursor_NoDeclFound;
244 Parent.data[0] = 0;
245 Parent.data[1] = 0;
246 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000249
Ted Kremenekd1ded662010-11-15 23:31:32 +0000250 ~CursorVisitor() {
251 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000252 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000253 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
254 delete *I;
255 }
256 }
257
Ted Kremeneka60ed472010-11-16 08:15:36 +0000258 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
259 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000260
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000261 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000262
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000263 bool visitPreprocessedEntitiesInRegion();
264
265 template<typename InputIterator>
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000266 bool visitPreprocessedEntities(InputIterator First, InputIterator Last);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000267
Douglas Gregorb1373d02010-01-20 20:59:29 +0000268 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000269
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000270 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000271 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000272 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000273 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000274 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000275 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000276 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000277 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
278 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000279 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000280 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000281 bool VisitClassTemplatePartialSpecializationDecl(
282 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000283 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000284 bool VisitEnumConstantDecl(EnumConstantDecl *D);
285 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
286 bool VisitFunctionDecl(FunctionDecl *ND);
287 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000288 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000289 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000290 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000291 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000292 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000293 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
294 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
295 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
296 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000297 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
299 bool VisitObjCImplDecl(ObjCImplDecl *D);
300 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
301 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000302 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
303 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
304 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000305 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000306 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000307 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000308 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000309 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000310 bool VisitUsingDecl(UsingDecl *D);
311 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
312 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000313
Douglas Gregor01829d32010-08-31 14:41:23 +0000314 // Name visitor
315 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000316 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000317 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000318
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000319 // Template visitors
320 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000321 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000322 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
323
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000324 // Type visitors
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000325#define ABSTRACT_TYPELOC(CLASS, PARENT)
326#define TYPELOC(CLASS, PARENT) \
327 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
328#include "clang/AST/TypeLocNodes.def"
329
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000332 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
333
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000334 // Data-recursive visitor functions.
335 bool IsInRegionOfInterest(CXCursor C);
336 bool RunVisitorWorkList(VisitorWorkList &WL);
337 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000338 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000339};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000340
Ted Kremenekab188932010-01-05 19:32:54 +0000341} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000342
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000343static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000344static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
345
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000346
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000347RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000348 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000349}
350
Douglas Gregorb1373d02010-01-20 20:59:29 +0000351/// \brief Visit the given cursor and, if requested by the visitor,
352/// its children.
353///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000354/// \param Cursor the cursor to visit.
355///
356/// \param CheckRegionOfInterest if true, then the caller already checked that
357/// this cursor is within the region of interest.
358///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000359/// \returns true if the visitation should be aborted, false if it
360/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000362 if (clang_isInvalid(Cursor.kind))
363 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000364
Douglas Gregorb1373d02010-01-20 20:59:29 +0000365 if (clang_isDeclaration(Cursor.kind)) {
366 Decl *D = getCursorDecl(Cursor);
367 assert(D && "Invalid declaration cursor");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000368 if (D->isImplicit())
369 return false;
370 }
371
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372 // If we have a range of interest, and this cursor doesn't intersect with it,
373 // we're done.
374 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000375 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000376 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000377 return false;
378 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000379
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380 switch (Visitor(Cursor, Parent, ClientData)) {
381 case CXChildVisit_Break:
382 return true;
383
384 case CXChildVisit_Continue:
385 return false;
386
387 case CXChildVisit_Recurse:
388 return VisitChildren(Cursor);
389 }
390
Douglas Gregorfd643772010-01-25 16:45:46 +0000391 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392}
393
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000394bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000395 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000396 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000397
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000398 if (RegionOfInterest.isValid()) {
399 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
400 Entities = PPRec.getPreprocessedEntitiesInRange(RegionOfInterest);
401 return visitPreprocessedEntities(Entities.first, Entities.second);
402 }
403
Douglas Gregor788f5a12010-03-20 00:41:21 +0000404 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000405 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
406
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000407 if (OnlyLocalDecls)
408 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000409
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000410 return visitPreprocessedEntities(PPRec.begin(), PPRec.end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000411}
412
413template<typename InputIterator>
414bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
415 InputIterator Last) {
416 for (; First != Last; ++First) {
417 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
418 if (Visit(MakeMacroExpansionCursor(ME, TU)))
419 return true;
420
421 continue;
422 }
423
424 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
425 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
426 return true;
427
428 continue;
429 }
430
431 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
432 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
433 return true;
434
435 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000436 }
437 }
438
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000439 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000440}
441
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000443///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444/// \returns true if the visitation should be aborted, false if it
445/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000446bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000447 if (clang_isReference(Cursor.kind) &&
448 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000449 // By definition, references have no children.
450 return false;
451 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000452
453 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000455 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457 if (clang_isDeclaration(Cursor.kind)) {
458 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000459 if (!D)
460 return false;
461
Ted Kremenek539311e2010-02-18 18:47:01 +0000462 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000465 if (clang_isStatement(Cursor.kind)) {
466 if (Stmt *S = getCursorStmt(Cursor))
467 return Visit(S);
468
469 return false;
470 }
471
472 if (clang_isExpression(Cursor.kind)) {
473 if (Expr *E = getCursorExpr(Cursor))
474 return Visit(E);
475
476 return false;
477 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478
Douglas Gregorb1373d02010-01-20 20:59:29 +0000479 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000480 CXTranslationUnit tu = getCursorTU(Cursor);
481 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000482
483 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
484 for (unsigned I = 0; I != 2; ++I) {
485 if (VisitOrder[I]) {
486 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
487 RegionOfInterest.isInvalid()) {
488 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
489 TLEnd = CXXUnit->top_level_end();
490 TL != TLEnd; ++TL) {
491 if (Visit(MakeCXCursor(*TL, tu), true))
492 return true;
493 }
494 } else if (VisitDeclContext(
495 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000496 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000497 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000498 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000499
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000500 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000501 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
502 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000504
Douglas Gregor7b691f332010-01-20 21:13:59 +0000505 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000506 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000507
Douglas Gregorc314aa42011-03-02 19:17:03 +0000508 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
509 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
510 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
511 return Visit(BaseTSInfo->getTypeLoc());
512 }
513 }
514 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000515
516 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
517 IBOutletCollectionAttr *A =
518 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
519 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
520 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
521 A->getInterfaceLoc(), TU));
522 }
523
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 return false;
526}
527
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000529 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
530 if (Visit(TSInfo->getTypeLoc()))
531 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000532
Ted Kremenek664cffd2010-07-22 11:30:19 +0000533 if (Stmt *Body = B->getBody())
534 return Visit(MakeCXCursor(Body, StmtParent, TU));
535
536 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000537}
538
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000539llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
540 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000541 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000542 if (Range.isInvalid())
543 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000544
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000545 switch (CompareRegionOfInterest(Range)) {
546 case RangeBefore:
547 // This declaration comes before the region of interest; skip it.
548 return llvm::Optional<bool>();
549
550 case RangeAfter:
551 // This declaration comes after the region of interest; we're done.
552 return false;
553
554 case RangeOverlap:
555 // This declaration overlaps the region of interest; visit it.
556 break;
557 }
558 }
559 return true;
560}
561
562bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
563 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
564
565 // FIXME: Eventually remove. This part of a hack to support proper
566 // iteration over all Decls contained lexically within an ObjC container.
567 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
568 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
569
570 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000571 Decl *D = *I;
572 if (D->getLexicalDeclContext() != DC)
573 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000574 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000575 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
576 if (!V.hasValue())
577 continue;
578 if (!V.getValue())
579 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000580 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581 return true;
582 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000584}
585
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000586bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
587 llvm_unreachable("Translation units are visited directly by Visit()");
588 return false;
589}
590
Richard Smith162e1c12011-04-15 14:24:37 +0000591bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
592 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
593 return Visit(TSInfo->getTypeLoc());
594
595 return false;
596}
597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
599 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
600 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602 return false;
603}
604
605bool CursorVisitor::VisitTagDecl(TagDecl *D) {
606 return VisitDeclContext(D);
607}
608
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000609bool CursorVisitor::VisitClassTemplateSpecializationDecl(
610 ClassTemplateSpecializationDecl *D) {
611 bool ShouldVisitBody = false;
612 switch (D->getSpecializationKind()) {
613 case TSK_Undeclared:
614 case TSK_ImplicitInstantiation:
615 // Nothing to visit
616 return false;
617
618 case TSK_ExplicitInstantiationDeclaration:
619 case TSK_ExplicitInstantiationDefinition:
620 break;
621
622 case TSK_ExplicitSpecialization:
623 ShouldVisitBody = true;
624 break;
625 }
626
627 // Visit the template arguments used in the specialization.
628 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
629 TypeLoc TL = SpecType->getTypeLoc();
630 if (TemplateSpecializationTypeLoc *TSTLoc
631 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
632 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
633 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
634 return true;
635 }
636 }
637
638 if (ShouldVisitBody && VisitCXXRecordDecl(D))
639 return true;
640
641 return false;
642}
643
Douglas Gregor74dbe642010-08-31 19:31:58 +0000644bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
645 ClassTemplatePartialSpecializationDecl *D) {
646 // FIXME: Visit the "outer" template parameter lists on the TagDecl
647 // before visiting these template parameters.
648 if (VisitTemplateParameters(D->getTemplateParameters()))
649 return true;
650
651 // Visit the partial specialization arguments.
652 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
653 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
654 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
655 return true;
656
657 return VisitCXXRecordDecl(D);
658}
659
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000660bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000661 // Visit the default argument.
662 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
663 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
664 if (Visit(DefArg->getTypeLoc()))
665 return true;
666
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000667 return false;
668}
669
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000670bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
671 if (Expr *Init = D->getInitExpr())
672 return Visit(MakeCXCursor(Init, StmtParent, TU));
673 return false;
674}
675
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000676bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
677 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
678 if (Visit(TSInfo->getTypeLoc()))
679 return true;
680
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000681 // Visit the nested-name-specifier, if present.
682 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
683 if (VisitNestedNameSpecifierLoc(QualifierLoc))
684 return true;
685
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000686 return false;
687}
688
Douglas Gregora67e03f2010-09-09 21:42:20 +0000689/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000690static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
691 CXXCtorInitializer const * const *X
692 = static_cast<CXXCtorInitializer const * const *>(Xp);
693 CXXCtorInitializer const * const *Y
694 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000695
696 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
697 return -1;
698 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
699 return 1;
700 else
701 return 0;
702}
703
Douglas Gregorb1373d02010-01-20 20:59:29 +0000704bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000705 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
706 // Visit the function declaration's syntactic components in the order
707 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000708 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000709 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
710
711 // If we have a function declared directly (without the use of a typedef),
712 // visit just the return type. Otherwise, just visit the function's type
713 // now.
714 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
715 (!FTL && Visit(TL)))
716 return true;
717
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000718 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000719 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
720 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000721 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000722
723 // Visit the declaration name.
724 if (VisitDeclarationNameInfo(ND->getNameInfo()))
725 return true;
726
727 // FIXME: Visit explicitly-specified template arguments!
728
729 // Visit the function parameters, if we have a function type.
730 if (FTL && VisitFunctionTypeLoc(*FTL, true))
731 return true;
732
733 // FIXME: Attributes?
734 }
735
Sean Hunt10620eb2011-05-06 20:44:56 +0000736 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000737 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
738 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000739 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000740 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
741 IEnd = Constructor->init_end();
742 I != IEnd; ++I) {
743 if (!(*I)->isWritten())
744 continue;
745
746 WrittenInits.push_back(*I);
747 }
748
749 // Sort the initializers in source order
750 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000751 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000752
753 // Visit the initializers in source order
754 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000755 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000756 if (Init->isAnyMemberInitializer()) {
757 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000758 Init->getMemberLocation(), TU)))
759 return true;
760 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
761 if (Visit(BaseInfo->getTypeLoc()))
762 return true;
763 }
764
765 // Visit the initializer value.
766 if (Expr *Initializer = Init->getInit())
767 if (Visit(MakeCXCursor(Initializer, ND, TU)))
768 return true;
769 }
770 }
771
772 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
773 return true;
774 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000775
Douglas Gregorb1373d02010-01-20 20:59:29 +0000776 return false;
777}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000778
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000779bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
780 if (VisitDeclaratorDecl(D))
781 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000783 if (Expr *BitWidth = D->getBitWidth())
784 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000786 return false;
787}
788
789bool CursorVisitor::VisitVarDecl(VarDecl *D) {
790 if (VisitDeclaratorDecl(D))
791 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000792
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000793 if (Expr *Init = D->getInit())
794 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000795
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796 return false;
797}
798
Douglas Gregor84b51d72010-09-01 20:16:53 +0000799bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
800 if (VisitDeclaratorDecl(D))
801 return true;
802
803 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
804 if (Expr *DefArg = D->getDefaultArgument())
805 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
806
807 return false;
808}
809
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000810bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
811 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
812 // before visiting these template parameters.
813 if (VisitTemplateParameters(D->getTemplateParameters()))
814 return true;
815
816 return VisitFunctionDecl(D->getTemplatedDecl());
817}
818
Douglas Gregor39d6f072010-08-31 19:02:00 +0000819bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
820 // FIXME: Visit the "outer" template parameter lists on the TagDecl
821 // before visiting these template parameters.
822 if (VisitTemplateParameters(D->getTemplateParameters()))
823 return true;
824
825 return VisitCXXRecordDecl(D->getTemplatedDecl());
826}
827
Douglas Gregor84b51d72010-09-01 20:16:53 +0000828bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
829 if (VisitTemplateParameters(D->getTemplateParameters()))
830 return true;
831
832 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
833 VisitTemplateArgumentLoc(D->getDefaultArgument()))
834 return true;
835
836 return false;
837}
838
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000840 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
841 if (Visit(TSInfo->getTypeLoc()))
842 return true;
843
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000844 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000845 PEnd = ND->param_end();
846 P != PEnd; ++P) {
847 if (Visit(MakeCXCursor(*P, TU)))
848 return true;
849 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000851 if (ND->isThisDeclarationADefinition() &&
852 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
853 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000854
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855 return false;
856}
857
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000858namespace {
859 struct ContainerDeclsSort {
860 SourceManager &SM;
861 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
862 bool operator()(Decl *A, Decl *B) {
863 SourceLocation L_A = A->getLocStart();
864 SourceLocation L_B = B->getLocStart();
865 assert(L_A.isValid() && L_B.isValid());
866 return SM.isBeforeInTranslationUnit(L_A, L_B);
867 }
868 };
869}
870
Douglas Gregora59e3902010-01-21 23:27:09 +0000871bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000872 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
873 // an @implementation can lexically contain Decls that are not properly
874 // nested in the AST. When we identify such cases, we need to retrofit
875 // this nesting here.
876 if (!DI_current)
877 return VisitDeclContext(D);
878
879 // Scan the Decls that immediately come after the container
880 // in the current DeclContext. If any fall within the
881 // container's lexical region, stash them into a vector
882 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000883 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000884 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000885 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000886 if (EndLoc.isValid()) {
887 DeclContext::decl_iterator next = *DI_current;
888 while (++next != DE_current) {
889 Decl *D_next = *next;
890 if (!D_next)
891 break;
892 SourceLocation L = D_next->getLocStart();
893 if (!L.isValid())
894 break;
895 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
896 *DI_current = next;
897 DeclsInContainer.push_back(D_next);
898 continue;
899 }
900 break;
901 }
902 }
903
904 // The common case.
905 if (DeclsInContainer.empty())
906 return VisitDeclContext(D);
907
908 // Get all the Decls in the DeclContext, and sort them with the
909 // additional ones we've collected. Then visit them.
910 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
911 I!=E; ++I) {
912 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000913 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
914 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000915 continue;
916 DeclsInContainer.push_back(subDecl);
917 }
918
919 // Now sort the Decls so that they appear in lexical order.
920 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
921 ContainerDeclsSort(SM));
922
923 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000924 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000925 E = DeclsInContainer.end(); I != E; ++I) {
926 CXCursor Cursor = MakeCXCursor(*I, TU);
927 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
928 if (!V.hasValue())
929 continue;
930 if (!V.getValue())
931 return false;
932 if (Visit(Cursor, true))
933 return true;
934 }
935 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000936}
937
Douglas Gregorb1373d02010-01-20 20:59:29 +0000938bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000939 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
940 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000943 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
944 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
945 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000946 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregora59e3902010-01-21 23:27:09 +0000949 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000950}
951
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000952bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
953 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
954 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
955 E = PID->protocol_end(); I != E; ++I, ++PL)
956 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
957 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000958
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000959 return VisitObjCContainerDecl(PID);
960}
961
Ted Kremenek23173d72010-05-18 21:09:07 +0000962bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000963 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000964 return true;
965
Ted Kremenek23173d72010-05-18 21:09:07 +0000966 // FIXME: This implements a workaround with @property declarations also being
967 // installed in the DeclContext for the @interface. Eventually this code
968 // should be removed.
969 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
970 if (!CDecl || !CDecl->IsClassExtension())
971 return false;
972
973 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
974 if (!ID)
975 return false;
976
977 IdentifierInfo *PropertyId = PD->getIdentifier();
978 ObjCPropertyDecl *prevDecl =
979 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
980
981 if (!prevDecl)
982 return false;
983
984 // Visit synthesized methods since they will be skipped when visiting
985 // the @interface.
986 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000987 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000988 if (Visit(MakeCXCursor(MD, TU)))
989 return true;
990
991 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000992 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000993 if (Visit(MakeCXCursor(MD, TU)))
994 return true;
995
996 return false;
997}
998
Douglas Gregorb1373d02010-01-20 20:59:29 +0000999bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001000 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001001 if (D->getSuperClass() &&
1002 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001003 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001004 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001005 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001007 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1008 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1009 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001010 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregora59e3902010-01-21 23:27:09 +00001013 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001014}
1015
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001016bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1017 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001018}
1019
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001020bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001021 // 'ID' could be null when dealing with invalid code.
1022 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1023 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1024 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001026 return VisitObjCImplDecl(D);
1027}
1028
1029bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1030#if 0
1031 // Issue callbacks for super class.
1032 // FIXME: No source location information!
1033 if (D->getSuperClass() &&
1034 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001035 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001036 TU)))
1037 return true;
1038#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001040 return VisitObjCImplDecl(D);
1041}
1042
1043bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1044 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1045 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1046 E = D->protocol_end();
1047 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001048 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001049 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001050
1051 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001052}
1053
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001054bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001055 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1056 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001057 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001058 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001059}
1060
Douglas Gregora4ffd852010-11-17 01:03:52 +00001061bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1062 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1063 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1064
1065 return false;
1066}
1067
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001068bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1069 return VisitDeclContext(D);
1070}
1071
Douglas Gregor69319002010-08-31 23:48:11 +00001072bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001073 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001074 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1075 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001076 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001077
1078 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1079 D->getTargetNameLoc(), TU));
1080}
1081
Douglas Gregor7e242562010-09-01 19:52:22 +00001082bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001083 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001084 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1085 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001087 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001088
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001089 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1090 return true;
1091
Douglas Gregor7e242562010-09-01 19:52:22 +00001092 return VisitDeclarationNameInfo(D->getNameInfo());
1093}
1094
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001095bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001096 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001097 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1098 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001099 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001100
1101 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1102 D->getIdentLocation(), TU));
1103}
1104
Douglas Gregor7e242562010-09-01 19:52:22 +00001105bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001106 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001107 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1108 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001109 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001110 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001111
Douglas Gregor7e242562010-09-01 19:52:22 +00001112 return VisitDeclarationNameInfo(D->getNameInfo());
1113}
1114
1115bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1116 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001117 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001118 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1119 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120 return true;
1121
Douglas Gregor7e242562010-09-01 19:52:22 +00001122 return false;
1123}
1124
Douglas Gregor01829d32010-08-31 14:41:23 +00001125bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1126 switch (Name.getName().getNameKind()) {
1127 case clang::DeclarationName::Identifier:
1128 case clang::DeclarationName::CXXLiteralOperatorName:
1129 case clang::DeclarationName::CXXOperatorName:
1130 case clang::DeclarationName::CXXUsingDirective:
1131 return false;
1132
1133 case clang::DeclarationName::CXXConstructorName:
1134 case clang::DeclarationName::CXXDestructorName:
1135 case clang::DeclarationName::CXXConversionFunctionName:
1136 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1137 return Visit(TSInfo->getTypeLoc());
1138 return false;
1139
1140 case clang::DeclarationName::ObjCZeroArgSelector:
1141 case clang::DeclarationName::ObjCOneArgSelector:
1142 case clang::DeclarationName::ObjCMultiArgSelector:
1143 // FIXME: Per-identifier location info?
1144 return false;
1145 }
1146
1147 return false;
1148}
1149
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001150bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1151 SourceRange Range) {
1152 // FIXME: This whole routine is a hack to work around the lack of proper
1153 // source information in nested-name-specifiers (PR5791). Since we do have
1154 // a beginning source location, we can visit the first component of the
1155 // nested-name-specifier, if it's a single-token component.
1156 if (!NNS)
1157 return false;
1158
1159 // Get the first component in the nested-name-specifier.
1160 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1161 NNS = Prefix;
1162
1163 switch (NNS->getKind()) {
1164 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001165 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1166 TU));
1167
Douglas Gregor14aba762011-02-24 02:36:08 +00001168 case NestedNameSpecifier::NamespaceAlias:
1169 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1170 Range.getBegin(), TU));
1171
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001172 case NestedNameSpecifier::TypeSpec: {
1173 // If the type has a form where we know that the beginning of the source
1174 // range matches up with a reference cursor. Visit the appropriate reference
1175 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001176 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001177 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1178 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1179 if (const TagType *Tag = dyn_cast<TagType>(T))
1180 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1181 if (const TemplateSpecializationType *TST
1182 = dyn_cast<TemplateSpecializationType>(T))
1183 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1184 break;
1185 }
1186
1187 case NestedNameSpecifier::TypeSpecWithTemplate:
1188 case NestedNameSpecifier::Global:
1189 case NestedNameSpecifier::Identifier:
1190 break;
1191 }
1192
1193 return false;
1194}
1195
Douglas Gregordc355712011-02-25 00:36:19 +00001196bool
1197CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001198 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001199 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1200 Qualifiers.push_back(Qualifier);
1201
1202 while (!Qualifiers.empty()) {
1203 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1204 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1205 switch (NNS->getKind()) {
1206 case NestedNameSpecifier::Namespace:
1207 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001208 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001209 TU)))
1210 return true;
1211
1212 break;
1213
1214 case NestedNameSpecifier::NamespaceAlias:
1215 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001216 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001217 TU)))
1218 return true;
1219
1220 break;
1221
1222 case NestedNameSpecifier::TypeSpec:
1223 case NestedNameSpecifier::TypeSpecWithTemplate:
1224 if (Visit(Q.getTypeLoc()))
1225 return true;
1226
1227 break;
1228
1229 case NestedNameSpecifier::Global:
1230 case NestedNameSpecifier::Identifier:
1231 break;
1232 }
1233 }
1234
1235 return false;
1236}
1237
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001238bool CursorVisitor::VisitTemplateParameters(
1239 const TemplateParameterList *Params) {
1240 if (!Params)
1241 return false;
1242
1243 for (TemplateParameterList::const_iterator P = Params->begin(),
1244 PEnd = Params->end();
1245 P != PEnd; ++P) {
1246 if (Visit(MakeCXCursor(*P, TU)))
1247 return true;
1248 }
1249
1250 return false;
1251}
1252
Douglas Gregor0b36e612010-08-31 20:37:03 +00001253bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1254 switch (Name.getKind()) {
1255 case TemplateName::Template:
1256 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1257
1258 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001259 // Visit the overloaded template set.
1260 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1261 return true;
1262
Douglas Gregor0b36e612010-08-31 20:37:03 +00001263 return false;
1264
1265 case TemplateName::DependentTemplate:
1266 // FIXME: Visit nested-name-specifier.
1267 return false;
1268
1269 case TemplateName::QualifiedTemplate:
1270 // FIXME: Visit nested-name-specifier.
1271 return Visit(MakeCursorTemplateRef(
1272 Name.getAsQualifiedTemplateName()->getDecl(),
1273 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001274
1275 case TemplateName::SubstTemplateTemplateParm:
1276 return Visit(MakeCursorTemplateRef(
1277 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1278 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001279
1280 case TemplateName::SubstTemplateTemplateParmPack:
1281 return Visit(MakeCursorTemplateRef(
1282 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1283 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001284 }
1285
1286 return false;
1287}
1288
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001289bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1290 switch (TAL.getArgument().getKind()) {
1291 case TemplateArgument::Null:
1292 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001293 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001294 return false;
1295
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001296 case TemplateArgument::Type:
1297 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1298 return Visit(TSInfo->getTypeLoc());
1299 return false;
1300
1301 case TemplateArgument::Declaration:
1302 if (Expr *E = TAL.getSourceDeclExpression())
1303 return Visit(MakeCXCursor(E, StmtParent, TU));
1304 return false;
1305
1306 case TemplateArgument::Expression:
1307 if (Expr *E = TAL.getSourceExpression())
1308 return Visit(MakeCXCursor(E, StmtParent, TU));
1309 return false;
1310
1311 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001312 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001313 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1314 return true;
1315
Douglas Gregora7fc9012011-01-05 18:58:31 +00001316 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001317 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001318 }
1319
1320 return false;
1321}
1322
Ted Kremeneka0536d82010-05-07 01:04:29 +00001323bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1324 return VisitDeclContext(D);
1325}
1326
Douglas Gregor01829d32010-08-31 14:41:23 +00001327bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1328 return Visit(TL.getUnqualifiedLoc());
1329}
1330
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001332 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333
1334 // Some builtin types (such as Objective-C's "id", "sel", and
1335 // "Class") have associated declarations. Create cursors for those.
1336 QualType VisitType;
1337 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001338 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001339 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001340 case BuiltinType::Char_U:
1341 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001342 case BuiltinType::Char16:
1343 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001344 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001345 case BuiltinType::UInt:
1346 case BuiltinType::ULong:
1347 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001348 case BuiltinType::UInt128:
1349 case BuiltinType::Char_S:
1350 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001351 case BuiltinType::WChar_U:
1352 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001353 case BuiltinType::Short:
1354 case BuiltinType::Int:
1355 case BuiltinType::Long:
1356 case BuiltinType::LongLong:
1357 case BuiltinType::Int128:
1358 case BuiltinType::Float:
1359 case BuiltinType::Double:
1360 case BuiltinType::LongDouble:
1361 case BuiltinType::NullPtr:
1362 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001363 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001364 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001365 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001366 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001367
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001368 case BuiltinType::ObjCId:
1369 VisitType = Context.getObjCIdType();
1370 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001371
1372 case BuiltinType::ObjCClass:
1373 VisitType = Context.getObjCClassType();
1374 break;
1375
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001376 case BuiltinType::ObjCSel:
1377 VisitType = Context.getObjCSelType();
1378 break;
1379 }
1380
1381 if (!VisitType.isNull()) {
1382 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001383 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001384 TU));
1385 }
1386
1387 return false;
1388}
1389
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001390bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001391 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001392}
1393
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001394bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1395 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1396}
1397
1398bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001399 if (TL.isDefinition())
1400 return Visit(MakeCXCursor(TL.getDecl(), TU));
1401
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001402 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1403}
1404
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001405bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001406 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001407}
1408
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1410 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1411 return true;
1412
John McCallc12c5bb2010-05-15 11:32:37 +00001413 return false;
1414}
1415
1416bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1417 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1418 return true;
1419
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001420 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1421 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1422 TU)))
1423 return true;
1424 }
1425
1426 return false;
1427}
1428
1429bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001430 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001431}
1432
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001433bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1434 return Visit(TL.getInnerLoc());
1435}
1436
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001437bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1438 return Visit(TL.getPointeeLoc());
1439}
1440
1441bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1442 return Visit(TL.getPointeeLoc());
1443}
1444
1445bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1446 return Visit(TL.getPointeeLoc());
1447}
1448
1449bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001450 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001451}
1452
1453bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001455}
1456
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001457bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1458 return Visit(TL.getModifiedLoc());
1459}
1460
Douglas Gregor01829d32010-08-31 14:41:23 +00001461bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1462 bool SkipResultType) {
1463 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001464 return true;
1465
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001466 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001467 if (Decl *D = TL.getArg(I))
1468 if (Visit(MakeCXCursor(D, TU)))
1469 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001470
1471 return false;
1472}
1473
1474bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1475 if (Visit(TL.getElementLoc()))
1476 return true;
1477
1478 if (Expr *Size = TL.getSizeExpr())
1479 return Visit(MakeCXCursor(Size, StmtParent, TU));
1480
1481 return false;
1482}
1483
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001484bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1485 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001486 // Visit the template name.
1487 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1488 TL.getTemplateNameLoc()))
1489 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001490
1491 // Visit the template arguments.
1492 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1493 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1494 return true;
1495
1496 return false;
1497}
1498
Douglas Gregor2332c112010-01-21 20:48:56 +00001499bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1500 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1501}
1502
1503bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1504 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1505 return Visit(TSInfo->getTypeLoc());
1506
1507 return false;
1508}
1509
Sean Huntca63c202011-05-24 22:41:36 +00001510bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1511 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1512 return Visit(TSInfo->getTypeLoc());
1513
1514 return false;
1515}
1516
Douglas Gregor2494dd02011-03-01 01:34:45 +00001517bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1518 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1519 return true;
1520
1521 return false;
1522}
1523
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001524bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1525 DependentTemplateSpecializationTypeLoc TL) {
1526 // Visit the nested-name-specifier, if there is one.
1527 if (TL.getQualifierLoc() &&
1528 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1529 return true;
1530
1531 // Visit the template arguments.
1532 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1533 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1534 return true;
1535
1536 return false;
1537}
1538
Douglas Gregor9e876872011-03-01 18:12:44 +00001539bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1540 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1541 return true;
1542
1543 return Visit(TL.getNamedTypeLoc());
1544}
1545
Douglas Gregor7536dd52010-12-20 02:24:11 +00001546bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1547 return Visit(TL.getPatternLoc());
1548}
1549
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001550bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1551 if (Expr *E = TL.getUnderlyingExpr())
1552 return Visit(MakeCXCursor(E, StmtParent, TU));
1553
1554 return false;
1555}
1556
1557bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1558 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1559}
1560
1561#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1562bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1563 return Visit##PARENT##Loc(TL); \
1564}
1565
1566DEFAULT_TYPELOC_IMPL(Complex, Type)
1567DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1568DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1569DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1570DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1571DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1572DEFAULT_TYPELOC_IMPL(Vector, Type)
1573DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1574DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1575DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1576DEFAULT_TYPELOC_IMPL(Record, TagType)
1577DEFAULT_TYPELOC_IMPL(Enum, TagType)
1578DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1579DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1580DEFAULT_TYPELOC_IMPL(Auto, Type)
1581
Ted Kremenek3064ef92010-08-27 21:34:58 +00001582bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001583 // Visit the nested-name-specifier, if present.
1584 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1585 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1586 return true;
1587
Ted Kremenek3064ef92010-08-27 21:34:58 +00001588 if (D->isDefinition()) {
1589 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1590 E = D->bases_end(); I != E; ++I) {
1591 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1592 return true;
1593 }
1594 }
1595
1596 return VisitTagDecl(D);
1597}
1598
Ted Kremenek09dfa372010-02-18 05:46:33 +00001599bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001600 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1601 i != e; ++i)
1602 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001603 return true;
1604
1605 return false;
1606}
1607
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001608//===----------------------------------------------------------------------===//
1609// Data-recursive visitor methods.
1610//===----------------------------------------------------------------------===//
1611
Ted Kremenek28a71942010-11-13 00:36:47 +00001612namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001613#define DEF_JOB(NAME, DATA, KIND)\
1614class NAME : public VisitorJob {\
1615public:\
1616 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1617 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001618 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001619};
1620
1621DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1622DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001623DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001624DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenek60608ec2010-11-17 00:50:47 +00001625DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList,
1626 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001627DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001628#undef DEF_JOB
1629
1630class DeclVisit : public VisitorJob {
1631public:
1632 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1633 VisitorJob(parent, VisitorJob::DeclVisitKind,
1634 d, isFirst ? (void*) 1 : (void*) 0) {}
1635 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001636 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001637 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001638 Decl *get() const { return static_cast<Decl*>(data[0]); }
1639 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001640};
Ted Kremenek035dc412010-11-13 00:36:50 +00001641class TypeLocVisit : public VisitorJob {
1642public:
1643 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1644 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1645 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1646
1647 static bool classof(const VisitorJob *VJ) {
1648 return VJ->getKind() == TypeLocVisitKind;
1649 }
1650
Ted Kremenek82f3c502010-11-15 22:23:26 +00001651 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001652 QualType T = QualType::getFromOpaquePtr(data[0]);
1653 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001654 }
1655};
1656
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001657class LabelRefVisit : public VisitorJob {
1658public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001659 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1660 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001661 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001662
1663 static bool classof(const VisitorJob *VJ) {
1664 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1665 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001666 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001667 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001668 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001669};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001670
1671class NestedNameSpecifierLocVisit : public VisitorJob {
1672public:
1673 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1674 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1675 Qualifier.getNestedNameSpecifier(),
1676 Qualifier.getOpaqueData()) { }
1677
1678 static bool classof(const VisitorJob *VJ) {
1679 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1680 }
1681
1682 NestedNameSpecifierLoc get() const {
1683 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1684 data[1]);
1685 }
1686};
1687
Ted Kremenekf64d8032010-11-18 00:02:32 +00001688class DeclarationNameInfoVisit : public VisitorJob {
1689public:
1690 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1691 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1692 static bool classof(const VisitorJob *VJ) {
1693 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1694 }
1695 DeclarationNameInfo get() const {
1696 Stmt *S = static_cast<Stmt*>(data[0]);
1697 switch (S->getStmtClass()) {
1698 default:
1699 llvm_unreachable("Unhandled Stmt");
1700 case Stmt::CXXDependentScopeMemberExprClass:
1701 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1702 case Stmt::DependentScopeDeclRefExprClass:
1703 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1704 }
1705 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001706};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001707class MemberRefVisit : public VisitorJob {
1708public:
1709 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1710 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001711 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001712 static bool classof(const VisitorJob *VJ) {
1713 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1714 }
1715 FieldDecl *get() const {
1716 return static_cast<FieldDecl*>(data[0]);
1717 }
1718 SourceLocation getLoc() const {
1719 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1720 }
1721};
Ted Kremenek28a71942010-11-13 00:36:47 +00001722class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1723 VisitorWorkList &WL;
1724 CXCursor Parent;
1725public:
1726 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1727 : WL(wl), Parent(parent) {}
1728
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001729 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001730 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001731 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001732 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001733 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001734 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001735 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001736 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001737 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001738 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001739 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001740 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001741 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001742 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001743 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001744 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001745 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001746 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001747 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1748 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001749 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001750 void VisitIfStmt(IfStmt *If);
1751 void VisitInitListExpr(InitListExpr *IE);
1752 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001753 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001754 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001755 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1756 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001757 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001758 void VisitStmt(Stmt *S);
1759 void VisitSwitchStmt(SwitchStmt *S);
1760 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001761 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001762 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001763 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001764 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001765 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001766 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001767 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001768
Ted Kremenek28a71942010-11-13 00:36:47 +00001769private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001770 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001771 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Ted Kremenek60608ec2010-11-17 00:50:47 +00001772 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001773 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001774 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001775 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001776 void AddTypeLoc(TypeSourceInfo *TI);
1777 void EnqueueChildren(Stmt *S);
1778};
1779} // end anonyous namespace
1780
Ted Kremenekf64d8032010-11-18 00:02:32 +00001781void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1782 // 'S' should always be non-null, since it comes from the
1783 // statement we are visiting.
1784 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1785}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001786
1787void
1788EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1789 if (Qualifier)
1790 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1791}
1792
Ted Kremenek28a71942010-11-13 00:36:47 +00001793void EnqueueVisitor::AddStmt(Stmt *S) {
1794 if (S)
1795 WL.push_back(StmtVisit(S, Parent));
1796}
Ted Kremenek035dc412010-11-13 00:36:50 +00001797void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001798 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001799 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001800}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001801void EnqueueVisitor::
1802 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) {
1803 if (A)
1804 WL.push_back(ExplicitTemplateArgsVisit(
1805 const_cast<ExplicitTemplateArgumentList*>(A), Parent));
1806}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001807void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1808 if (D)
1809 WL.push_back(MemberRefVisit(D, L, Parent));
1810}
Ted Kremenek28a71942010-11-13 00:36:47 +00001811void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1812 if (TI)
1813 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1814 }
1815void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001816 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001817 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001818 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001819 }
1820 if (size == WL.size())
1821 return;
1822 // Now reverse the entries we just added. This will match the DFS
1823 // ordering performed by the worklist.
1824 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1825 std::reverse(I, E);
1826}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001827void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1828 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1829}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001830void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1831 AddDecl(B->getBlockDecl());
1832}
Ted Kremenek28a71942010-11-13 00:36:47 +00001833void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1834 EnqueueChildren(E);
1835 AddTypeLoc(E->getTypeSourceInfo());
1836}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001837void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1838 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1839 E = S->body_rend(); I != E; ++I) {
1840 AddStmt(*I);
1841 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001842}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001843void EnqueueVisitor::
1844VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1845 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1846 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001847 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1848 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001849 if (!E->isImplicitAccess())
1850 AddStmt(E->getBase());
1851}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001852void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1853 // Enqueue the initializer or constructor arguments.
1854 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1855 AddStmt(E->getConstructorArg(I-1));
1856 // Enqueue the array size, if any.
1857 AddStmt(E->getArraySize());
1858 // Enqueue the allocated type.
1859 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1860 // Enqueue the placement arguments.
1861 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1862 AddStmt(E->getPlacementArg(I-1));
1863}
Ted Kremenek28a71942010-11-13 00:36:47 +00001864void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001865 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1866 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001867 AddStmt(CE->getCallee());
1868 AddStmt(CE->getArg(0));
1869}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001870void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1871 // Visit the name of the type being destroyed.
1872 AddTypeLoc(E->getDestroyedTypeInfo());
1873 // Visit the scope type that looks disturbingly like the nested-name-specifier
1874 // but isn't.
1875 AddTypeLoc(E->getScopeTypeInfo());
1876 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001877 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1878 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001879 // Visit base expression.
1880 AddStmt(E->getBase());
1881}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001882void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1883 AddTypeLoc(E->getTypeSourceInfo());
1884}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001885void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1886 EnqueueChildren(E);
1887 AddTypeLoc(E->getTypeSourceInfo());
1888}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001889void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1890 EnqueueChildren(E);
1891 if (E->isTypeOperand())
1892 AddTypeLoc(E->getTypeOperandSourceInfo());
1893}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001894
1895void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1896 *E) {
1897 EnqueueChildren(E);
1898 AddTypeLoc(E->getTypeSourceInfo());
1899}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001900void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1901 EnqueueChildren(E);
1902 if (E->isTypeOperand())
1903 AddTypeLoc(E->getTypeOperandSourceInfo());
1904}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001905void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001906 if (DR->hasExplicitTemplateArgs()) {
1907 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1908 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001909 WL.push_back(DeclRefExprParts(DR, Parent));
1910}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001911void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1912 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1913 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001914 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001915}
Ted Kremenek035dc412010-11-13 00:36:50 +00001916void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1917 unsigned size = WL.size();
1918 bool isFirst = true;
1919 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1920 D != DEnd; ++D) {
1921 AddDecl(*D, isFirst);
1922 isFirst = false;
1923 }
1924 if (size == WL.size())
1925 return;
1926 // Now reverse the entries we just added. This will match the DFS
1927 // ordering performed by the worklist.
1928 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1929 std::reverse(I, E);
1930}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001931void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1932 AddStmt(E->getInit());
1933 typedef DesignatedInitExpr::Designator Designator;
1934 for (DesignatedInitExpr::reverse_designators_iterator
1935 D = E->designators_rbegin(), DEnd = E->designators_rend();
1936 D != DEnd; ++D) {
1937 if (D->isFieldDesignator()) {
1938 if (FieldDecl *Field = D->getField())
1939 AddMemberRef(Field, D->getFieldLoc());
1940 continue;
1941 }
1942 if (D->isArrayDesignator()) {
1943 AddStmt(E->getArrayIndex(*D));
1944 continue;
1945 }
1946 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1947 AddStmt(E->getArrayRangeEnd(*D));
1948 AddStmt(E->getArrayRangeStart(*D));
1949 }
1950}
Ted Kremenek28a71942010-11-13 00:36:47 +00001951void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1952 EnqueueChildren(E);
1953 AddTypeLoc(E->getTypeInfoAsWritten());
1954}
1955void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1956 AddStmt(FS->getBody());
1957 AddStmt(FS->getInc());
1958 AddStmt(FS->getCond());
1959 AddDecl(FS->getConditionVariable());
1960 AddStmt(FS->getInit());
1961}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001962void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1963 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1964}
Ted Kremenek28a71942010-11-13 00:36:47 +00001965void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1966 AddStmt(If->getElse());
1967 AddStmt(If->getThen());
1968 AddStmt(If->getCond());
1969 AddDecl(If->getConditionVariable());
1970}
1971void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1972 // We care about the syntactic form of the initializer list, only.
1973 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1974 IE = Syntactic;
1975 EnqueueChildren(IE);
1976}
1977void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001978 WL.push_back(MemberExprParts(M, Parent));
1979
1980 // If the base of the member access expression is an implicit 'this', don't
1981 // visit it.
1982 // FIXME: If we ever want to show these implicit accesses, this will be
1983 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001984 if (!M->isImplicitAccess())
1985 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001986}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001987void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1988 AddTypeLoc(E->getEncodedTypeSourceInfo());
1989}
Ted Kremenek28a71942010-11-13 00:36:47 +00001990void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1991 EnqueueChildren(M);
1992 AddTypeLoc(M->getClassReceiverTypeInfo());
1993}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001994void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1995 // Visit the components of the offsetof expression.
1996 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1997 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1998 const OffsetOfNode &Node = E->getComponent(I-1);
1999 switch (Node.getKind()) {
2000 case OffsetOfNode::Array:
2001 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2002 break;
2003 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002004 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002005 break;
2006 case OffsetOfNode::Identifier:
2007 case OffsetOfNode::Base:
2008 continue;
2009 }
2010 }
2011 // Visit the type into which we're computing the offset.
2012 AddTypeLoc(E->getTypeSourceInfo());
2013}
Ted Kremenek28a71942010-11-13 00:36:47 +00002014void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002015 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002016 WL.push_back(OverloadExprParts(E, Parent));
2017}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002018void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2019 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002020 EnqueueChildren(E);
2021 if (E->isArgumentType())
2022 AddTypeLoc(E->getArgumentTypeInfo());
2023}
Ted Kremenek28a71942010-11-13 00:36:47 +00002024void EnqueueVisitor::VisitStmt(Stmt *S) {
2025 EnqueueChildren(S);
2026}
2027void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2028 AddStmt(S->getBody());
2029 AddStmt(S->getCond());
2030 AddDecl(S->getConditionVariable());
2031}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002032
Ted Kremenek28a71942010-11-13 00:36:47 +00002033void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2034 AddStmt(W->getBody());
2035 AddStmt(W->getCond());
2036 AddDecl(W->getConditionVariable());
2037}
John Wiegley21ff2e52011-04-28 00:16:57 +00002038
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002039void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2040 AddTypeLoc(E->getQueriedTypeSourceInfo());
2041}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002042
2043void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002044 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002045 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002046}
2047
John Wiegley21ff2e52011-04-28 00:16:57 +00002048void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2049 AddTypeLoc(E->getQueriedTypeSourceInfo());
2050}
2051
John Wiegley55262202011-04-25 06:54:41 +00002052void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2053 EnqueueChildren(E);
2054}
2055
Ted Kremenek28a71942010-11-13 00:36:47 +00002056void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2057 VisitOverloadExpr(U);
2058 if (!U->isImplicitAccess())
2059 AddStmt(U->getBase());
2060}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002061void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2062 AddStmt(E->getSubExpr());
2063 AddTypeLoc(E->getWrittenTypeInfo());
2064}
Douglas Gregor94d96292011-01-19 20:34:17 +00002065void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2066 WL.push_back(SizeOfPackExprParts(E, Parent));
2067}
Ted Kremenek60458782010-11-12 21:34:16 +00002068
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002069void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002070 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002071}
2072
2073bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2074 if (RegionOfInterest.isValid()) {
2075 SourceRange Range = getRawCursorExtent(C);
2076 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2077 return false;
2078 }
2079 return true;
2080}
2081
2082bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2083 while (!WL.empty()) {
2084 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002085 VisitorJob LI = WL.back();
2086 WL.pop_back();
2087
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002088 // Set the Parent field, then back to its old value once we're done.
2089 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2090
2091 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002092 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002093 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002094 if (!D)
2095 continue;
2096
2097 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002098 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002099 return true;
2100
2101 continue;
2102 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002103 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2104 const ExplicitTemplateArgumentList *ArgList =
2105 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2106 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2107 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2108 Arg != ArgEnd; ++Arg) {
2109 if (VisitTemplateArgumentLoc(*Arg))
2110 return true;
2111 }
2112 continue;
2113 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002114 case VisitorJob::TypeLocVisitKind: {
2115 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002116 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002117 return true;
2118 continue;
2119 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002120 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002121 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002122 if (LabelStmt *stmt = LS->getStmt()) {
2123 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2124 TU))) {
2125 return true;
2126 }
2127 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002128 continue;
2129 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002130
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002131 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2132 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2133 if (VisitNestedNameSpecifierLoc(V->get()))
2134 return true;
2135 continue;
2136 }
2137
Ted Kremenekf64d8032010-11-18 00:02:32 +00002138 case VisitorJob::DeclarationNameInfoVisitKind: {
2139 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2140 ->get()))
2141 return true;
2142 continue;
2143 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002144 case VisitorJob::MemberRefVisitKind: {
2145 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2146 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2147 return true;
2148 continue;
2149 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002150 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002151 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002152 if (!S)
2153 continue;
2154
Ted Kremenekf1107452010-11-12 18:26:56 +00002155 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002156 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002157 if (!IsInRegionOfInterest(Cursor))
2158 continue;
2159 switch (Visitor(Cursor, Parent, ClientData)) {
2160 case CXChildVisit_Break: return true;
2161 case CXChildVisit_Continue: break;
2162 case CXChildVisit_Recurse:
2163 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002164 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002165 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002166 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002167 }
2168 case VisitorJob::MemberExprPartsKind: {
2169 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002170 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002171
2172 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002173 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2174 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002175 return true;
2176
2177 // Visit the declaration name.
2178 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2179 return true;
2180
2181 // Visit the explicitly-specified template arguments, if any.
2182 if (M->hasExplicitTemplateArgs()) {
2183 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2184 *ArgEnd = Arg + M->getNumTemplateArgs();
2185 Arg != ArgEnd; ++Arg) {
2186 if (VisitTemplateArgumentLoc(*Arg))
2187 return true;
2188 }
2189 }
2190 continue;
2191 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002192 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002193 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002194 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002195 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2196 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002197 return true;
2198 // Visit declaration name.
2199 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2200 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002201 continue;
2202 }
Ted Kremenek60458782010-11-12 21:34:16 +00002203 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002204 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002205 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002206 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2207 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002208 return true;
2209 // Visit the declaration name.
2210 if (VisitDeclarationNameInfo(O->getNameInfo()))
2211 return true;
2212 // Visit the overloaded declaration reference.
2213 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2214 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002215 continue;
2216 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002217 case VisitorJob::SizeOfPackExprPartsKind: {
2218 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2219 NamedDecl *Pack = E->getPack();
2220 if (isa<TemplateTypeParmDecl>(Pack)) {
2221 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2222 E->getPackLoc(), TU)))
2223 return true;
2224
2225 continue;
2226 }
2227
2228 if (isa<TemplateTemplateParmDecl>(Pack)) {
2229 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2230 E->getPackLoc(), TU)))
2231 return true;
2232
2233 continue;
2234 }
2235
2236 // Non-type template parameter packs and function parameter packs are
2237 // treated like DeclRefExpr cursors.
2238 continue;
2239 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002240 }
2241 }
2242 return false;
2243}
2244
Ted Kremenekcdba6592010-11-18 00:42:18 +00002245bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002246 VisitorWorkList *WL = 0;
2247 if (!WorkListFreeList.empty()) {
2248 WL = WorkListFreeList.back();
2249 WL->clear();
2250 WorkListFreeList.pop_back();
2251 }
2252 else {
2253 WL = new VisitorWorkList();
2254 WorkListCache.push_back(WL);
2255 }
2256 EnqueueWorkList(*WL, S);
2257 bool result = RunVisitorWorkList(*WL);
2258 WorkListFreeList.push_back(WL);
2259 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002260}
2261
Francois Pichet48a8d142011-07-25 22:00:44 +00002262namespace {
2263typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2264RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2265 const DeclarationNameInfo &NI,
2266 const SourceRange &QLoc,
2267 const ExplicitTemplateArgumentList *TemplateArgs = 0){
2268 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2269 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2270 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2271
2272 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2273
2274 RefNamePieces Pieces;
2275
2276 if (WantQualifier && QLoc.isValid())
2277 Pieces.push_back(QLoc);
2278
2279 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2280 Pieces.push_back(NI.getLoc());
2281
2282 if (WantTemplateArgs && TemplateArgs)
2283 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2284 TemplateArgs->RAngleLoc));
2285
2286 if (Kind == DeclarationName::CXXOperatorName) {
2287 Pieces.push_back(SourceLocation::getFromRawEncoding(
2288 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2289 Pieces.push_back(SourceLocation::getFromRawEncoding(
2290 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2291 }
2292
2293 if (WantSinglePiece) {
2294 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2295 Pieces.clear();
2296 Pieces.push_back(R);
2297 }
2298
2299 return Pieces;
2300}
2301}
2302
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002303//===----------------------------------------------------------------------===//
2304// Misc. API hooks.
2305//===----------------------------------------------------------------------===//
2306
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002307static llvm::sys::Mutex EnableMultithreadingMutex;
2308static bool EnabledMultithreading;
2309
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002310extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002311CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2312 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002313 // Disable pretty stack trace functionality, which will otherwise be a very
2314 // poor citizen of the world and set up all sorts of signal handlers.
2315 llvm::DisablePrettyStackTrace = true;
2316
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002317 // We use crash recovery to make some of our APIs more reliable, implicitly
2318 // enable it.
2319 llvm::CrashRecoveryContext::Enable();
2320
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002321 // Enable support for multithreading in LLVM.
2322 {
2323 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2324 if (!EnabledMultithreading) {
2325 llvm::llvm_start_multithreaded();
2326 EnabledMultithreading = true;
2327 }
2328 }
2329
Douglas Gregora030b7c2010-01-22 20:35:53 +00002330 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002331 if (excludeDeclarationsFromPCH)
2332 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002333 if (displayDiagnostics)
2334 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002335 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002336}
2337
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002338void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002339 if (CIdx)
2340 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002341}
2342
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002343void clang_toggleCrashRecovery(unsigned isEnabled) {
2344 if (isEnabled)
2345 llvm::CrashRecoveryContext::Enable();
2346 else
2347 llvm::CrashRecoveryContext::Disable();
2348}
2349
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002350CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002351 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002352 if (!CIdx)
2353 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002354
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002355 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002356 FileSystemOptions FileSystemOpts;
2357 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002358
Douglas Gregor28019772010-04-05 23:52:57 +00002359 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002360 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002361 CXXIdx->getOnlyLocalDecls(),
2362 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002363 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002364}
2365
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002366unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002367 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002368 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002369}
2370
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002371CXTranslationUnit
2372clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2373 const char *source_filename,
2374 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002375 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002376 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002377 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002378 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002379 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002380 return clang_parseTranslationUnit(CIdx, source_filename,
2381 command_line_args, num_command_line_args,
2382 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002383 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002384}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002385
2386struct ParseTranslationUnitInfo {
2387 CXIndex CIdx;
2388 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002389 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002390 int num_command_line_args;
2391 struct CXUnsavedFile *unsaved_files;
2392 unsigned num_unsaved_files;
2393 unsigned options;
2394 CXTranslationUnit result;
2395};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002396static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002397 ParseTranslationUnitInfo *PTUI =
2398 static_cast<ParseTranslationUnitInfo*>(UserData);
2399 CXIndex CIdx = PTUI->CIdx;
2400 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002401 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002402 int num_command_line_args = PTUI->num_command_line_args;
2403 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2404 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2405 unsigned options = PTUI->options;
2406 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002407
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002408 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002409 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002410
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002411 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2412
Douglas Gregor44c181a2010-07-23 00:33:23 +00002413 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002414 // FIXME: Add a flag for modules.
2415 TranslationUnitKind TUKind
2416 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002417 bool CacheCodeCompetionResults
2418 = options & CXTranslationUnit_CacheCompletionResults;
2419
Douglas Gregor5352ac02010-01-28 00:27:43 +00002420 // Configure the diagnostics.
2421 DiagnosticOptions DiagOpts;
Ted Kremenek25a11e12011-03-22 01:15:24 +00002422 llvm::IntrusiveRefCntPtr<Diagnostic>
2423 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2424 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425
Ted Kremenek25a11e12011-03-22 01:15:24 +00002426 // Recover resources if we crash before exiting this function.
2427 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
2428 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
2429 DiagCleanup(Diags.getPtr());
2430
2431 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2432 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2433
2434 // Recover resources if we crash before exiting this function.
2435 llvm::CrashRecoveryContextCleanupRegistrar<
2436 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2437
Douglas Gregor4db64a42010-01-23 00:14:00 +00002438 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002439 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002440 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002441 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002442 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2443 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002444 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002445
Ted Kremenek25a11e12011-03-22 01:15:24 +00002446 llvm::OwningPtr<std::vector<const char *> >
2447 Args(new std::vector<const char*>());
2448
2449 // Recover resources if we crash before exiting this method.
2450 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2451 ArgsCleanup(Args.get());
2452
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002453 // Since the Clang C library is primarily used by batch tools dealing with
2454 // (often very broken) source code, where spell-checking can have a
2455 // significant negative impact on performance (particularly when
2456 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002457 // Only do this if we haven't found a spell-checking-related argument.
2458 bool FoundSpellCheckingArgument = false;
2459 for (int I = 0; I != num_command_line_args; ++I) {
2460 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2461 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2462 FoundSpellCheckingArgument = true;
2463 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002464 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002465 }
2466 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002467 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002468
Ted Kremenek25a11e12011-03-22 01:15:24 +00002469 Args->insert(Args->end(), command_line_args,
2470 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002471
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002472 // The 'source_filename' argument is optional. If the caller does not
2473 // specify it then it is assumed that the source file is specified
2474 // in the actual argument list.
2475 // Put the source file after command_line_args otherwise if '-x' flag is
2476 // present it will be unused.
2477 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002478 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002479
Douglas Gregor44c181a2010-07-23 00:33:23 +00002480 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002481 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002482 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002483 Args->push_back("-Xclang");
2484 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002485 NestedMacroExpansions
2486 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002487 }
2488
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002489 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002490 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002491 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2492 /* vector::data() not portable */,
2493 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002494 Diags,
2495 CXXIdx->getClangResourcesPath(),
2496 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002497 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002498 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002499 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002500 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002501 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002502 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002503 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002504 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002505
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002506 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002507 // Make sure to check that 'Unit' is non-NULL.
2508 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2509 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2510 DEnd = Unit->stored_diag_end();
2511 D != DEnd; ++D) {
2512 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2513 CXString Msg = clang_formatDiagnostic(&Diag,
2514 clang_defaultDiagnosticDisplayOptions());
2515 fprintf(stderr, "%s\n", clang_getCString(Msg));
2516 clang_disposeString(Msg);
2517 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002518#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002519 // On Windows, force a flush, since there may be multiple copies of
2520 // stderr and stdout in the file system, all with different buffers
2521 // but writing to the same device.
2522 fflush(stderr);
2523#endif
2524 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002525 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002526
Ted Kremeneka60ed472010-11-16 08:15:36 +00002527 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002528}
2529CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2530 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002531 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002532 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002533 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002534 unsigned num_unsaved_files,
2535 unsigned options) {
2536 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002537 num_command_line_args, unsaved_files,
2538 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002539 llvm::CrashRecoveryContext CRC;
2540
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002541 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002542 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2543 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2544 fprintf(stderr, " 'command_line_args' : [");
2545 for (int i = 0; i != num_command_line_args; ++i) {
2546 if (i)
2547 fprintf(stderr, ", ");
2548 fprintf(stderr, "'%s'", command_line_args[i]);
2549 }
2550 fprintf(stderr, "],\n");
2551 fprintf(stderr, " 'unsaved_files' : [");
2552 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2553 if (i)
2554 fprintf(stderr, ", ");
2555 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2556 unsaved_files[i].Length);
2557 }
2558 fprintf(stderr, "],\n");
2559 fprintf(stderr, " 'options' : %d,\n", options);
2560 fprintf(stderr, "}\n");
2561
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002562 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002563 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2564 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002565 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002566
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002567 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002568}
2569
Douglas Gregor19998442010-08-13 15:35:05 +00002570unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2571 return CXSaveTranslationUnit_None;
2572}
2573
2574int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2575 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002576 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002577 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002578
Douglas Gregor39c411f2011-07-06 16:43:36 +00002579 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002580 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2581 PrintLibclangResourceUsage(TU);
2582 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002583}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002584
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002585void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002586 if (CTUnit) {
2587 // If the translation unit has been marked as unsafe to free, just discard
2588 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002589 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002590 return;
2591
Ted Kremeneka60ed472010-11-16 08:15:36 +00002592 delete static_cast<ASTUnit *>(CTUnit->TUData);
2593 disposeCXStringPool(CTUnit->StringPool);
2594 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002595 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002596}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002597
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002598unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2599 return CXReparse_None;
2600}
2601
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002602struct ReparseTranslationUnitInfo {
2603 CXTranslationUnit TU;
2604 unsigned num_unsaved_files;
2605 struct CXUnsavedFile *unsaved_files;
2606 unsigned options;
2607 int result;
2608};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002609
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002610static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002611 ReparseTranslationUnitInfo *RTUI =
2612 static_cast<ReparseTranslationUnitInfo*>(UserData);
2613 CXTranslationUnit TU = RTUI->TU;
2614 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2615 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2616 unsigned options = RTUI->options;
2617 (void) options;
2618 RTUI->result = 1;
2619
Douglas Gregorabc563f2010-07-19 21:46:24 +00002620 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002621 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002622
Ted Kremeneka60ed472010-11-16 08:15:36 +00002623 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002624 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002625
Ted Kremenek25a11e12011-03-22 01:15:24 +00002626 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2627 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2628
2629 // Recover resources if we crash before exiting this function.
2630 llvm::CrashRecoveryContextCleanupRegistrar<
2631 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2632
Douglas Gregorabc563f2010-07-19 21:46:24 +00002633 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002634 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002635 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002636 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002637 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2638 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002639 }
2640
Ted Kremenek4ee99262011-03-22 20:16:19 +00002641 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2642 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002643 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002644}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002645
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002646int clang_reparseTranslationUnit(CXTranslationUnit TU,
2647 unsigned num_unsaved_files,
2648 struct CXUnsavedFile *unsaved_files,
2649 unsigned options) {
2650 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2651 options, 0 };
2652 llvm::CrashRecoveryContext CRC;
2653
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002654 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002655 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002656 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002657 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002658 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2659 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002660
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002661 return RTUI.result;
2662}
2663
Douglas Gregordf95a132010-08-09 20:45:32 +00002664
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002665CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002666 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002667 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002668
Ted Kremeneka60ed472010-11-16 08:15:36 +00002669 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002670 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002671}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002672
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002673CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002674 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002675 return Result;
2676}
2677
Ted Kremenekfb480492010-01-13 21:46:36 +00002678} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002679
Ted Kremenekfb480492010-01-13 21:46:36 +00002680//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002681// CXSourceLocation and CXSourceRange Operations.
2682//===----------------------------------------------------------------------===//
2683
Douglas Gregorb9790342010-01-22 21:44:22 +00002684extern "C" {
2685CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002686 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002687 return Result;
2688}
2689
2690unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002691 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2692 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2693 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002694}
2695
2696CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2697 CXFile file,
2698 unsigned line,
2699 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002700 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002701 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002702
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002703 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002704 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002705 const FileEntry *File = static_cast<const FileEntry *>(file);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002706 SourceLocation SLoc = CXXUnit->getLocation(File, line, column);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002707 if (SLoc.isInvalid()) {
2708 if (Logging)
2709 llvm::errs() << "clang_getLocation(\"" << File->getName()
2710 << "\", " << line << ", " << column << ") = invalid\n";
2711 return clang_getNullLocation();
2712 }
2713
2714 if (Logging)
2715 llvm::errs() << "clang_getLocation(\"" << File->getName()
2716 << "\", " << line << ", " << column << ") = "
2717 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002718
2719 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2720}
2721
2722CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2723 CXFile file,
2724 unsigned offset) {
2725 if (!tu || !file)
2726 return clang_getNullLocation();
2727
Ted Kremeneka60ed472010-11-16 08:15:36 +00002728 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002729 SourceLocation SLoc
2730 = CXXUnit->getLocation(static_cast<const FileEntry *>(file), offset);
David Chisnall83889a72010-10-15 17:07:39 +00002731 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002732
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002733 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002734}
2735
Douglas Gregor5352ac02010-01-28 00:27:43 +00002736CXSourceRange clang_getNullRange() {
2737 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2738 return Result;
2739}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002740
Douglas Gregor5352ac02010-01-28 00:27:43 +00002741CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2742 if (begin.ptr_data[0] != end.ptr_data[0] ||
2743 begin.ptr_data[1] != end.ptr_data[1])
2744 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002745
2746 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002747 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002748 return Result;
2749}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002750
2751unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2752{
2753 return range1.ptr_data[0] == range2.ptr_data[0]
2754 && range1.ptr_data[1] == range2.ptr_data[1]
2755 && range1.begin_int_data == range2.begin_int_data
2756 && range1.end_int_data == range2.end_int_data;
2757}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002758} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002759
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002760static void createNullLocation(CXFile *file, unsigned *line,
2761 unsigned *column, unsigned *offset) {
2762 if (file)
2763 *file = 0;
2764 if (line)
2765 *line = 0;
2766 if (column)
2767 *column = 0;
2768 if (offset)
2769 *offset = 0;
2770 return;
2771}
2772
2773extern "C" {
Chandler Carruth20174222011-08-31 16:53:37 +00002774void clang_getExpansionLocation(CXSourceLocation location,
2775 CXFile *file,
2776 unsigned *line,
2777 unsigned *column,
2778 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002779 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2780
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002781 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002782 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002783 return;
2784 }
2785
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002786 const SourceManager &SM =
2787 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth20174222011-08-31 16:53:37 +00002788 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002789
Chandler Carruthcea731a2011-07-14 16:07:57 +00002790 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002791 // This can manifest in invalid code.
Chandler Carruth20174222011-08-31 16:53:37 +00002792 FileID fileID = SM.getFileID(ExpansionLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002793 bool Invalid = false;
2794 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2795 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002796 createNullLocation(file, line, column, offset);
2797 return;
2798 }
2799
Douglas Gregor1db19de2010-01-19 21:36:55 +00002800 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002801 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002802 if (line)
Chandler Carruth20174222011-08-31 16:53:37 +00002803 *line = SM.getExpansionLineNumber(ExpansionLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002804 if (column)
Chandler Carruth20174222011-08-31 16:53:37 +00002805 *column = SM.getExpansionColumnNumber(ExpansionLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002806 if (offset)
Chandler Carruth20174222011-08-31 16:53:37 +00002807 *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2808}
2809
Argyrios Kyrtzidise6be34d2011-09-13 21:49:08 +00002810void clang_getPresumedLocation(CXSourceLocation location,
2811 CXString *filename,
2812 unsigned *line,
2813 unsigned *column) {
2814 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2815
2816 if (!location.ptr_data[0] || Loc.isInvalid()) {
2817 if (filename)
2818 *filename = createCXString("");
2819 if (line)
2820 *line = 0;
2821 if (column)
2822 *column = 0;
2823 }
2824 else {
2825 const SourceManager &SM =
2826 *static_cast<const SourceManager*>(location.ptr_data[0]);
2827 PresumedLoc PreLoc = SM.getPresumedLoc(Loc);
2828
2829 if (filename)
2830 *filename = createCXString(PreLoc.getFilename());
2831 if (line)
2832 *line = PreLoc.getLine();
2833 if (column)
2834 *column = PreLoc.getColumn();
2835 }
2836}
2837
Chandler Carruth20174222011-08-31 16:53:37 +00002838void clang_getInstantiationLocation(CXSourceLocation location,
2839 CXFile *file,
2840 unsigned *line,
2841 unsigned *column,
2842 unsigned *offset) {
2843 // Redirect to new API.
2844 clang_getExpansionLocation(location, file, line, column, offset);
Douglas Gregore69517c2010-01-26 03:07:15 +00002845}
2846
Douglas Gregora9b06d42010-11-09 06:24:54 +00002847void clang_getSpellingLocation(CXSourceLocation location,
2848 CXFile *file,
2849 unsigned *line,
2850 unsigned *column,
2851 unsigned *offset) {
2852 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2853
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002854 if (!location.ptr_data[0] || Loc.isInvalid())
2855 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002856
2857 const SourceManager &SM =
2858 *static_cast<const SourceManager*>(location.ptr_data[0]);
2859 SourceLocation SpellLoc = Loc;
2860 if (SpellLoc.isMacroID()) {
2861 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2862 if (SimpleSpellingLoc.isFileID() &&
2863 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2864 SpellLoc = SimpleSpellingLoc;
2865 else
Chandler Carruth40278532011-07-25 16:49:02 +00002866 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002867 }
2868
2869 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2870 FileID FID = LocInfo.first;
2871 unsigned FileOffset = LocInfo.second;
2872
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002873 if (FID.isInvalid())
2874 return createNullLocation(file, line, column, offset);
2875
Douglas Gregora9b06d42010-11-09 06:24:54 +00002876 if (file)
2877 *file = (void *)SM.getFileEntryForID(FID);
2878 if (line)
2879 *line = SM.getLineNumber(FID, FileOffset);
2880 if (column)
2881 *column = SM.getColumnNumber(FID, FileOffset);
2882 if (offset)
2883 *offset = FileOffset;
2884}
2885
Douglas Gregor1db19de2010-01-19 21:36:55 +00002886CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002887 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002888 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002889 return Result;
2890}
2891
2892CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002893 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002894 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002895 return Result;
2896}
2897
Douglas Gregorb9790342010-01-22 21:44:22 +00002898} // end: extern "C"
2899
Douglas Gregor1db19de2010-01-19 21:36:55 +00002900//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002901// CXFile Operations.
2902//===----------------------------------------------------------------------===//
2903
2904extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002905CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002906 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002907 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002908
Steve Naroff88145032009-10-27 14:35:18 +00002909 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002910 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002911}
2912
2913time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002914 if (!SFile)
2915 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002916
Steve Naroff88145032009-10-27 14:35:18 +00002917 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2918 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002919}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002920
Douglas Gregorb9790342010-01-22 21:44:22 +00002921CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2922 if (!tu)
2923 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002924
Ted Kremeneka60ed472010-11-16 08:15:36 +00002925 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002926
Douglas Gregorb9790342010-01-22 21:44:22 +00002927 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002928 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002929}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002930
Douglas Gregordd3e5542011-05-04 00:14:37 +00002931unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2932 if (!tu || !file)
2933 return 0;
2934
2935 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2936 FileEntry *FEnt = static_cast<FileEntry *>(file);
2937 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2938 .isFileMultipleIncludeGuarded(FEnt);
2939}
2940
Ted Kremenekfb480492010-01-13 21:46:36 +00002941} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002942
Ted Kremenekfb480492010-01-13 21:46:36 +00002943//===----------------------------------------------------------------------===//
2944// CXCursor Operations.
2945//===----------------------------------------------------------------------===//
2946
Ted Kremenekfb480492010-01-13 21:46:36 +00002947static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002948 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002949 return getDeclFromExpr(CE->getSubExpr());
2950
Ted Kremenekfb480492010-01-13 21:46:36 +00002951 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2952 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002953 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2954 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002955 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2956 return ME->getMemberDecl();
2957 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2958 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002959 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002960 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002961
Ted Kremenekfb480492010-01-13 21:46:36 +00002962 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2963 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002964 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002965 if (!CE->isElidable())
2966 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002967 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2968 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002969
Douglas Gregordb1314e2010-10-01 21:11:22 +00002970 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2971 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002972 if (SubstNonTypeTemplateParmPackExpr *NTTP
2973 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2974 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002975 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2976 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2977 isa<ParmVarDecl>(SizeOfPack->getPack()))
2978 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002979
Ted Kremenekfb480492010-01-13 21:46:36 +00002980 return 0;
2981}
2982
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002983static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002984 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2985 return getLocationFromExpr(CE->getSubExpr());
2986
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002987 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2988 return /*FIXME:*/Msg->getLeftLoc();
2989 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2990 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002991 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2992 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002993 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2994 return Member->getMemberLoc();
2995 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2996 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002997 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2998 return SizeOfPack->getPackLoc();
2999
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003000 return E->getLocStart();
3001}
3002
Ted Kremenekfb480492010-01-13 21:46:36 +00003003extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003004
3005unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003006 CXCursorVisitor visitor,
3007 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003008 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003009 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003010 return CursorVis.VisitChildren(parent);
3011}
3012
David Chisnall3387c652010-11-03 14:12:26 +00003013#ifndef __has_feature
3014#define __has_feature(x) 0
3015#endif
3016#if __has_feature(blocks)
3017typedef enum CXChildVisitResult
3018 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3019
3020static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3021 CXClientData client_data) {
3022 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3023 return block(cursor, parent);
3024}
3025#else
3026// If we are compiled with a compiler that doesn't have native blocks support,
3027// define and call the block manually, so the
3028typedef struct _CXChildVisitResult
3029{
3030 void *isa;
3031 int flags;
3032 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003033 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3034 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003035} *CXCursorVisitorBlock;
3036
3037static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3038 CXClientData client_data) {
3039 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3040 return block->invoke(block, cursor, parent);
3041}
3042#endif
3043
3044
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003045unsigned clang_visitChildrenWithBlock(CXCursor parent,
3046 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003047 return clang_visitChildren(parent, visitWithBlock, block);
3048}
3049
Douglas Gregor78205d42010-01-20 21:45:58 +00003050static CXString getDeclSpelling(Decl *D) {
3051 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003052 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003053 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003054 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3055 return createCXString(Property->getIdentifier()->getName());
3056
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003057 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003058 }
3059
Douglas Gregor78205d42010-01-20 21:45:58 +00003060 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003061 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003062
Douglas Gregor78205d42010-01-20 21:45:58 +00003063 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3064 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3065 // and returns different names. NamedDecl returns the class name and
3066 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003067 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003068
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003069 if (isa<UsingDirectiveDecl>(D))
3070 return createCXString("");
3071
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003072 llvm::SmallString<1024> S;
3073 llvm::raw_svector_ostream os(S);
3074 ND->printName(os);
3075
3076 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003077}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003078
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003079CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003080 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003081 return clang_getTranslationUnitSpelling(
3082 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003083
Steve Narofff334b4e2009-09-02 18:26:48 +00003084 if (clang_isReference(C.kind)) {
3085 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003086 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003087 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003088 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003089 }
3090 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003091 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003092 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003093 }
3094 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003095 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003096 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003097 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003098 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003099 case CXCursor_CXXBaseSpecifier: {
3100 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3101 return createCXString(B->getType().getAsString());
3102 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003103 case CXCursor_TypeRef: {
3104 TypeDecl *Type = getCursorTypeRef(C).first;
3105 assert(Type && "Missing type decl");
3106
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003107 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3108 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003109 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003110 case CXCursor_TemplateRef: {
3111 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003112 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003113
3114 return createCXString(Template->getNameAsString());
3115 }
Douglas Gregor69319002010-08-31 23:48:11 +00003116
3117 case CXCursor_NamespaceRef: {
3118 NamedDecl *NS = getCursorNamespaceRef(C).first;
3119 assert(NS && "Missing namespace decl");
3120
3121 return createCXString(NS->getNameAsString());
3122 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003123
Douglas Gregora67e03f2010-09-09 21:42:20 +00003124 case CXCursor_MemberRef: {
3125 FieldDecl *Field = getCursorMemberRef(C).first;
3126 assert(Field && "Missing member decl");
3127
3128 return createCXString(Field->getNameAsString());
3129 }
3130
Douglas Gregor36897b02010-09-10 00:22:18 +00003131 case CXCursor_LabelRef: {
3132 LabelStmt *Label = getCursorLabelRef(C).first;
3133 assert(Label && "Missing label");
3134
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003135 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003136 }
3137
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003138 case CXCursor_OverloadedDeclRef: {
3139 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3140 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3141 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3142 return createCXString(ND->getNameAsString());
3143 return createCXString("");
3144 }
3145 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3146 return createCXString(E->getName().getAsString());
3147 OverloadedTemplateStorage *Ovl
3148 = Storage.get<OverloadedTemplateStorage*>();
3149 if (Ovl->size() == 0)
3150 return createCXString("");
3151 return createCXString((*Ovl->begin())->getNameAsString());
3152 }
3153
Daniel Dunbaracca7252009-11-30 20:42:49 +00003154 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003155 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003156 }
3157 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003158
3159 if (clang_isExpression(C.kind)) {
3160 Decl *D = getDeclFromExpr(getCursorExpr(C));
3161 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003162 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003163 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003164 }
3165
Douglas Gregor36897b02010-09-10 00:22:18 +00003166 if (clang_isStatement(C.kind)) {
3167 Stmt *S = getCursorStmt(C);
3168 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003169 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003170
3171 return createCXString("");
3172 }
3173
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003174 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003175 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003176 ->getNameStart());
3177
Douglas Gregor572feb22010-03-18 18:04:21 +00003178 if (C.kind == CXCursor_MacroDefinition)
3179 return createCXString(getCursorMacroDefinition(C)->getName()
3180 ->getNameStart());
3181
Douglas Gregorecdcb882010-10-20 22:00:55 +00003182 if (C.kind == CXCursor_InclusionDirective)
3183 return createCXString(getCursorInclusionDirective(C)->getFileName());
3184
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003185 if (clang_isDeclaration(C.kind))
3186 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003187
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003188 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003189}
3190
Douglas Gregor358559d2010-10-02 22:49:11 +00003191CXString clang_getCursorDisplayName(CXCursor C) {
3192 if (!clang_isDeclaration(C.kind))
3193 return clang_getCursorSpelling(C);
3194
3195 Decl *D = getCursorDecl(C);
3196 if (!D)
3197 return createCXString("");
3198
3199 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3200 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3201 D = FunTmpl->getTemplatedDecl();
3202
3203 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3204 llvm::SmallString<64> Str;
3205 llvm::raw_svector_ostream OS(Str);
3206 OS << Function->getNameAsString();
3207 if (Function->getPrimaryTemplate())
3208 OS << "<>";
3209 OS << "(";
3210 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3211 if (I)
3212 OS << ", ";
3213 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3214 }
3215
3216 if (Function->isVariadic()) {
3217 if (Function->getNumParams())
3218 OS << ", ";
3219 OS << "...";
3220 }
3221 OS << ")";
3222 return createCXString(OS.str());
3223 }
3224
3225 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3226 llvm::SmallString<64> Str;
3227 llvm::raw_svector_ostream OS(Str);
3228 OS << ClassTemplate->getNameAsString();
3229 OS << "<";
3230 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3231 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3232 if (I)
3233 OS << ", ";
3234
3235 NamedDecl *Param = Params->getParam(I);
3236 if (Param->getIdentifier()) {
3237 OS << Param->getIdentifier()->getName();
3238 continue;
3239 }
3240
3241 // There is no parameter name, which makes this tricky. Try to come up
3242 // with something useful that isn't too long.
3243 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3244 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3245 else if (NonTypeTemplateParmDecl *NTTP
3246 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3247 OS << NTTP->getType().getAsString(Policy);
3248 else
3249 OS << "template<...> class";
3250 }
3251
3252 OS << ">";
3253 return createCXString(OS.str());
3254 }
3255
3256 if (ClassTemplateSpecializationDecl *ClassSpec
3257 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3258 // If the type was explicitly written, use that.
3259 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3260 return createCXString(TSInfo->getType().getAsString(Policy));
3261
3262 llvm::SmallString<64> Str;
3263 llvm::raw_svector_ostream OS(Str);
3264 OS << ClassSpec->getNameAsString();
3265 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003266 ClassSpec->getTemplateArgs().data(),
3267 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003268 Policy);
3269 return createCXString(OS.str());
3270 }
3271
3272 return clang_getCursorSpelling(C);
3273}
3274
Ted Kremeneke68fff62010-02-17 00:41:32 +00003275CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003276 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003277 case CXCursor_FunctionDecl:
3278 return createCXString("FunctionDecl");
3279 case CXCursor_TypedefDecl:
3280 return createCXString("TypedefDecl");
3281 case CXCursor_EnumDecl:
3282 return createCXString("EnumDecl");
3283 case CXCursor_EnumConstantDecl:
3284 return createCXString("EnumConstantDecl");
3285 case CXCursor_StructDecl:
3286 return createCXString("StructDecl");
3287 case CXCursor_UnionDecl:
3288 return createCXString("UnionDecl");
3289 case CXCursor_ClassDecl:
3290 return createCXString("ClassDecl");
3291 case CXCursor_FieldDecl:
3292 return createCXString("FieldDecl");
3293 case CXCursor_VarDecl:
3294 return createCXString("VarDecl");
3295 case CXCursor_ParmDecl:
3296 return createCXString("ParmDecl");
3297 case CXCursor_ObjCInterfaceDecl:
3298 return createCXString("ObjCInterfaceDecl");
3299 case CXCursor_ObjCCategoryDecl:
3300 return createCXString("ObjCCategoryDecl");
3301 case CXCursor_ObjCProtocolDecl:
3302 return createCXString("ObjCProtocolDecl");
3303 case CXCursor_ObjCPropertyDecl:
3304 return createCXString("ObjCPropertyDecl");
3305 case CXCursor_ObjCIvarDecl:
3306 return createCXString("ObjCIvarDecl");
3307 case CXCursor_ObjCInstanceMethodDecl:
3308 return createCXString("ObjCInstanceMethodDecl");
3309 case CXCursor_ObjCClassMethodDecl:
3310 return createCXString("ObjCClassMethodDecl");
3311 case CXCursor_ObjCImplementationDecl:
3312 return createCXString("ObjCImplementationDecl");
3313 case CXCursor_ObjCCategoryImplDecl:
3314 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003315 case CXCursor_CXXMethod:
3316 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003317 case CXCursor_UnexposedDecl:
3318 return createCXString("UnexposedDecl");
3319 case CXCursor_ObjCSuperClassRef:
3320 return createCXString("ObjCSuperClassRef");
3321 case CXCursor_ObjCProtocolRef:
3322 return createCXString("ObjCProtocolRef");
3323 case CXCursor_ObjCClassRef:
3324 return createCXString("ObjCClassRef");
3325 case CXCursor_TypeRef:
3326 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003327 case CXCursor_TemplateRef:
3328 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003329 case CXCursor_NamespaceRef:
3330 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003331 case CXCursor_MemberRef:
3332 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003333 case CXCursor_LabelRef:
3334 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003335 case CXCursor_OverloadedDeclRef:
3336 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003337 case CXCursor_UnexposedExpr:
3338 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003339 case CXCursor_BlockExpr:
3340 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003341 case CXCursor_DeclRefExpr:
3342 return createCXString("DeclRefExpr");
3343 case CXCursor_MemberRefExpr:
3344 return createCXString("MemberRefExpr");
3345 case CXCursor_CallExpr:
3346 return createCXString("CallExpr");
3347 case CXCursor_ObjCMessageExpr:
3348 return createCXString("ObjCMessageExpr");
3349 case CXCursor_UnexposedStmt:
3350 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003351 case CXCursor_LabelStmt:
3352 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003353 case CXCursor_InvalidFile:
3354 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003355 case CXCursor_InvalidCode:
3356 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003357 case CXCursor_NoDeclFound:
3358 return createCXString("NoDeclFound");
3359 case CXCursor_NotImplemented:
3360 return createCXString("NotImplemented");
3361 case CXCursor_TranslationUnit:
3362 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003363 case CXCursor_UnexposedAttr:
3364 return createCXString("UnexposedAttr");
3365 case CXCursor_IBActionAttr:
3366 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003367 case CXCursor_IBOutletAttr:
3368 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003369 case CXCursor_IBOutletCollectionAttr:
3370 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003371 case CXCursor_CXXFinalAttr:
3372 return createCXString("attribute(final)");
3373 case CXCursor_CXXOverrideAttr:
3374 return createCXString("attribute(override)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003375 case CXCursor_PreprocessingDirective:
3376 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003377 case CXCursor_MacroDefinition:
3378 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003379 case CXCursor_MacroExpansion:
3380 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003381 case CXCursor_InclusionDirective:
3382 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003383 case CXCursor_Namespace:
3384 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003385 case CXCursor_LinkageSpec:
3386 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003387 case CXCursor_CXXBaseSpecifier:
3388 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003389 case CXCursor_Constructor:
3390 return createCXString("CXXConstructor");
3391 case CXCursor_Destructor:
3392 return createCXString("CXXDestructor");
3393 case CXCursor_ConversionFunction:
3394 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003395 case CXCursor_TemplateTypeParameter:
3396 return createCXString("TemplateTypeParameter");
3397 case CXCursor_NonTypeTemplateParameter:
3398 return createCXString("NonTypeTemplateParameter");
3399 case CXCursor_TemplateTemplateParameter:
3400 return createCXString("TemplateTemplateParameter");
3401 case CXCursor_FunctionTemplate:
3402 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003403 case CXCursor_ClassTemplate:
3404 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003405 case CXCursor_ClassTemplatePartialSpecialization:
3406 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003407 case CXCursor_NamespaceAlias:
3408 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003409 case CXCursor_UsingDirective:
3410 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003411 case CXCursor_UsingDeclaration:
3412 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003413 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003414 return createCXString("TypeAliasDecl");
3415 case CXCursor_ObjCSynthesizeDecl:
3416 return createCXString("ObjCSynthesizeDecl");
3417 case CXCursor_ObjCDynamicDecl:
3418 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003419 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003420
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003421 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003422 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003423}
Steve Naroff89922f82009-08-31 00:59:03 +00003424
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003425struct GetCursorData {
3426 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003427 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003428 CXCursor &BestCursor;
3429
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003430 GetCursorData(SourceManager &SM,
3431 SourceLocation tokenBegin, CXCursor &outputCursor)
3432 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3433 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3434 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003435};
3436
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003437static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3438 CXCursor parent,
3439 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003440 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3441 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003442
3443 // If we point inside a macro argument we should provide info of what the
3444 // token is so use the actual cursor, don't replace it with a macro expansion
3445 // cursor.
3446 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3447 return CXChildVisit_Recurse;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003448
3449 if (clang_isExpression(cursor.kind) &&
3450 clang_isDeclaration(BestCursor->kind)) {
3451 Decl *D = getCursorDecl(*BestCursor);
3452
3453 // Avoid having the cursor of an expression replace the declaration cursor
3454 // when the expression source range overlaps the declaration range.
3455 // This can happen for C++ constructor expressions whose range generally
3456 // include the variable declaration, e.g.:
3457 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3458 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3459 D->getLocation() == Data->TokenBeginLoc)
3460 return CXChildVisit_Break;
3461 }
3462
Douglas Gregor93798e22010-11-05 21:11:19 +00003463 // If our current best cursor is the construction of a temporary object,
3464 // don't replace that cursor with a type reference, because we want
3465 // clang_getCursor() to point at the constructor.
3466 if (clang_isExpression(BestCursor->kind) &&
3467 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3468 cursor.kind == CXCursor_TypeRef)
3469 return CXChildVisit_Recurse;
3470
Douglas Gregor85fe1562010-12-10 07:23:11 +00003471 // Don't override a preprocessing cursor with another preprocessing
3472 // cursor; we want the outermost preprocessing cursor.
3473 if (clang_isPreprocessing(cursor.kind) &&
3474 clang_isPreprocessing(BestCursor->kind))
3475 return CXChildVisit_Recurse;
3476
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003477 *BestCursor = cursor;
3478 return CXChildVisit_Recurse;
3479}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003480
Douglas Gregorb9790342010-01-22 21:44:22 +00003481CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3482 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003483 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003484
Ted Kremeneka60ed472010-11-16 08:15:36 +00003485 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003486 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3487
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003488 // Translate the given source location to make it point at the beginning of
3489 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003490 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003491
3492 // Guard against an invalid SourceLocation, or we may assert in one
3493 // of the following calls.
3494 if (SLoc.isInvalid())
3495 return clang_getNullCursor();
3496
Douglas Gregor40749ee2010-11-03 00:35:38 +00003497 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003498 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3499 CXXUnit->getASTContext().getLangOptions());
3500
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003501 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3502 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003503 // FIXME: Would be great to have a "hint" cursor, then walk from that
3504 // hint cursor upward until we find a cursor whose source range encloses
3505 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003506 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003507 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003508 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00003509 /*VisitPreprocessorLast=*/true,
3510 SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003511 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003512 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003513
3514 if (Logging) {
3515 CXFile SearchFile;
3516 unsigned SearchLine, SearchColumn;
3517 CXFile ResultFile;
3518 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003519 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3520 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003521 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3522
Chandler Carruth20174222011-08-31 16:53:37 +00003523 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3524 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3525 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003526 SearchFileName = clang_getFileName(SearchFile);
3527 ResultFileName = clang_getFileName(ResultFile);
3528 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003529 USR = clang_getCursorUSR(Result);
3530 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003531 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3532 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003533 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3534 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003535 clang_disposeString(SearchFileName);
3536 clang_disposeString(ResultFileName);
3537 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003538 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003539
3540 CXCursor Definition = clang_getCursorDefinition(Result);
3541 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3542 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3543 CXString DefinitionKindSpelling
3544 = clang_getCursorKindSpelling(Definition.kind);
3545 CXFile DefinitionFile;
3546 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003547 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3548 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003549 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3550 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3551 clang_getCString(DefinitionKindSpelling),
3552 clang_getCString(DefinitionFileName),
3553 DefinitionLine, DefinitionColumn);
3554 clang_disposeString(DefinitionFileName);
3555 clang_disposeString(DefinitionKindSpelling);
3556 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003557 }
3558
Ted Kremeneke68fff62010-02-17 00:41:32 +00003559 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003560}
3561
Ted Kremenek73885552009-11-17 19:28:59 +00003562CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003563 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003564}
3565
3566unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003567 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003568}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003569
Douglas Gregor9ce55842010-11-20 00:09:34 +00003570unsigned clang_hashCursor(CXCursor C) {
3571 unsigned Index = 0;
3572 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3573 Index = 1;
3574
3575 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3576 std::make_pair(C.kind, C.data[Index]));
3577}
3578
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003579unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003580 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3581}
3582
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003583unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003584 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3585}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003586
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003587unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003588 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3589}
3590
Douglas Gregor97b98722010-01-19 23:20:36 +00003591unsigned clang_isExpression(enum CXCursorKind K) {
3592 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3593}
3594
3595unsigned clang_isStatement(enum CXCursorKind K) {
3596 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3597}
3598
Douglas Gregor8be80e12011-07-06 03:00:34 +00003599unsigned clang_isAttribute(enum CXCursorKind K) {
3600 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3601}
3602
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003603unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3604 return K == CXCursor_TranslationUnit;
3605}
3606
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003607unsigned clang_isPreprocessing(enum CXCursorKind K) {
3608 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3609}
3610
Ted Kremenekad6eff62010-03-08 21:17:29 +00003611unsigned clang_isUnexposed(enum CXCursorKind K) {
3612 switch (K) {
3613 case CXCursor_UnexposedDecl:
3614 case CXCursor_UnexposedExpr:
3615 case CXCursor_UnexposedStmt:
3616 case CXCursor_UnexposedAttr:
3617 return true;
3618 default:
3619 return false;
3620 }
3621}
3622
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003623CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003624 return C.kind;
3625}
3626
Douglas Gregor98258af2010-01-18 22:46:11 +00003627CXSourceLocation clang_getCursorLocation(CXCursor C) {
3628 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003629 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003630 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003631 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3632 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003633 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003634 }
3635
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003636 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003637 std::pair<ObjCProtocolDecl *, SourceLocation> P
3638 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003639 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003640 }
3641
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003642 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003643 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3644 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003645 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003646 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003647
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003648 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003649 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003650 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003651 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003652
3653 case CXCursor_TemplateRef: {
3654 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3655 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3656 }
3657
Douglas Gregor69319002010-08-31 23:48:11 +00003658 case CXCursor_NamespaceRef: {
3659 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3660 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3661 }
3662
Douglas Gregora67e03f2010-09-09 21:42:20 +00003663 case CXCursor_MemberRef: {
3664 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3665 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3666 }
3667
Ted Kremenek3064ef92010-08-27 21:34:58 +00003668 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003669 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3670 if (!BaseSpec)
3671 return clang_getNullLocation();
3672
3673 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3674 return cxloc::translateSourceLocation(getCursorContext(C),
3675 TSInfo->getTypeLoc().getBeginLoc());
3676
3677 return cxloc::translateSourceLocation(getCursorContext(C),
3678 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003679 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003680
Douglas Gregor36897b02010-09-10 00:22:18 +00003681 case CXCursor_LabelRef: {
3682 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3683 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3684 }
3685
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003686 case CXCursor_OverloadedDeclRef:
3687 return cxloc::translateSourceLocation(getCursorContext(C),
3688 getCursorOverloadedDeclRef(C).second);
3689
Douglas Gregorf46034a2010-01-18 23:41:10 +00003690 default:
3691 // FIXME: Need a way to enumerate all non-reference cases.
3692 llvm_unreachable("Missed a reference kind");
3693 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003694 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003695
3696 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003697 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003698 getLocationFromExpr(getCursorExpr(C)));
3699
Douglas Gregor36897b02010-09-10 00:22:18 +00003700 if (clang_isStatement(C.kind))
3701 return cxloc::translateSourceLocation(getCursorContext(C),
3702 getCursorStmt(C)->getLocStart());
3703
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003704 if (C.kind == CXCursor_PreprocessingDirective) {
3705 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3706 return cxloc::translateSourceLocation(getCursorContext(C), L);
3707 }
Douglas Gregor48072312010-03-18 15:23:44 +00003708
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003709 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003710 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003711 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003712 return cxloc::translateSourceLocation(getCursorContext(C), L);
3713 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003714
3715 if (C.kind == CXCursor_MacroDefinition) {
3716 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3717 return cxloc::translateSourceLocation(getCursorContext(C), L);
3718 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003719
3720 if (C.kind == CXCursor_InclusionDirective) {
3721 SourceLocation L
3722 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3723 return cxloc::translateSourceLocation(getCursorContext(C), L);
3724 }
3725
Ted Kremenek9a700d22010-05-12 06:16:13 +00003726 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003727 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003728
Douglas Gregorf46034a2010-01-18 23:41:10 +00003729 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003730 SourceLocation Loc = D->getLocation();
3731 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3732 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003733 // FIXME: Multiple variables declared in a single declaration
3734 // currently lack the information needed to correctly determine their
3735 // ranges when accounting for the type-specifier. We use context
3736 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3737 // and if so, whether it is the first decl.
3738 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3739 if (!cxcursor::isFirstInDeclGroup(C))
3740 Loc = VD->getLocation();
3741 }
3742
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003743 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003744}
Douglas Gregora7bde202010-01-19 00:34:46 +00003745
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003746} // end extern "C"
3747
3748static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003749 if (clang_isReference(C.kind)) {
3750 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003751 case CXCursor_ObjCSuperClassRef:
3752 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003753
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003754 case CXCursor_ObjCProtocolRef:
3755 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003756
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003757 case CXCursor_ObjCClassRef:
3758 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003759
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003760 case CXCursor_TypeRef:
3761 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003762
3763 case CXCursor_TemplateRef:
3764 return getCursorTemplateRef(C).second;
3765
Douglas Gregor69319002010-08-31 23:48:11 +00003766 case CXCursor_NamespaceRef:
3767 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003768
3769 case CXCursor_MemberRef:
3770 return getCursorMemberRef(C).second;
3771
Ted Kremenek3064ef92010-08-27 21:34:58 +00003772 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003773 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003774
Douglas Gregor36897b02010-09-10 00:22:18 +00003775 case CXCursor_LabelRef:
3776 return getCursorLabelRef(C).second;
3777
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003778 case CXCursor_OverloadedDeclRef:
3779 return getCursorOverloadedDeclRef(C).second;
3780
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003781 default:
3782 // FIXME: Need a way to enumerate all non-reference cases.
3783 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003784 }
3785 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003786
3787 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003788 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003789
3790 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003791 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003792
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003793 if (clang_isAttribute(C.kind))
3794 return getCursorAttr(C)->getRange();
3795
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003796 if (C.kind == CXCursor_PreprocessingDirective)
3797 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003798
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003799 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003800 return cxcursor::getCursorMacroExpansion(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003801
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003802 if (C.kind == CXCursor_MacroDefinition)
3803 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003804
3805 if (C.kind == CXCursor_InclusionDirective)
3806 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3807
Ted Kremenek007a7c92010-11-01 23:26:51 +00003808 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3809 Decl *D = cxcursor::getCursorDecl(C);
3810 SourceRange R = D->getSourceRange();
3811 // FIXME: Multiple variables declared in a single declaration
3812 // currently lack the information needed to correctly determine their
3813 // ranges when accounting for the type-specifier. We use context
3814 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3815 // and if so, whether it is the first decl.
3816 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3817 if (!cxcursor::isFirstInDeclGroup(C))
3818 R.setBegin(VD->getLocation());
3819 }
3820 return R;
3821 }
Douglas Gregor66537982010-11-17 17:14:07 +00003822 return SourceRange();
3823}
3824
3825/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3826/// the decl-specifier-seq for declarations.
3827static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3828 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3829 Decl *D = cxcursor::getCursorDecl(C);
3830 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003831
Douglas Gregor2494dd02011-03-01 01:34:45 +00003832 // Adjust the start of the location for declarations preceded by
3833 // declaration specifiers.
3834 SourceLocation StartLoc;
3835 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3836 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3837 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3838 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3839 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3840 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3841 }
3842
3843 if (StartLoc.isValid() && R.getBegin().isValid() &&
3844 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3845 R.setBegin(StartLoc);
3846
3847 // FIXME: Multiple variables declared in a single declaration
3848 // currently lack the information needed to correctly determine their
3849 // ranges when accounting for the type-specifier. We use context
3850 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3851 // and if so, whether it is the first decl.
3852 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3853 if (!cxcursor::isFirstInDeclGroup(C))
3854 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003855 }
3856
3857 return R;
3858 }
3859
3860 return getRawCursorExtent(C);
3861}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003862
3863extern "C" {
3864
3865CXSourceRange clang_getCursorExtent(CXCursor C) {
3866 SourceRange R = getRawCursorExtent(C);
3867 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003868 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003870 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003871}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003872
3873CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003874 if (clang_isInvalid(C.kind))
3875 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003876
Ted Kremeneka60ed472010-11-16 08:15:36 +00003877 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003878 if (clang_isDeclaration(C.kind)) {
3879 Decl *D = getCursorDecl(C);
3880 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003881 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003882 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003883 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003884 if (ObjCForwardProtocolDecl *Protocols
3885 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003886 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003887 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003888 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3889 return MakeCXCursor(Property, tu);
3890
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003891 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003892 }
3893
Douglas Gregor97b98722010-01-19 23:20:36 +00003894 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003895 Expr *E = getCursorExpr(C);
3896 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003897 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003898 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003899
3900 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003901 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003902
Douglas Gregor97b98722010-01-19 23:20:36 +00003903 return clang_getNullCursor();
3904 }
3905
Douglas Gregor36897b02010-09-10 00:22:18 +00003906 if (clang_isStatement(C.kind)) {
3907 Stmt *S = getCursorStmt(C);
3908 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003909 if (LabelDecl *label = Goto->getLabel())
3910 if (LabelStmt *labelS = label->getStmt())
3911 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003912
3913 return clang_getNullCursor();
3914 }
3915
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003916 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003917 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003918 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003919 }
3920
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003921 if (!clang_isReference(C.kind))
3922 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003923
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003924 switch (C.kind) {
3925 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003926 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003927
3928 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003929 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003930
3931 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003932 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003933
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003934 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003935 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003936
3937 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003938 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003939
Douglas Gregor69319002010-08-31 23:48:11 +00003940 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003941 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003942
Douglas Gregora67e03f2010-09-09 21:42:20 +00003943 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003944 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003945
Ted Kremenek3064ef92010-08-27 21:34:58 +00003946 case CXCursor_CXXBaseSpecifier: {
3947 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3948 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003949 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003950 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003951
Douglas Gregor36897b02010-09-10 00:22:18 +00003952 case CXCursor_LabelRef:
3953 // FIXME: We end up faking the "parent" declaration here because we
3954 // don't want to make CXCursor larger.
3955 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003956 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3957 .getTranslationUnitDecl(),
3958 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003959
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003960 case CXCursor_OverloadedDeclRef:
3961 return C;
3962
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003963 default:
3964 // We would prefer to enumerate all non-reference cursor kinds here.
3965 llvm_unreachable("Unhandled reference cursor kind");
3966 break;
3967 }
3968 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003969
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003970 return clang_getNullCursor();
3971}
3972
Douglas Gregorb6998662010-01-19 19:34:47 +00003973CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003974 if (clang_isInvalid(C.kind))
3975 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003976
Ted Kremeneka60ed472010-11-16 08:15:36 +00003977 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003978
Douglas Gregorb6998662010-01-19 19:34:47 +00003979 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003980 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003981 C = clang_getCursorReferenced(C);
3982 WasReference = true;
3983 }
3984
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003985 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003986 return clang_getCursorReferenced(C);
3987
Douglas Gregorb6998662010-01-19 19:34:47 +00003988 if (!clang_isDeclaration(C.kind))
3989 return clang_getNullCursor();
3990
3991 Decl *D = getCursorDecl(C);
3992 if (!D)
3993 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003994
Douglas Gregorb6998662010-01-19 19:34:47 +00003995 switch (D->getKind()) {
3996 // Declaration kinds that don't really separate the notions of
3997 // declaration and definition.
3998 case Decl::Namespace:
3999 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004000 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004001 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004002 case Decl::TemplateTypeParm:
4003 case Decl::EnumConstant:
4004 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004005 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004006 case Decl::ObjCIvar:
4007 case Decl::ObjCAtDefsField:
4008 case Decl::ImplicitParam:
4009 case Decl::ParmVar:
4010 case Decl::NonTypeTemplateParm:
4011 case Decl::TemplateTemplateParm:
4012 case Decl::ObjCCategoryImpl:
4013 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004014 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004015 case Decl::LinkageSpec:
4016 case Decl::ObjCPropertyImpl:
4017 case Decl::FileScopeAsm:
4018 case Decl::StaticAssert:
4019 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004020 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004021 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004022 return C;
4023
4024 // Declaration kinds that don't make any sense here, but are
4025 // nonetheless harmless.
4026 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004027 break;
4028
4029 // Declaration kinds for which the definition is not resolvable.
4030 case Decl::UnresolvedUsingTypename:
4031 case Decl::UnresolvedUsingValue:
4032 break;
4033
4034 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004035 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004036 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004037
4038 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004039 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004040
4041 case Decl::Enum:
4042 case Decl::Record:
4043 case Decl::CXXRecord:
4044 case Decl::ClassTemplateSpecialization:
4045 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004046 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004047 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004048 return clang_getNullCursor();
4049
4050 case Decl::Function:
4051 case Decl::CXXMethod:
4052 case Decl::CXXConstructor:
4053 case Decl::CXXDestructor:
4054 case Decl::CXXConversion: {
4055 const FunctionDecl *Def = 0;
4056 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004057 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004058 return clang_getNullCursor();
4059 }
4060
4061 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004062 // Ask the variable if it has a definition.
4063 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004064 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004065 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004066 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004067
Douglas Gregorb6998662010-01-19 19:34:47 +00004068 case Decl::FunctionTemplate: {
4069 const FunctionDecl *Def = 0;
4070 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004071 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004072 return clang_getNullCursor();
4073 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004074
Douglas Gregorb6998662010-01-19 19:34:47 +00004075 case Decl::ClassTemplate: {
4076 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004077 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004078 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004079 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004080 return clang_getNullCursor();
4081 }
4082
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004083 case Decl::Using:
4084 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004085 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004086
4087 case Decl::UsingShadow:
4088 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004089 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004090 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004091
4092 case Decl::ObjCMethod: {
4093 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4094 if (Method->isThisDeclarationADefinition())
4095 return C;
4096
4097 // Dig out the method definition in the associated
4098 // @implementation, if we have it.
4099 // FIXME: The ASTs should make finding the definition easier.
4100 if (ObjCInterfaceDecl *Class
4101 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4102 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4103 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4104 Method->isInstanceMethod()))
4105 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004106 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004107
4108 return clang_getNullCursor();
4109 }
4110
4111 case Decl::ObjCCategory:
4112 if (ObjCCategoryImplDecl *Impl
4113 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004114 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004115 return clang_getNullCursor();
4116
4117 case Decl::ObjCProtocol:
4118 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4119 return C;
4120 return clang_getNullCursor();
4121
4122 case Decl::ObjCInterface:
4123 // There are two notions of a "definition" for an Objective-C
4124 // class: the interface and its implementation. When we resolved a
4125 // reference to an Objective-C class, produce the @interface as
4126 // the definition; when we were provided with the interface,
4127 // produce the @implementation as the definition.
4128 if (WasReference) {
4129 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4130 return C;
4131 } else if (ObjCImplementationDecl *Impl
4132 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004133 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004134 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004135
Douglas Gregorb6998662010-01-19 19:34:47 +00004136 case Decl::ObjCProperty:
4137 // FIXME: We don't really know where to find the
4138 // ObjCPropertyImplDecls that implement this property.
4139 return clang_getNullCursor();
4140
4141 case Decl::ObjCCompatibleAlias:
4142 if (ObjCInterfaceDecl *Class
4143 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4144 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004145 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004146
Douglas Gregorb6998662010-01-19 19:34:47 +00004147 return clang_getNullCursor();
4148
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004149 case Decl::ObjCForwardProtocol:
4150 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004151 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004152
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004153 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004154 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004155 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004156
4157 case Decl::Friend:
4158 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004159 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004160 return clang_getNullCursor();
4161
4162 case Decl::FriendTemplate:
4163 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004164 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004165 return clang_getNullCursor();
4166 }
4167
4168 return clang_getNullCursor();
4169}
4170
4171unsigned clang_isCursorDefinition(CXCursor C) {
4172 if (!clang_isDeclaration(C.kind))
4173 return 0;
4174
4175 return clang_getCursorDefinition(C) == C;
4176}
4177
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004178CXCursor clang_getCanonicalCursor(CXCursor C) {
4179 if (!clang_isDeclaration(C.kind))
4180 return C;
4181
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004182 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004183 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4184 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4185 return MakeCXCursor(CatD, getCursorTU(C));
4186
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004187 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4188 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4189 return MakeCXCursor(IFD, getCursorTU(C));
4190
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004191 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004192 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004193
4194 return C;
4195}
4196
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004197unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004198 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004199 return 0;
4200
4201 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4202 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4203 return E->getNumDecls();
4204
4205 if (OverloadedTemplateStorage *S
4206 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4207 return S->size();
4208
4209 Decl *D = Storage.get<Decl*>();
4210 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004211 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004212 if (isa<ObjCClassDecl>(D))
4213 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004214 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4215 return Protocols->protocol_size();
4216
4217 return 0;
4218}
4219
4220CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004221 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004222 return clang_getNullCursor();
4223
4224 if (index >= clang_getNumOverloadedDecls(cursor))
4225 return clang_getNullCursor();
4226
Ted Kremeneka60ed472010-11-16 08:15:36 +00004227 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004228 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4229 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004230 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004231
4232 if (OverloadedTemplateStorage *S
4233 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004234 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004235
4236 Decl *D = Storage.get<Decl*>();
4237 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4238 // FIXME: This is, unfortunately, linear time.
4239 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4240 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004241 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004242 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004243 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004244 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004245 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004246 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004247
4248 return clang_getNullCursor();
4249}
4250
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004251void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004252 const char **startBuf,
4253 const char **endBuf,
4254 unsigned *startLine,
4255 unsigned *startColumn,
4256 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004257 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004258 assert(getCursorDecl(C) && "CXCursor has null decl");
4259 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004260 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4261 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004262
Steve Naroff4ade6d62009-09-23 17:52:52 +00004263 SourceManager &SM = FD->getASTContext().getSourceManager();
4264 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4265 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4266 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4267 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4268 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4269 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4270}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004271
Douglas Gregor430d7a12011-07-25 17:48:11 +00004272
4273CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4274 unsigned PieceIndex) {
4275 RefNamePieces Pieces;
4276
4277 switch (C.kind) {
4278 case CXCursor_MemberRefExpr:
4279 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4280 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4281 E->getQualifierLoc().getSourceRange());
4282 break;
4283
4284 case CXCursor_DeclRefExpr:
4285 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4286 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4287 E->getQualifierLoc().getSourceRange(),
4288 E->getExplicitTemplateArgsOpt());
4289 break;
4290
4291 case CXCursor_CallExpr:
4292 if (CXXOperatorCallExpr *OCE =
4293 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4294 Expr *Callee = OCE->getCallee();
4295 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4296 Callee = ICE->getSubExpr();
4297
4298 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4299 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4300 DRE->getQualifierLoc().getSourceRange());
4301 }
4302 break;
4303
4304 default:
4305 break;
4306 }
4307
4308 if (Pieces.empty()) {
4309 if (PieceIndex == 0)
4310 return clang_getCursorExtent(C);
4311 } else if (PieceIndex < Pieces.size()) {
4312 SourceRange R = Pieces[PieceIndex];
4313 if (R.isValid())
4314 return cxloc::translateSourceRange(getCursorContext(C), R);
4315 }
4316
4317 return clang_getNullRange();
4318}
4319
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004320void clang_enableStackTraces(void) {
4321 llvm::sys::PrintStackTraceOnErrorSignal();
4322}
4323
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004324void clang_executeOnThread(void (*fn)(void*), void *user_data,
4325 unsigned stack_size) {
4326 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4327}
4328
Ted Kremenekfb480492010-01-13 21:46:36 +00004329} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004330
Ted Kremenekfb480492010-01-13 21:46:36 +00004331//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004332// Token-based Operations.
4333//===----------------------------------------------------------------------===//
4334
4335/* CXToken layout:
4336 * int_data[0]: a CXTokenKind
4337 * int_data[1]: starting token location
4338 * int_data[2]: token length
4339 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004340 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004341 * otherwise unused.
4342 */
4343extern "C" {
4344
4345CXTokenKind clang_getTokenKind(CXToken CXTok) {
4346 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4347}
4348
4349CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4350 switch (clang_getTokenKind(CXTok)) {
4351 case CXToken_Identifier:
4352 case CXToken_Keyword:
4353 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004354 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4355 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004356
4357 case CXToken_Literal: {
4358 // We have stashed the starting pointer in the ptr_data field. Use it.
4359 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004360 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004361 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004362
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004363 case CXToken_Punctuation:
4364 case CXToken_Comment:
4365 break;
4366 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004367
4368 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004369 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004370 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004371 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004372 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004373
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004374 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4375 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004376 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004377 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004378 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004379 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4380 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004381 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004382
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004383 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004384}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004385
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004387 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004388 if (!CXXUnit)
4389 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004390
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004391 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4392 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4393}
4394
4395CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004396 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004397 if (!CXXUnit)
4398 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004399
4400 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004401 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4402}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004403
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004404void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4405 CXToken **Tokens, unsigned *NumTokens) {
4406 if (Tokens)
4407 *Tokens = 0;
4408 if (NumTokens)
4409 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004410
Ted Kremeneka60ed472010-11-16 08:15:36 +00004411 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004412 if (!CXXUnit || !Tokens || !NumTokens)
4413 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004414
Douglas Gregorbdf60622010-03-05 21:16:25 +00004415 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4416
Daniel Dunbar85b988f2010-02-14 08:31:57 +00004417 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004418 if (R.isInvalid())
4419 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004420
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004421 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4422 std::pair<FileID, unsigned> BeginLocInfo
4423 = SourceMgr.getDecomposedLoc(R.getBegin());
4424 std::pair<FileID, unsigned> EndLocInfo
4425 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004426
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004427 // Cannot tokenize across files.
4428 if (BeginLocInfo.first != EndLocInfo.first)
4429 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004430
4431 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004432 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004433 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004434 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004435 if (Invalid)
4436 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004437
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004438 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4439 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004440 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004441 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004442
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004443 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004444 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004445 SmallVector<CXToken, 32> CXTokens;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004446 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004447 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004448 do {
4449 // Lex the next token
4450 Lex.LexFromRawLexer(Tok);
4451 if (Tok.is(tok::eof))
4452 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004453
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004454 // Initialize the CXToken.
4455 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004456
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004457 // - Common fields
4458 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4459 CXTok.int_data[2] = Tok.getLength();
4460 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004461
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004462 // - Kind-specific fields
4463 if (Tok.isLiteral()) {
4464 CXTok.int_data[0] = CXToken_Literal;
4465 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004466 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004467 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004468 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004469 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004470
David Chisnall096428b2010-10-13 21:44:48 +00004471 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004472 CXTok.int_data[0] = CXToken_Keyword;
4473 }
4474 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004475 CXTok.int_data[0] = Tok.is(tok::identifier)
4476 ? CXToken_Identifier
4477 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004478 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004479 CXTok.ptr_data = II;
4480 } else if (Tok.is(tok::comment)) {
4481 CXTok.int_data[0] = CXToken_Comment;
4482 CXTok.ptr_data = 0;
4483 } else {
4484 CXTok.int_data[0] = CXToken_Punctuation;
4485 CXTok.ptr_data = 0;
4486 }
4487 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004488 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004489 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004490
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004491 if (CXTokens.empty())
4492 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004493
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004494 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4495 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4496 *NumTokens = CXTokens.size();
4497}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004498
Ted Kremenek6db61092010-05-05 00:55:15 +00004499void clang_disposeTokens(CXTranslationUnit TU,
4500 CXToken *Tokens, unsigned NumTokens) {
4501 free(Tokens);
4502}
4503
4504} // end: extern "C"
4505
4506//===----------------------------------------------------------------------===//
4507// Token annotation APIs.
4508//===----------------------------------------------------------------------===//
4509
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004510typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004511static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4512 CXCursor parent,
4513 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004514namespace {
4515class AnnotateTokensWorker {
4516 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004517 CXToken *Tokens;
4518 CXCursor *Cursors;
4519 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004520 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004521 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004522 CursorVisitor AnnotateVis;
4523 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004524 bool HasContextSensitiveKeywords;
4525
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004526 bool MoreTokens() const { return TokIdx < NumTokens; }
4527 unsigned NextToken() const { return TokIdx; }
4528 void AdvanceToken() { ++TokIdx; }
4529 SourceLocation GetTokenLoc(unsigned tokI) {
4530 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4531 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004532 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004533 return Tokens[tokI].int_data[3] != 0;
4534 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004535 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004536 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4537 }
4538
4539 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004540 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4541 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004542
Ted Kremenek6db61092010-05-05 00:55:15 +00004543public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004544 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004545 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004546 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004547 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004548 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004549 AnnotateVis(tu,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00004550 AnnotateTokensVisitor, this, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004551 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4552 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004553
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004554 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004555 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004556 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004557 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004558 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004559 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004560
4561 /// \brief Determine whether the annotator saw any cursors that have
4562 /// context-sensitive keywords.
4563 bool hasContextSensitiveKeywords() const {
4564 return HasContextSensitiveKeywords;
4565 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004566};
4567}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004568
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004569void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4570 // Walk the AST within the region of interest, annotating tokens
4571 // along the way.
4572 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004573
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004574 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4575 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004576 if (Pos != Annotated.end() &&
4577 (clang_isInvalid(Cursors[I].kind) ||
4578 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004579 Cursors[I] = Pos->second;
4580 }
4581
4582 // Finish up annotating any tokens left.
4583 if (!MoreTokens())
4584 return;
4585
4586 const CXCursor &C = clang_getNullCursor();
4587 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4588 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4589 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004590 }
4591}
4592
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004593/// \brief It annotates and advances tokens with a cursor until the comparison
4594//// between the cursor location and the source range is the same as
4595/// \arg compResult.
4596///
4597/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4598/// Pass RangeOverlap to annotate tokens inside a range.
4599void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4600 RangeComparisonResult compResult,
4601 SourceRange range) {
4602 while (MoreTokens()) {
4603 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004604 if (isFunctionMacroToken(I))
4605 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004606
4607 SourceLocation TokLoc = GetTokenLoc(I);
4608 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4609 Cursors[I] = updateC;
4610 AdvanceToken();
4611 continue;
4612 }
4613 break;
4614 }
4615}
4616
4617/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004618void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4619 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004620 RangeComparisonResult compResult,
4621 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004622 assert(MoreTokens());
4623 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004624 "Should be called only for macro arg tokens");
4625
4626 // This works differently than annotateAndAdvanceTokens; because expanded
4627 // macro arguments can have arbitrary translation-unit source order, we do not
4628 // advance the token index one by one until a token fails the range test.
4629 // We only advance once past all of the macro arg tokens if all of them
4630 // pass the range test. If one of them fails we keep the token index pointing
4631 // at the start of the macro arg tokens so that the failing token will be
4632 // annotated by a subsequent annotation try.
4633
4634 bool atLeastOneCompFail = false;
4635
4636 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004637 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4638 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004639 if (TokLoc.isFileID())
4640 continue; // not macro arg token, it's parens or comma.
4641 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4642 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4643 Cursors[I] = updateC;
4644 } else
4645 atLeastOneCompFail = true;
4646 }
4647
4648 if (!atLeastOneCompFail)
4649 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4650}
4651
Ted Kremenek6db61092010-05-05 00:55:15 +00004652enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004653AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004654 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004655 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004656 if (cursorRange.isInvalid())
4657 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004658
4659 if (!HasContextSensitiveKeywords) {
4660 // Objective-C properties can have context-sensitive keywords.
4661 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4662 if (ObjCPropertyDecl *Property
4663 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4664 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4665 }
4666 // Objective-C methods can have context-sensitive keywords.
4667 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4668 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4669 if (ObjCMethodDecl *Method
4670 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4671 if (Method->getObjCDeclQualifier())
4672 HasContextSensitiveKeywords = true;
4673 else {
4674 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4675 PEnd = Method->param_end();
4676 P != PEnd; ++P) {
4677 if ((*P)->getObjCDeclQualifier()) {
4678 HasContextSensitiveKeywords = true;
4679 break;
4680 }
4681 }
4682 }
4683 }
4684 }
4685 // C++ methods can have context-sensitive keywords.
4686 else if (cursor.kind == CXCursor_CXXMethod) {
4687 if (CXXMethodDecl *Method
4688 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4689 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4690 HasContextSensitiveKeywords = true;
4691 }
4692 }
4693 // C++ classes can have context-sensitive keywords.
4694 else if (cursor.kind == CXCursor_StructDecl ||
4695 cursor.kind == CXCursor_ClassDecl ||
4696 cursor.kind == CXCursor_ClassTemplate ||
4697 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4698 if (Decl *D = getCursorDecl(cursor))
4699 if (D->hasAttr<FinalAttr>())
4700 HasContextSensitiveKeywords = true;
4701 }
4702 }
4703
Douglas Gregor4419b672010-10-21 06:10:04 +00004704 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004705 // For macro expansions, just note where the beginning of the macro
4706 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004707 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004708 Annotated[Loc.int_data] = cursor;
4709 return CXChildVisit_Recurse;
4710 }
4711
Douglas Gregor4419b672010-10-21 06:10:04 +00004712 // Items in the preprocessing record are kept separate from items in
4713 // declarations, so we keep a separate token index.
4714 unsigned SavedTokIdx = TokIdx;
4715 TokIdx = PreprocessingTokIdx;
4716
4717 // Skip tokens up until we catch up to the beginning of the preprocessing
4718 // entry.
4719 while (MoreTokens()) {
4720 const unsigned I = NextToken();
4721 SourceLocation TokLoc = GetTokenLoc(I);
4722 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4723 case RangeBefore:
4724 AdvanceToken();
4725 continue;
4726 case RangeAfter:
4727 case RangeOverlap:
4728 break;
4729 }
4730 break;
4731 }
4732
4733 // Look at all of the tokens within this range.
4734 while (MoreTokens()) {
4735 const unsigned I = NextToken();
4736 SourceLocation TokLoc = GetTokenLoc(I);
4737 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4738 case RangeBefore:
4739 assert(0 && "Infeasible");
4740 case RangeAfter:
4741 break;
4742 case RangeOverlap:
4743 Cursors[I] = cursor;
4744 AdvanceToken();
4745 continue;
4746 }
4747 break;
4748 }
4749
4750 // Save the preprocessing token index; restore the non-preprocessing
4751 // token index.
4752 PreprocessingTokIdx = TokIdx;
4753 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004754 return CXChildVisit_Recurse;
4755 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004756
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004757 if (cursorRange.isInvalid())
4758 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004759
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004760 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4761
Ted Kremeneka333c662010-05-12 05:29:33 +00004762 // Adjust the annotated range based specific declarations.
4763 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4764 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004765 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004766
4767 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004768 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004769 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4770 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4771 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4772 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4773 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004774 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004775
4776 if (StartLoc.isValid() && L.isValid() &&
4777 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4778 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004779 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004780
Ted Kremenek3f404602010-08-14 01:14:06 +00004781 // If the location of the cursor occurs within a macro instantiation, record
4782 // the spelling location of the cursor in our annotation map. We can then
4783 // paper over the token labelings during a post-processing step to try and
4784 // get cursor mappings for tokens that are the *arguments* of a macro
4785 // instantiation.
4786 if (L.isMacroID()) {
4787 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4788 // Only invalidate the old annotation if it isn't part of a preprocessing
4789 // directive. Here we assume that the default construction of CXCursor
4790 // results in CXCursor.kind being an initialized value (i.e., 0). If
4791 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004792
Ted Kremenek3f404602010-08-14 01:14:06 +00004793 CXCursor &oldC = Annotated[rawEncoding];
4794 if (!clang_isPreprocessing(oldC.kind))
4795 oldC = cursor;
4796 }
4797
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004798 const enum CXCursorKind K = clang_getCursorKind(parent);
4799 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004800 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4801 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004802
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004803 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004804
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004805 // Avoid having the cursor of an expression "overwrite" the annotation of the
4806 // variable declaration that it belongs to.
4807 // This can happen for C++ constructor expressions whose range generally
4808 // include the variable declaration, e.g.:
4809 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4810 if (clang_isExpression(cursorK)) {
4811 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004812 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004813 const unsigned I = NextToken();
4814 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4815 E->getLocStart() == D->getLocation() &&
4816 E->getLocStart() == GetTokenLoc(I)) {
4817 Cursors[I] = updateC;
4818 AdvanceToken();
4819 }
4820 }
4821 }
4822
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004823 // Visit children to get their cursor information.
4824 const unsigned BeforeChildren = NextToken();
4825 VisitChildren(cursor);
4826 const unsigned AfterChildren = NextToken();
4827
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004828 // Scan the tokens that are at the end of the cursor, but are not captured
4829 // but the child cursors.
4830 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004831
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004832 // Scan the tokens that are at the beginning of the cursor, but are not
4833 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004834 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4835 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4836 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004837
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004838 Cursors[I] = cursor;
4839 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004840
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004841 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004842}
4843
Ted Kremenek6db61092010-05-05 00:55:15 +00004844static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4845 CXCursor parent,
4846 CXClientData client_data) {
4847 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4848}
4849
Ted Kremenek6628a612011-03-18 22:51:30 +00004850namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004851
4852/// \brief Uses the macro expansions in the preprocessing record to find
4853/// and mark tokens that are macro arguments. This info is used by the
4854/// AnnotateTokensWorker.
4855class MarkMacroArgTokensVisitor {
4856 SourceManager &SM;
4857 CXToken *Tokens;
4858 unsigned NumTokens;
4859 unsigned CurIdx;
4860
4861public:
4862 MarkMacroArgTokensVisitor(SourceManager &SM,
4863 CXToken *tokens, unsigned numTokens)
4864 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4865
4866 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4867 if (cursor.kind != CXCursor_MacroExpansion)
4868 return CXChildVisit_Continue;
4869
4870 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4871 if (macroRange.getBegin() == macroRange.getEnd())
4872 return CXChildVisit_Continue; // it's not a function macro.
4873
4874 for (; CurIdx < NumTokens; ++CurIdx) {
4875 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4876 macroRange.getBegin()))
4877 break;
4878 }
4879
4880 if (CurIdx == NumTokens)
4881 return CXChildVisit_Break;
4882
4883 for (; CurIdx < NumTokens; ++CurIdx) {
4884 SourceLocation tokLoc = getTokenLoc(CurIdx);
4885 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4886 break;
4887
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004888 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004889 }
4890
4891 if (CurIdx == NumTokens)
4892 return CXChildVisit_Break;
4893
4894 return CXChildVisit_Continue;
4895 }
4896
4897private:
4898 SourceLocation getTokenLoc(unsigned tokI) {
4899 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4900 }
4901
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004902 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004903 // The third field is reserved and currently not used. Use it here
4904 // to mark macro arg expanded tokens with their expanded locations.
4905 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4906 }
4907};
4908
4909} // end anonymous namespace
4910
4911static CXChildVisitResult
4912MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4913 CXClientData client_data) {
4914 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4915 parent);
4916}
4917
4918namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004919 struct clang_annotateTokens_Data {
4920 CXTranslationUnit TU;
4921 ASTUnit *CXXUnit;
4922 CXToken *Tokens;
4923 unsigned NumTokens;
4924 CXCursor *Cursors;
4925 };
4926}
4927
Ted Kremenekab979612010-11-11 08:05:23 +00004928// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00004929static void clang_annotateTokensImpl(void *UserData) {
4930 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
4931 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
4932 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
4933 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
4934 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
4935
4936 // Determine the region of interest, which contains all of the tokens.
4937 SourceRange RegionOfInterest;
4938 RegionOfInterest.setBegin(
4939 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
4940 RegionOfInterest.setEnd(
4941 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
4942 Tokens[NumTokens-1])));
4943
4944 // A mapping from the source locations found when re-lexing or traversing the
4945 // region of interest to the corresponding cursors.
4946 AnnotateTokensData Annotated;
4947
4948 // Relex the tokens within the source range to look for preprocessing
4949 // directives.
4950 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4951 std::pair<FileID, unsigned> BeginLocInfo
4952 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4953 std::pair<FileID, unsigned> EndLocInfo
4954 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4955
Chris Lattner5f9e2722011-07-23 10:55:15 +00004956 StringRef Buffer;
Ted Kremenek6628a612011-03-18 22:51:30 +00004957 bool Invalid = false;
4958 if (BeginLocInfo.first == EndLocInfo.first &&
4959 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4960 !Invalid) {
4961 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4962 CXXUnit->getASTContext().getLangOptions(),
4963 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4964 Buffer.end());
4965 Lex.SetCommentRetentionState(true);
4966
4967 // Lex tokens in raw mode until we hit the end of the range, to avoid
4968 // entering #includes or expanding macros.
4969 while (true) {
4970 Token Tok;
4971 Lex.LexFromRawLexer(Tok);
4972
4973 reprocess:
4974 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4975 // We have found a preprocessing directive. Gobble it up so that we
4976 // don't see it while preprocessing these tokens later, but keep track
4977 // of all of the token locations inside this preprocessing directive so
4978 // that we can annotate them appropriately.
4979 //
4980 // FIXME: Some simple tests here could identify macro definitions and
4981 // #undefs, to provide specific cursor kinds for those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004982 SmallVector<SourceLocation, 32> Locations;
Ted Kremenek6628a612011-03-18 22:51:30 +00004983 do {
4984 Locations.push_back(Tok.getLocation());
4985 Lex.LexFromRawLexer(Tok);
4986 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4987
4988 using namespace cxcursor;
4989 CXCursor Cursor
4990 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4991 Locations.back()),
4992 TU);
4993 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4994 Annotated[Locations[I].getRawEncoding()] = Cursor;
4995 }
4996
4997 if (Tok.isAtStartOfLine())
4998 goto reprocess;
4999
5000 continue;
5001 }
5002
5003 if (Tok.is(tok::eof))
5004 break;
5005 }
5006 }
5007
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005008 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5009 // Search and mark tokens that are macro argument expansions.
5010 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5011 Tokens, NumTokens);
5012 CursorVisitor MacroArgMarker(TU,
5013 MarkMacroArgTokensVisitorDelegate, &Visitor,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00005014 true, RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005015 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5016 }
5017
Ted Kremenek6628a612011-03-18 22:51:30 +00005018 // Annotate all of the source locations in the region of interest that map to
5019 // a specific cursor.
5020 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5021 TU, RegionOfInterest);
5022
5023 // FIXME: We use a ridiculous stack size here because the data-recursion
5024 // algorithm uses a large stack frame than the non-data recursive version,
5025 // and AnnotationTokensWorker currently transforms the data-recursion
5026 // algorithm back into a traditional recursion by explicitly calling
5027 // VisitChildren(). We will need to remove this explicit recursive call.
5028 W.AnnotateTokens();
5029
5030 // If we ran into any entities that involve context-sensitive keywords,
5031 // take another pass through the tokens to mark them as such.
5032 if (W.hasContextSensitiveKeywords()) {
5033 for (unsigned I = 0; I != NumTokens; ++I) {
5034 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5035 continue;
5036
5037 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5038 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5039 if (ObjCPropertyDecl *Property
5040 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5041 if (Property->getPropertyAttributesAsWritten() != 0 &&
5042 llvm::StringSwitch<bool>(II->getName())
5043 .Case("readonly", true)
5044 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005045 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005046 .Case("readwrite", true)
5047 .Case("retain", true)
5048 .Case("copy", true)
5049 .Case("nonatomic", true)
5050 .Case("atomic", true)
5051 .Case("getter", true)
5052 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005053 .Case("strong", true)
5054 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005055 .Default(false))
5056 Tokens[I].int_data[0] = CXToken_Keyword;
5057 }
5058 continue;
5059 }
5060
5061 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5062 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5063 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5064 if (llvm::StringSwitch<bool>(II->getName())
5065 .Case("in", true)
5066 .Case("out", true)
5067 .Case("inout", true)
5068 .Case("oneway", true)
5069 .Case("bycopy", true)
5070 .Case("byref", true)
5071 .Default(false))
5072 Tokens[I].int_data[0] = CXToken_Keyword;
5073 continue;
5074 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005075
5076 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5077 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5078 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005079 continue;
5080 }
5081 }
5082 }
Ted Kremenekab979612010-11-11 08:05:23 +00005083}
5084
Ted Kremenek6db61092010-05-05 00:55:15 +00005085extern "C" {
5086
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005087void clang_annotateTokens(CXTranslationUnit TU,
5088 CXToken *Tokens, unsigned NumTokens,
5089 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005090
5091 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005092 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005093
Douglas Gregor4419b672010-10-21 06:10:04 +00005094 // Any token we don't specifically annotate will have a NULL cursor.
5095 CXCursor C = clang_getNullCursor();
5096 for (unsigned I = 0; I != NumTokens; ++I)
5097 Cursors[I] = C;
5098
Ted Kremeneka60ed472010-11-16 08:15:36 +00005099 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005100 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005101 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005102
Douglas Gregorbdf60622010-03-05 21:16:25 +00005103 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005104
5105 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005106 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005107 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005108 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005109 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5110 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005111}
Ted Kremenek6628a612011-03-18 22:51:30 +00005112
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005113} // end: extern "C"
5114
5115//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005116// Operations for querying linkage of a cursor.
5117//===----------------------------------------------------------------------===//
5118
5119extern "C" {
5120CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005121 if (!clang_isDeclaration(cursor.kind))
5122 return CXLinkage_Invalid;
5123
Ted Kremenek16b42592010-03-03 06:36:57 +00005124 Decl *D = cxcursor::getCursorDecl(cursor);
5125 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5126 switch (ND->getLinkage()) {
5127 case NoLinkage: return CXLinkage_NoLinkage;
5128 case InternalLinkage: return CXLinkage_Internal;
5129 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5130 case ExternalLinkage: return CXLinkage_External;
5131 };
5132
5133 return CXLinkage_Invalid;
5134}
5135} // end: extern "C"
5136
5137//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005138// Operations for querying language of a cursor.
5139//===----------------------------------------------------------------------===//
5140
5141static CXLanguageKind getDeclLanguage(const Decl *D) {
5142 switch (D->getKind()) {
5143 default:
5144 break;
5145 case Decl::ImplicitParam:
5146 case Decl::ObjCAtDefsField:
5147 case Decl::ObjCCategory:
5148 case Decl::ObjCCategoryImpl:
5149 case Decl::ObjCClass:
5150 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005151 case Decl::ObjCForwardProtocol:
5152 case Decl::ObjCImplementation:
5153 case Decl::ObjCInterface:
5154 case Decl::ObjCIvar:
5155 case Decl::ObjCMethod:
5156 case Decl::ObjCProperty:
5157 case Decl::ObjCPropertyImpl:
5158 case Decl::ObjCProtocol:
5159 return CXLanguage_ObjC;
5160 case Decl::CXXConstructor:
5161 case Decl::CXXConversion:
5162 case Decl::CXXDestructor:
5163 case Decl::CXXMethod:
5164 case Decl::CXXRecord:
5165 case Decl::ClassTemplate:
5166 case Decl::ClassTemplatePartialSpecialization:
5167 case Decl::ClassTemplateSpecialization:
5168 case Decl::Friend:
5169 case Decl::FriendTemplate:
5170 case Decl::FunctionTemplate:
5171 case Decl::LinkageSpec:
5172 case Decl::Namespace:
5173 case Decl::NamespaceAlias:
5174 case Decl::NonTypeTemplateParm:
5175 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005176 case Decl::TemplateTemplateParm:
5177 case Decl::TemplateTypeParm:
5178 case Decl::UnresolvedUsingTypename:
5179 case Decl::UnresolvedUsingValue:
5180 case Decl::Using:
5181 case Decl::UsingDirective:
5182 case Decl::UsingShadow:
5183 return CXLanguage_CPlusPlus;
5184 }
5185
5186 return CXLanguage_C;
5187}
5188
5189extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005190
5191enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5192 if (clang_isDeclaration(cursor.kind))
5193 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005194 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005195 return CXAvailability_Available;
5196
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005197 switch (D->getAvailability()) {
5198 case AR_Available:
5199 case AR_NotYetIntroduced:
5200 return CXAvailability_Available;
5201
5202 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005203 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005204
5205 case AR_Unavailable:
5206 return CXAvailability_NotAvailable;
5207 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005208 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005209
Douglas Gregor58ddb602010-08-23 23:00:57 +00005210 return CXAvailability_Available;
5211}
5212
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005213CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5214 if (clang_isDeclaration(cursor.kind))
5215 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5216
5217 return CXLanguage_Invalid;
5218}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005219
5220 /// \brief If the given cursor is the "templated" declaration
5221 /// descibing a class or function template, return the class or
5222 /// function template.
5223static Decl *maybeGetTemplateCursor(Decl *D) {
5224 if (!D)
5225 return 0;
5226
5227 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5228 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5229 return FunTmpl;
5230
5231 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5232 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5233 return ClassTmpl;
5234
5235 return D;
5236}
5237
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005238CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5239 if (clang_isDeclaration(cursor.kind)) {
5240 if (Decl *D = getCursorDecl(cursor)) {
5241 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005242 if (!DC)
5243 return clang_getNullCursor();
5244
5245 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5246 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005247 }
5248 }
5249
5250 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5251 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005252 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005253 }
5254
5255 return clang_getNullCursor();
5256}
5257
5258CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5259 if (clang_isDeclaration(cursor.kind)) {
5260 if (Decl *D = getCursorDecl(cursor)) {
5261 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005262 if (!DC)
5263 return clang_getNullCursor();
5264
5265 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5266 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005267 }
5268 }
5269
5270 // FIXME: Note that we can't easily compute the lexical context of a
5271 // statement or expression, so we return nothing.
5272 return clang_getNullCursor();
5273}
5274
Douglas Gregor9f592342010-10-01 20:25:15 +00005275static void CollectOverriddenMethods(DeclContext *Ctx,
5276 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005277 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005278 if (!Ctx)
5279 return;
5280
5281 // If we have a class or category implementation, jump straight to the
5282 // interface.
5283 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5284 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5285
5286 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5287 if (!Container)
5288 return;
5289
5290 // Check whether we have a matching method at this level.
5291 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5292 Method->isInstanceMethod()))
5293 if (Method != Overridden) {
5294 // We found an override at this level; there is no need to look
5295 // into other protocols or categories.
5296 Methods.push_back(Overridden);
5297 return;
5298 }
5299
5300 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5301 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5302 PEnd = Protocol->protocol_end();
5303 P != PEnd; ++P)
5304 CollectOverriddenMethods(*P, Method, Methods);
5305 }
5306
5307 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5308 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5309 PEnd = Category->protocol_end();
5310 P != PEnd; ++P)
5311 CollectOverriddenMethods(*P, Method, Methods);
5312 }
5313
5314 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5315 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5316 PEnd = Interface->protocol_end();
5317 P != PEnd; ++P)
5318 CollectOverriddenMethods(*P, Method, Methods);
5319
5320 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5321 Category; Category = Category->getNextClassCategory())
5322 CollectOverriddenMethods(Category, Method, Methods);
5323
5324 // We only look into the superclass if we haven't found anything yet.
5325 if (Methods.empty())
5326 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5327 return CollectOverriddenMethods(Super, Method, Methods);
5328 }
5329}
5330
5331void clang_getOverriddenCursors(CXCursor cursor,
5332 CXCursor **overridden,
5333 unsigned *num_overridden) {
5334 if (overridden)
5335 *overridden = 0;
5336 if (num_overridden)
5337 *num_overridden = 0;
5338 if (!overridden || !num_overridden)
5339 return;
5340
5341 if (!clang_isDeclaration(cursor.kind))
5342 return;
5343
5344 Decl *D = getCursorDecl(cursor);
5345 if (!D)
5346 return;
5347
5348 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005349 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005350 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5351 *num_overridden = CXXMethod->size_overridden_methods();
5352 if (!*num_overridden)
5353 return;
5354
5355 *overridden = new CXCursor [*num_overridden];
5356 unsigned I = 0;
5357 for (CXXMethodDecl::method_iterator
5358 M = CXXMethod->begin_overridden_methods(),
5359 MEnd = CXXMethod->end_overridden_methods();
5360 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005361 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005362 return;
5363 }
5364
5365 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5366 if (!Method)
5367 return;
5368
5369 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005370 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005371 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5372
5373 if (Methods.empty())
5374 return;
5375
5376 *num_overridden = Methods.size();
5377 *overridden = new CXCursor [Methods.size()];
5378 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005379 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005380}
5381
5382void clang_disposeOverriddenCursors(CXCursor *overridden) {
5383 delete [] overridden;
5384}
5385
Douglas Gregorecdcb882010-10-20 22:00:55 +00005386CXFile clang_getIncludedFile(CXCursor cursor) {
5387 if (cursor.kind != CXCursor_InclusionDirective)
5388 return 0;
5389
5390 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5391 return (void *)ID->getFile();
5392}
5393
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005394} // end: extern "C"
5395
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005396
5397//===----------------------------------------------------------------------===//
5398// C++ AST instrospection.
5399//===----------------------------------------------------------------------===//
5400
5401extern "C" {
5402unsigned clang_CXXMethod_isStatic(CXCursor C) {
5403 if (!clang_isDeclaration(C.kind))
5404 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005405
5406 CXXMethodDecl *Method = 0;
5407 Decl *D = cxcursor::getCursorDecl(C);
5408 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5409 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5410 else
5411 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5412 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005413}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005414
Douglas Gregor211924b2011-05-12 15:17:24 +00005415unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5416 if (!clang_isDeclaration(C.kind))
5417 return 0;
5418
5419 CXXMethodDecl *Method = 0;
5420 Decl *D = cxcursor::getCursorDecl(C);
5421 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5422 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5423 else
5424 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5425 return (Method && Method->isVirtual()) ? 1 : 0;
5426}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005427} // end: extern "C"
5428
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005429//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005430// Attribute introspection.
5431//===----------------------------------------------------------------------===//
5432
5433extern "C" {
5434CXType clang_getIBOutletCollectionType(CXCursor C) {
5435 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005436 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005437
5438 IBOutletCollectionAttr *A =
5439 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5440
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005441 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005442}
5443} // end: extern "C"
5444
5445//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005446// Inspecting memory usage.
5447//===----------------------------------------------------------------------===//
5448
Ted Kremenekf7870022011-04-20 16:41:07 +00005449typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005450
Ted Kremenekf7870022011-04-20 16:41:07 +00005451static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5452 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005453 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005454 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005455 entries.push_back(entry);
5456}
5457
5458extern "C" {
5459
Ted Kremenekf7870022011-04-20 16:41:07 +00005460const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005461 const char *str = "";
5462 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005463 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005464 str = "ASTContext: expressions, declarations, and types";
5465 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005466 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005467 str = "ASTContext: identifiers";
5468 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005469 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005470 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005471 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005472 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005473 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005474 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005475 case CXTUResourceUsage_SourceManagerContentCache:
5476 str = "SourceManager: content cache allocator";
5477 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005478 case CXTUResourceUsage_AST_SideTables:
5479 str = "ASTContext: side tables";
5480 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005481 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5482 str = "SourceManager: malloc'ed memory buffers";
5483 break;
5484 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5485 str = "SourceManager: mmap'ed memory buffers";
5486 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005487 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5488 str = "ExternalASTSource: malloc'ed memory buffers";
5489 break;
5490 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5491 str = "ExternalASTSource: mmap'ed memory buffers";
5492 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005493 case CXTUResourceUsage_Preprocessor:
5494 str = "Preprocessor: malloc'ed memory";
5495 break;
5496 case CXTUResourceUsage_PreprocessingRecord:
5497 str = "Preprocessor: PreprocessingRecord";
5498 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005499 case CXTUResourceUsage_SourceManager_DataStructures:
5500 str = "SourceManager: data structures and tables";
5501 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005502 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5503 str = "Preprocessor: header search tables";
5504 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005505 }
5506 return str;
5507}
5508
Ted Kremenekf7870022011-04-20 16:41:07 +00005509CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005510 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005511 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005512 return usage;
5513 }
5514
5515 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5516 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5517 ASTContext &astContext = astUnit->getASTContext();
5518
5519 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005520 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005521 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005522
5523 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005524 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005525 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5526
5527 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005528 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005529 (unsigned long) astContext.Selectors.getTotalMemory());
5530
Ted Kremenekba29bd22011-04-28 04:53:38 +00005531 // How much memory is used by ASTContext's side tables?
5532 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5533 (unsigned long) astContext.getSideTableAllocatedMemory());
5534
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005535 // How much memory is used for caching global code completion results?
5536 unsigned long completionBytes = 0;
5537 if (GlobalCodeCompletionAllocator *completionAllocator =
5538 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005539 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005540 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005541 createCXTUResourceUsageEntry(*entries,
5542 CXTUResourceUsage_GlobalCompletionResults,
5543 completionBytes);
5544
5545 // How much memory is being used by SourceManager's content cache?
5546 createCXTUResourceUsageEntry(*entries,
5547 CXTUResourceUsage_SourceManagerContentCache,
5548 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005549
5550 // How much memory is being used by the MemoryBuffer's in SourceManager?
5551 const SourceManager::MemoryBufferSizes &srcBufs =
5552 astUnit->getSourceManager().getMemoryBufferSizes();
5553
5554 createCXTUResourceUsageEntry(*entries,
5555 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5556 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005557 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005558 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5559 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005560 createCXTUResourceUsageEntry(*entries,
5561 CXTUResourceUsage_SourceManager_DataStructures,
5562 (unsigned long) astContext.getSourceManager()
5563 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005564
5565 // How much memory is being used by the ExternalASTSource?
5566 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5567 const ExternalASTSource::MemoryBufferSizes &sizes =
5568 esrc->getMemoryBufferSizes();
5569
5570 createCXTUResourceUsageEntry(*entries,
5571 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5572 (unsigned long) sizes.malloc_bytes);
5573 createCXTUResourceUsageEntry(*entries,
5574 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5575 (unsigned long) sizes.mmap_bytes);
5576 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005577
5578 // How much memory is being used by the Preprocessor?
5579 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005580 createCXTUResourceUsageEntry(*entries,
5581 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005582 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005583
5584 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5585 createCXTUResourceUsageEntry(*entries,
5586 CXTUResourceUsage_PreprocessingRecord,
5587 pRec->getTotalMemory());
5588 }
5589
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005590 createCXTUResourceUsageEntry(*entries,
5591 CXTUResourceUsage_Preprocessor_HeaderSearch,
5592 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005593
Ted Kremenekf7870022011-04-20 16:41:07 +00005594 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005595 (unsigned) entries->size(),
5596 entries->size() ? &(*entries)[0] : 0 };
5597 entries.take();
5598 return usage;
5599}
5600
Ted Kremenekf7870022011-04-20 16:41:07 +00005601void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005602 if (usage.data)
5603 delete (MemUsageEntries*) usage.data;
5604}
5605
5606} // end extern "C"
5607
Douglas Gregor6df78732011-05-05 20:27:22 +00005608void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5609 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5610 for (unsigned I = 0; I != Usage.numEntries; ++I)
5611 fprintf(stderr, " %s: %lu\n",
5612 clang_getTUResourceUsageName(Usage.entries[I].kind),
5613 Usage.entries[I].amount);
5614
5615 clang_disposeCXTUResourceUsage(Usage);
5616}
5617
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005618//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005619// Misc. utility functions.
5620//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005621
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005622/// Default to using an 8 MB stack size on "safety" threads.
5623static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005624
5625namespace clang {
5626
5627bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005628 void (*Fn)(void*), void *UserData,
5629 unsigned Size) {
5630 if (!Size)
5631 Size = GetSafetyThreadStackSize();
5632 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005633 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5634 return CRC.RunSafely(Fn, UserData);
5635}
5636
5637unsigned GetSafetyThreadStackSize() {
5638 return SafetyStackThreadSize;
5639}
5640
5641void SetSafetyThreadStackSize(unsigned Value) {
5642 SafetyStackThreadSize = Value;
5643}
5644
5645}
5646
Ted Kremenek04bb7162010-01-22 22:44:15 +00005647extern "C" {
5648
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005649CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005650 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005651}
5652
5653} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005654