blob: 8c2776d9f812d3864bbfad072f12460799fec8ca [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");
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +0000368 // Ignore implicit declarations, unless it's an objc method because
369 // currently we should report implicit methods for properties when indexing.
370 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 return false;
372 }
373
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374 // If we have a range of interest, and this cursor doesn't intersect with it,
375 // we're done.
376 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000377 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000378 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000379 return false;
380 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000381
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382 switch (Visitor(Cursor, Parent, ClientData)) {
383 case CXChildVisit_Break:
384 return true;
385
386 case CXChildVisit_Continue:
387 return false;
388
389 case CXChildVisit_Recurse:
390 return VisitChildren(Cursor);
391 }
392
Douglas Gregorfd643772010-01-25 16:45:46 +0000393 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000394}
395
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000396bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000397 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000398 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000399
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000400 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000401 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000402 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000403 Entities = PPRec.getPreprocessedEntitiesInRange(MappedRange);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000404 return visitPreprocessedEntities(Entities.first, Entities.second);
405 }
406
Douglas Gregor788f5a12010-03-20 00:41:21 +0000407 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000408 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
409
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000410 if (OnlyLocalDecls)
411 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000412
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000413 return visitPreprocessedEntities(PPRec.begin(), PPRec.end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000414}
415
416template<typename InputIterator>
417bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
418 InputIterator Last) {
419 for (; First != Last; ++First) {
420 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
421 if (Visit(MakeMacroExpansionCursor(ME, TU)))
422 return true;
423
424 continue;
425 }
426
427 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
428 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
429 return true;
430
431 continue;
432 }
433
434 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
435 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
436 return true;
437
438 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000439 }
440 }
441
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000442 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000443}
444
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000446///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447/// \returns true if the visitation should be aborted, false if it
448/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000449bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000450 if (clang_isReference(Cursor.kind) &&
451 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000452 // By definition, references have no children.
453 return false;
454 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455
456 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000458 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000459
Douglas Gregorb1373d02010-01-20 20:59:29 +0000460 if (clang_isDeclaration(Cursor.kind)) {
461 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000462 if (!D)
463 return false;
464
Ted Kremenek539311e2010-02-18 18:47:01 +0000465 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000467
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000468 if (clang_isStatement(Cursor.kind)) {
469 if (Stmt *S = getCursorStmt(Cursor))
470 return Visit(S);
471
472 return false;
473 }
474
475 if (clang_isExpression(Cursor.kind)) {
476 if (Expr *E = getCursorExpr(Cursor))
477 return Visit(E);
478
479 return false;
480 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000483 CXTranslationUnit tu = getCursorTU(Cursor);
484 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000485
486 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
487 for (unsigned I = 0; I != 2; ++I) {
488 if (VisitOrder[I]) {
489 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
490 RegionOfInterest.isInvalid()) {
491 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
492 TLEnd = CXXUnit->top_level_end();
493 TL != TLEnd; ++TL) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000494 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000495 return true;
496 }
497 } else if (VisitDeclContext(
498 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000499 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000500 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000501 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000502
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000503 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000504 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
505 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000506 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000507
Douglas Gregor7b691f332010-01-20 21:13:59 +0000508 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000510
Douglas Gregorc314aa42011-03-02 19:17:03 +0000511 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
512 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
513 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
514 return Visit(BaseTSInfo->getTypeLoc());
515 }
516 }
517 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000518
519 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
520 IBOutletCollectionAttr *A =
521 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
522 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
523 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
524 A->getInterfaceLoc(), TU));
525 }
526
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000528 return false;
529}
530
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000531bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000532 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
533 if (Visit(TSInfo->getTypeLoc()))
534 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000535
Ted Kremenek664cffd2010-07-22 11:30:19 +0000536 if (Stmt *Body = B->getBody())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000537 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
Ted Kremenek664cffd2010-07-22 11:30:19 +0000538
539 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000540}
541
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000542llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
543 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000544 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000545 if (Range.isInvalid())
546 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000547
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000548 switch (CompareRegionOfInterest(Range)) {
549 case RangeBefore:
550 // This declaration comes before the region of interest; skip it.
551 return llvm::Optional<bool>();
552
553 case RangeAfter:
554 // This declaration comes after the region of interest; we're done.
555 return false;
556
557 case RangeOverlap:
558 // This declaration overlaps the region of interest; visit it.
559 break;
560 }
561 }
562 return true;
563}
564
565bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
566 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
567
568 // FIXME: Eventually remove. This part of a hack to support proper
569 // iteration over all Decls contained lexically within an ObjC container.
570 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
571 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
572
573 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000574 Decl *D = *I;
575 if (D->getLexicalDeclContext() != DC)
576 continue;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000577 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000578 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
579 if (!V.hasValue())
580 continue;
581 if (!V.getValue())
582 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000583 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return true;
585 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000586 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000587}
588
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000589bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
590 llvm_unreachable("Translation units are visited directly by Visit()");
591 return false;
592}
593
Richard Smith162e1c12011-04-15 14:24:37 +0000594bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
595 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
596 return Visit(TSInfo->getTypeLoc());
597
598 return false;
599}
600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
602 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
603 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605 return false;
606}
607
608bool CursorVisitor::VisitTagDecl(TagDecl *D) {
609 return VisitDeclContext(D);
610}
611
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000612bool CursorVisitor::VisitClassTemplateSpecializationDecl(
613 ClassTemplateSpecializationDecl *D) {
614 bool ShouldVisitBody = false;
615 switch (D->getSpecializationKind()) {
616 case TSK_Undeclared:
617 case TSK_ImplicitInstantiation:
618 // Nothing to visit
619 return false;
620
621 case TSK_ExplicitInstantiationDeclaration:
622 case TSK_ExplicitInstantiationDefinition:
623 break;
624
625 case TSK_ExplicitSpecialization:
626 ShouldVisitBody = true;
627 break;
628 }
629
630 // Visit the template arguments used in the specialization.
631 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
632 TypeLoc TL = SpecType->getTypeLoc();
633 if (TemplateSpecializationTypeLoc *TSTLoc
634 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
635 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
636 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
637 return true;
638 }
639 }
640
641 if (ShouldVisitBody && VisitCXXRecordDecl(D))
642 return true;
643
644 return false;
645}
646
Douglas Gregor74dbe642010-08-31 19:31:58 +0000647bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
648 ClassTemplatePartialSpecializationDecl *D) {
649 // FIXME: Visit the "outer" template parameter lists on the TagDecl
650 // before visiting these template parameters.
651 if (VisitTemplateParameters(D->getTemplateParameters()))
652 return true;
653
654 // Visit the partial specialization arguments.
655 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
656 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
657 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
658 return true;
659
660 return VisitCXXRecordDecl(D);
661}
662
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000663bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000664 // Visit the default argument.
665 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
666 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
667 if (Visit(DefArg->getTypeLoc()))
668 return true;
669
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000670 return false;
671}
672
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000673bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
674 if (Expr *Init = D->getInitExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000675 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000676 return false;
677}
678
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000679bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
680 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
681 if (Visit(TSInfo->getTypeLoc()))
682 return true;
683
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000684 // Visit the nested-name-specifier, if present.
685 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
686 if (VisitNestedNameSpecifierLoc(QualifierLoc))
687 return true;
688
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000689 return false;
690}
691
Douglas Gregora67e03f2010-09-09 21:42:20 +0000692/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000693static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
694 CXXCtorInitializer const * const *X
695 = static_cast<CXXCtorInitializer const * const *>(Xp);
696 CXXCtorInitializer const * const *Y
697 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000698
699 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
700 return -1;
701 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
702 return 1;
703 else
704 return 0;
705}
706
Douglas Gregorb1373d02010-01-20 20:59:29 +0000707bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000708 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
709 // Visit the function declaration's syntactic components in the order
710 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000711 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000712 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
713
714 // If we have a function declared directly (without the use of a typedef),
715 // visit just the return type. Otherwise, just visit the function's type
716 // now.
717 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
718 (!FTL && Visit(TL)))
719 return true;
720
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000721 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000722 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
723 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000724 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000725
726 // Visit the declaration name.
727 if (VisitDeclarationNameInfo(ND->getNameInfo()))
728 return true;
729
730 // FIXME: Visit explicitly-specified template arguments!
731
732 // Visit the function parameters, if we have a function type.
733 if (FTL && VisitFunctionTypeLoc(*FTL, true))
734 return true;
735
736 // FIXME: Attributes?
737 }
738
Sean Hunt10620eb2011-05-06 20:44:56 +0000739 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000740 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
741 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000742 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000743 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
744 IEnd = Constructor->init_end();
745 I != IEnd; ++I) {
746 if (!(*I)->isWritten())
747 continue;
748
749 WrittenInits.push_back(*I);
750 }
751
752 // Sort the initializers in source order
753 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000754 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000755
756 // Visit the initializers in source order
757 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000758 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000759 if (Init->isAnyMemberInitializer()) {
760 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000761 Init->getMemberLocation(), TU)))
762 return true;
763 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
764 if (Visit(BaseInfo->getTypeLoc()))
765 return true;
766 }
767
768 // Visit the initializer value.
769 if (Expr *Initializer = Init->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000770 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000771 return true;
772 }
773 }
774
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000775 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregora67e03f2010-09-09 21:42:20 +0000776 return true;
777 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000778
Douglas Gregorb1373d02010-01-20 20:59:29 +0000779 return false;
780}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000781
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000782bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
783 if (VisitDeclaratorDecl(D))
784 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000785
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000786 if (Expr *BitWidth = D->getBitWidth())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000787 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000788
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000789 return false;
790}
791
792bool CursorVisitor::VisitVarDecl(VarDecl *D) {
793 if (VisitDeclaratorDecl(D))
794 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000795
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796 if (Expr *Init = D->getInit())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000797 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799 return false;
800}
801
Douglas Gregor84b51d72010-09-01 20:16:53 +0000802bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
803 if (VisitDeclaratorDecl(D))
804 return true;
805
806 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
807 if (Expr *DefArg = D->getDefaultArgument())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000808 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
Douglas Gregor84b51d72010-09-01 20:16:53 +0000809
810 return false;
811}
812
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000813bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
814 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
815 // before visiting these template parameters.
816 if (VisitTemplateParameters(D->getTemplateParameters()))
817 return true;
818
819 return VisitFunctionDecl(D->getTemplatedDecl());
820}
821
Douglas Gregor39d6f072010-08-31 19:02:00 +0000822bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
823 // FIXME: Visit the "outer" template parameter lists on the TagDecl
824 // before visiting these template parameters.
825 if (VisitTemplateParameters(D->getTemplateParameters()))
826 return true;
827
828 return VisitCXXRecordDecl(D->getTemplatedDecl());
829}
830
Douglas Gregor84b51d72010-09-01 20:16:53 +0000831bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
832 if (VisitTemplateParameters(D->getTemplateParameters()))
833 return true;
834
835 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
836 VisitTemplateArgumentLoc(D->getDefaultArgument()))
837 return true;
838
839 return false;
840}
841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000843 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
844 if (Visit(TSInfo->getTypeLoc()))
845 return true;
846
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000847 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000848 PEnd = ND->param_end();
849 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000850 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000851 return true;
852 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854 if (ND->isThisDeclarationADefinition() &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000855 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000857
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000858 return false;
859}
860
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000861namespace {
862 struct ContainerDeclsSort {
863 SourceManager &SM;
864 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
865 bool operator()(Decl *A, Decl *B) {
866 SourceLocation L_A = A->getLocStart();
867 SourceLocation L_B = B->getLocStart();
868 assert(L_A.isValid() && L_B.isValid());
869 return SM.isBeforeInTranslationUnit(L_A, L_B);
870 }
871 };
872}
873
Douglas Gregora59e3902010-01-21 23:27:09 +0000874bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000875 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
876 // an @implementation can lexically contain Decls that are not properly
877 // nested in the AST. When we identify such cases, we need to retrofit
878 // this nesting here.
879 if (!DI_current)
880 return VisitDeclContext(D);
881
882 // Scan the Decls that immediately come after the container
883 // in the current DeclContext. If any fall within the
884 // container's lexical region, stash them into a vector
885 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000886 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000887 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000888 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000889 if (EndLoc.isValid()) {
890 DeclContext::decl_iterator next = *DI_current;
891 while (++next != DE_current) {
892 Decl *D_next = *next;
893 if (!D_next)
894 break;
895 SourceLocation L = D_next->getLocStart();
896 if (!L.isValid())
897 break;
898 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
899 *DI_current = next;
900 DeclsInContainer.push_back(D_next);
901 continue;
902 }
903 break;
904 }
905 }
906
907 // The common case.
908 if (DeclsInContainer.empty())
909 return VisitDeclContext(D);
910
911 // Get all the Decls in the DeclContext, and sort them with the
912 // additional ones we've collected. Then visit them.
913 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
914 I!=E; ++I) {
915 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000916 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
917 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000918 continue;
919 DeclsInContainer.push_back(subDecl);
920 }
921
922 // Now sort the Decls so that they appear in lexical order.
923 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
924 ContainerDeclsSort(SM));
925
926 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000927 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000928 E = DeclsInContainer.end(); I != E; ++I) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000929 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000930 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
931 if (!V.hasValue())
932 continue;
933 if (!V.getValue())
934 return false;
935 if (Visit(Cursor, true))
936 return true;
937 }
938 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000939}
940
Douglas Gregorb1373d02010-01-20 20:59:29 +0000941bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000942 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
943 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000944 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000945
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000946 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
947 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
948 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000949 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000950 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000951
Douglas Gregora59e3902010-01-21 23:27:09 +0000952 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000953}
954
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000955bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
956 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
957 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
958 E = PID->protocol_end(); I != E; ++I, ++PL)
959 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
960 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000961
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000962 return VisitObjCContainerDecl(PID);
963}
964
Ted Kremenek23173d72010-05-18 21:09:07 +0000965bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000966 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000967 return true;
968
Ted Kremenek23173d72010-05-18 21:09:07 +0000969 // FIXME: This implements a workaround with @property declarations also being
970 // installed in the DeclContext for the @interface. Eventually this code
971 // should be removed.
972 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
973 if (!CDecl || !CDecl->IsClassExtension())
974 return false;
975
976 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
977 if (!ID)
978 return false;
979
980 IdentifierInfo *PropertyId = PD->getIdentifier();
981 ObjCPropertyDecl *prevDecl =
982 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
983
984 if (!prevDecl)
985 return false;
986
987 // Visit synthesized methods since they will be skipped when visiting
988 // the @interface.
989 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000990 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000991 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000992 return true;
993
994 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000995 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000996 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
Ted Kremenek23173d72010-05-18 21:09:07 +0000997 return true;
998
999 return false;
1000}
1001
Douglas Gregorb1373d02010-01-20 20:59:29 +00001002bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001003 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001004 if (D->getSuperClass() &&
1005 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001007 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001009
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001010 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1011 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1012 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001013 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001014 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001015
Douglas Gregora59e3902010-01-21 23:27:09 +00001016 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001017}
1018
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001019bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1020 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001021}
1022
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001023bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001024 // 'ID' could be null when dealing with invalid code.
1025 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1026 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1027 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001029 return VisitObjCImplDecl(D);
1030}
1031
1032bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1033#if 0
1034 // Issue callbacks for super class.
1035 // FIXME: No source location information!
1036 if (D->getSuperClass() &&
1037 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001038 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001039 TU)))
1040 return true;
1041#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001043 return VisitObjCImplDecl(D);
1044}
1045
1046bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1047 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1048 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1049 E = D->protocol_end();
1050 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001051 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001052 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001053
1054 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001055}
1056
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001057bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001058 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1059 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001060 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001062}
1063
Douglas Gregora4ffd852010-11-17 01:03:52 +00001064bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1065 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1066 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1067
1068 return false;
1069}
1070
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001071bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1072 return VisitDeclContext(D);
1073}
1074
Douglas Gregor69319002010-08-31 23:48:11 +00001075bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001076 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001077 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1078 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001079 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001080
1081 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1082 D->getTargetNameLoc(), TU));
1083}
1084
Douglas Gregor7e242562010-09-01 19:52:22 +00001085bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001086 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001087 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1088 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001089 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001090 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001091
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001092 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1093 return true;
1094
Douglas Gregor7e242562010-09-01 19:52:22 +00001095 return VisitDeclarationNameInfo(D->getNameInfo());
1096}
1097
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001098bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001099 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001100 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1101 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001102 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001103
1104 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1105 D->getIdentLocation(), TU));
1106}
1107
Douglas Gregor7e242562010-09-01 19:52:22 +00001108bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001109 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001110 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1111 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001112 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001113 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001114
Douglas Gregor7e242562010-09-01 19:52:22 +00001115 return VisitDeclarationNameInfo(D->getNameInfo());
1116}
1117
1118bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1119 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001121 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1122 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001123 return true;
1124
Douglas Gregor7e242562010-09-01 19:52:22 +00001125 return false;
1126}
1127
Douglas Gregor01829d32010-08-31 14:41:23 +00001128bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1129 switch (Name.getName().getNameKind()) {
1130 case clang::DeclarationName::Identifier:
1131 case clang::DeclarationName::CXXLiteralOperatorName:
1132 case clang::DeclarationName::CXXOperatorName:
1133 case clang::DeclarationName::CXXUsingDirective:
1134 return false;
1135
1136 case clang::DeclarationName::CXXConstructorName:
1137 case clang::DeclarationName::CXXDestructorName:
1138 case clang::DeclarationName::CXXConversionFunctionName:
1139 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1140 return Visit(TSInfo->getTypeLoc());
1141 return false;
1142
1143 case clang::DeclarationName::ObjCZeroArgSelector:
1144 case clang::DeclarationName::ObjCOneArgSelector:
1145 case clang::DeclarationName::ObjCMultiArgSelector:
1146 // FIXME: Per-identifier location info?
1147 return false;
1148 }
1149
1150 return false;
1151}
1152
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001153bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1154 SourceRange Range) {
1155 // FIXME: This whole routine is a hack to work around the lack of proper
1156 // source information in nested-name-specifiers (PR5791). Since we do have
1157 // a beginning source location, we can visit the first component of the
1158 // nested-name-specifier, if it's a single-token component.
1159 if (!NNS)
1160 return false;
1161
1162 // Get the first component in the nested-name-specifier.
1163 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1164 NNS = Prefix;
1165
1166 switch (NNS->getKind()) {
1167 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001168 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1169 TU));
1170
Douglas Gregor14aba762011-02-24 02:36:08 +00001171 case NestedNameSpecifier::NamespaceAlias:
1172 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1173 Range.getBegin(), TU));
1174
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001175 case NestedNameSpecifier::TypeSpec: {
1176 // If the type has a form where we know that the beginning of the source
1177 // range matches up with a reference cursor. Visit the appropriate reference
1178 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001179 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001180 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1181 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1182 if (const TagType *Tag = dyn_cast<TagType>(T))
1183 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1184 if (const TemplateSpecializationType *TST
1185 = dyn_cast<TemplateSpecializationType>(T))
1186 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1187 break;
1188 }
1189
1190 case NestedNameSpecifier::TypeSpecWithTemplate:
1191 case NestedNameSpecifier::Global:
1192 case NestedNameSpecifier::Identifier:
1193 break;
1194 }
1195
1196 return false;
1197}
1198
Douglas Gregordc355712011-02-25 00:36:19 +00001199bool
1200CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001201 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001202 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1203 Qualifiers.push_back(Qualifier);
1204
1205 while (!Qualifiers.empty()) {
1206 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1207 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1208 switch (NNS->getKind()) {
1209 case NestedNameSpecifier::Namespace:
1210 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001211 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001212 TU)))
1213 return true;
1214
1215 break;
1216
1217 case NestedNameSpecifier::NamespaceAlias:
1218 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001219 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001220 TU)))
1221 return true;
1222
1223 break;
1224
1225 case NestedNameSpecifier::TypeSpec:
1226 case NestedNameSpecifier::TypeSpecWithTemplate:
1227 if (Visit(Q.getTypeLoc()))
1228 return true;
1229
1230 break;
1231
1232 case NestedNameSpecifier::Global:
1233 case NestedNameSpecifier::Identifier:
1234 break;
1235 }
1236 }
1237
1238 return false;
1239}
1240
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001241bool CursorVisitor::VisitTemplateParameters(
1242 const TemplateParameterList *Params) {
1243 if (!Params)
1244 return false;
1245
1246 for (TemplateParameterList::const_iterator P = Params->begin(),
1247 PEnd = Params->end();
1248 P != PEnd; ++P) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001249 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001250 return true;
1251 }
1252
1253 return false;
1254}
1255
Douglas Gregor0b36e612010-08-31 20:37:03 +00001256bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1257 switch (Name.getKind()) {
1258 case TemplateName::Template:
1259 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1260
1261 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001262 // Visit the overloaded template set.
1263 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1264 return true;
1265
Douglas Gregor0b36e612010-08-31 20:37:03 +00001266 return false;
1267
1268 case TemplateName::DependentTemplate:
1269 // FIXME: Visit nested-name-specifier.
1270 return false;
1271
1272 case TemplateName::QualifiedTemplate:
1273 // FIXME: Visit nested-name-specifier.
1274 return Visit(MakeCursorTemplateRef(
1275 Name.getAsQualifiedTemplateName()->getDecl(),
1276 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001277
1278 case TemplateName::SubstTemplateTemplateParm:
1279 return Visit(MakeCursorTemplateRef(
1280 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1281 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001282
1283 case TemplateName::SubstTemplateTemplateParmPack:
1284 return Visit(MakeCursorTemplateRef(
1285 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1286 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001287 }
1288
1289 return false;
1290}
1291
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001292bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1293 switch (TAL.getArgument().getKind()) {
1294 case TemplateArgument::Null:
1295 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001296 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001297 return false;
1298
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001299 case TemplateArgument::Type:
1300 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1301 return Visit(TSInfo->getTypeLoc());
1302 return false;
1303
1304 case TemplateArgument::Declaration:
1305 if (Expr *E = TAL.getSourceDeclExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001306 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001307 return false;
1308
1309 case TemplateArgument::Expression:
1310 if (Expr *E = TAL.getSourceExpression())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001311 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001312 return false;
1313
1314 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001315 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001316 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1317 return true;
1318
Douglas Gregora7fc9012011-01-05 18:58:31 +00001319 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001320 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001321 }
1322
1323 return false;
1324}
1325
Ted Kremeneka0536d82010-05-07 01:04:29 +00001326bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1327 return VisitDeclContext(D);
1328}
1329
Douglas Gregor01829d32010-08-31 14:41:23 +00001330bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1331 return Visit(TL.getUnqualifiedLoc());
1332}
1333
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001335 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001336
1337 // Some builtin types (such as Objective-C's "id", "sel", and
1338 // "Class") have associated declarations. Create cursors for those.
1339 QualType VisitType;
1340 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001341 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001342 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001343 case BuiltinType::Char_U:
1344 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001345 case BuiltinType::Char16:
1346 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001347 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348 case BuiltinType::UInt:
1349 case BuiltinType::ULong:
1350 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001351 case BuiltinType::UInt128:
1352 case BuiltinType::Char_S:
1353 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001354 case BuiltinType::WChar_U:
1355 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001356 case BuiltinType::Short:
1357 case BuiltinType::Int:
1358 case BuiltinType::Long:
1359 case BuiltinType::LongLong:
1360 case BuiltinType::Int128:
1361 case BuiltinType::Float:
1362 case BuiltinType::Double:
1363 case BuiltinType::LongDouble:
1364 case BuiltinType::NullPtr:
1365 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001366 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001367 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001368 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001369 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001370
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001371 case BuiltinType::ObjCId:
1372 VisitType = Context.getObjCIdType();
1373 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001374
1375 case BuiltinType::ObjCClass:
1376 VisitType = Context.getObjCClassType();
1377 break;
1378
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001379 case BuiltinType::ObjCSel:
1380 VisitType = Context.getObjCSelType();
1381 break;
1382 }
1383
1384 if (!VisitType.isNull()) {
1385 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001386 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001387 TU));
1388 }
1389
1390 return false;
1391}
1392
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001393bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001394 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001395}
1396
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001397bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1398 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1399}
1400
1401bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001402 if (TL.isDefinition())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001403 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001404
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001405 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1406}
1407
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001408bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001409 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001410}
1411
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001412bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1413 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1414 return true;
1415
John McCallc12c5bb2010-05-15 11:32:37 +00001416 return false;
1417}
1418
1419bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1420 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1421 return true;
1422
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1424 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1425 TU)))
1426 return true;
1427 }
1428
1429 return false;
1430}
1431
1432bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001433 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001434}
1435
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001436bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1437 return Visit(TL.getInnerLoc());
1438}
1439
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001440bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1441 return Visit(TL.getPointeeLoc());
1442}
1443
1444bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1445 return Visit(TL.getPointeeLoc());
1446}
1447
1448bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1449 return Visit(TL.getPointeeLoc());
1450}
1451
1452bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001453 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001454}
1455
1456bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001457 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001458}
1459
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001460bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1461 return Visit(TL.getModifiedLoc());
1462}
1463
Douglas Gregor01829d32010-08-31 14:41:23 +00001464bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1465 bool SkipResultType) {
1466 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001467 return true;
1468
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001469 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001470 if (Decl *D = TL.getArg(I))
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001471 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001472 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001473
1474 return false;
1475}
1476
1477bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1478 if (Visit(TL.getElementLoc()))
1479 return true;
1480
1481 if (Expr *Size = TL.getSizeExpr())
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001482 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001483
1484 return false;
1485}
1486
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001487bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1488 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001489 // Visit the template name.
1490 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1491 TL.getTemplateNameLoc()))
1492 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001493
1494 // Visit the template arguments.
1495 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1496 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1497 return true;
1498
1499 return false;
1500}
1501
Douglas Gregor2332c112010-01-21 20:48:56 +00001502bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1503 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1504}
1505
1506bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1507 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1508 return Visit(TSInfo->getTypeLoc());
1509
1510 return false;
1511}
1512
Sean Huntca63c202011-05-24 22:41:36 +00001513bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1514 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1515 return Visit(TSInfo->getTypeLoc());
1516
1517 return false;
1518}
1519
Douglas Gregor2494dd02011-03-01 01:34:45 +00001520bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1521 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1522 return true;
1523
1524 return false;
1525}
1526
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001527bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1528 DependentTemplateSpecializationTypeLoc TL) {
1529 // Visit the nested-name-specifier, if there is one.
1530 if (TL.getQualifierLoc() &&
1531 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1532 return true;
1533
1534 // Visit the template arguments.
1535 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1536 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1537 return true;
1538
1539 return false;
1540}
1541
Douglas Gregor9e876872011-03-01 18:12:44 +00001542bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1543 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1544 return true;
1545
1546 return Visit(TL.getNamedTypeLoc());
1547}
1548
Douglas Gregor7536dd52010-12-20 02:24:11 +00001549bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1550 return Visit(TL.getPatternLoc());
1551}
1552
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001553bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1554 if (Expr *E = TL.getUnderlyingExpr())
1555 return Visit(MakeCXCursor(E, StmtParent, TU));
1556
1557 return false;
1558}
1559
1560bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1561 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1562}
1563
Eli Friedmanb001de72011-10-06 23:00:33 +00001564bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1565 return Visit(TL.getValueLoc());
1566}
1567
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001568#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1569bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1570 return Visit##PARENT##Loc(TL); \
1571}
1572
1573DEFAULT_TYPELOC_IMPL(Complex, Type)
1574DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1575DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1576DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1577DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1578DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1579DEFAULT_TYPELOC_IMPL(Vector, Type)
1580DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1581DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1582DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1583DEFAULT_TYPELOC_IMPL(Record, TagType)
1584DEFAULT_TYPELOC_IMPL(Enum, TagType)
1585DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1586DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1587DEFAULT_TYPELOC_IMPL(Auto, Type)
1588
Ted Kremenek3064ef92010-08-27 21:34:58 +00001589bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001590 // Visit the nested-name-specifier, if present.
1591 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1592 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1593 return true;
1594
Ted Kremenek3064ef92010-08-27 21:34:58 +00001595 if (D->isDefinition()) {
1596 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1597 E = D->bases_end(); I != E; ++I) {
1598 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1599 return true;
1600 }
1601 }
1602
1603 return VisitTagDecl(D);
1604}
1605
Ted Kremenek09dfa372010-02-18 05:46:33 +00001606bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001607 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1608 i != e; ++i)
1609 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001610 return true;
1611
1612 return false;
1613}
1614
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001615//===----------------------------------------------------------------------===//
1616// Data-recursive visitor methods.
1617//===----------------------------------------------------------------------===//
1618
Ted Kremenek28a71942010-11-13 00:36:47 +00001619namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001620#define DEF_JOB(NAME, DATA, KIND)\
1621class NAME : public VisitorJob {\
1622public:\
1623 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1624 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001625 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001626};
1627
1628DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1629DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001630DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001631DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001632DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001633 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001634DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001635#undef DEF_JOB
1636
1637class DeclVisit : public VisitorJob {
1638public:
1639 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1640 VisitorJob(parent, VisitorJob::DeclVisitKind,
1641 d, isFirst ? (void*) 1 : (void*) 0) {}
1642 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001643 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001644 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001645 Decl *get() const { return static_cast<Decl*>(data[0]); }
1646 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001647};
Ted Kremenek035dc412010-11-13 00:36:50 +00001648class TypeLocVisit : public VisitorJob {
1649public:
1650 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1651 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1652 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1653
1654 static bool classof(const VisitorJob *VJ) {
1655 return VJ->getKind() == TypeLocVisitKind;
1656 }
1657
Ted Kremenek82f3c502010-11-15 22:23:26 +00001658 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001659 QualType T = QualType::getFromOpaquePtr(data[0]);
1660 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001661 }
1662};
1663
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001664class LabelRefVisit : public VisitorJob {
1665public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001666 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1667 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001668 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001669
1670 static bool classof(const VisitorJob *VJ) {
1671 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1672 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001673 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001674 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001675 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001676};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001677
1678class NestedNameSpecifierLocVisit : public VisitorJob {
1679public:
1680 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1681 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1682 Qualifier.getNestedNameSpecifier(),
1683 Qualifier.getOpaqueData()) { }
1684
1685 static bool classof(const VisitorJob *VJ) {
1686 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1687 }
1688
1689 NestedNameSpecifierLoc get() const {
1690 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1691 data[1]);
1692 }
1693};
1694
Ted Kremenekf64d8032010-11-18 00:02:32 +00001695class DeclarationNameInfoVisit : public VisitorJob {
1696public:
1697 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1698 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1699 static bool classof(const VisitorJob *VJ) {
1700 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1701 }
1702 DeclarationNameInfo get() const {
1703 Stmt *S = static_cast<Stmt*>(data[0]);
1704 switch (S->getStmtClass()) {
1705 default:
1706 llvm_unreachable("Unhandled Stmt");
1707 case Stmt::CXXDependentScopeMemberExprClass:
1708 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1709 case Stmt::DependentScopeDeclRefExprClass:
1710 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1711 }
1712 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001713};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001714class MemberRefVisit : public VisitorJob {
1715public:
1716 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1717 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001718 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001719 static bool classof(const VisitorJob *VJ) {
1720 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1721 }
1722 FieldDecl *get() const {
1723 return static_cast<FieldDecl*>(data[0]);
1724 }
1725 SourceLocation getLoc() const {
1726 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1727 }
1728};
Ted Kremenek28a71942010-11-13 00:36:47 +00001729class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1730 VisitorWorkList &WL;
1731 CXCursor Parent;
1732public:
1733 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1734 : WL(wl), Parent(parent) {}
1735
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001736 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001737 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001738 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001739 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001740 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001741 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001742 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001743 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001744 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001745 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001746 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001747 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001748 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001749 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001750 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001751 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001752 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001753 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001754 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1755 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001756 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001757 void VisitIfStmt(IfStmt *If);
1758 void VisitInitListExpr(InitListExpr *IE);
1759 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001760 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001761 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001762 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1763 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001764 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001765 void VisitStmt(Stmt *S);
1766 void VisitSwitchStmt(SwitchStmt *S);
1767 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001768 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001769 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001770 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001771 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001772 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001773 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001774 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001775
Ted Kremenek28a71942010-11-13 00:36:47 +00001776private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001777 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001778 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001779 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001780 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001781 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001782 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001783 void AddTypeLoc(TypeSourceInfo *TI);
1784 void EnqueueChildren(Stmt *S);
1785};
1786} // end anonyous namespace
1787
Ted Kremenekf64d8032010-11-18 00:02:32 +00001788void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1789 // 'S' should always be non-null, since it comes from the
1790 // statement we are visiting.
1791 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1792}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001793
1794void
1795EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1796 if (Qualifier)
1797 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1798}
1799
Ted Kremenek28a71942010-11-13 00:36:47 +00001800void EnqueueVisitor::AddStmt(Stmt *S) {
1801 if (S)
1802 WL.push_back(StmtVisit(S, Parent));
1803}
Ted Kremenek035dc412010-11-13 00:36:50 +00001804void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001805 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001806 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001807}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001808void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001809 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001810 if (A)
1811 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001812 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001813}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001814void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1815 if (D)
1816 WL.push_back(MemberRefVisit(D, L, Parent));
1817}
Ted Kremenek28a71942010-11-13 00:36:47 +00001818void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1819 if (TI)
1820 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1821 }
1822void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001823 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001824 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001825 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001826 }
1827 if (size == WL.size())
1828 return;
1829 // Now reverse the entries we just added. This will match the DFS
1830 // ordering performed by the worklist.
1831 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1832 std::reverse(I, E);
1833}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001834void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1835 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1836}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001837void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1838 AddDecl(B->getBlockDecl());
1839}
Ted Kremenek28a71942010-11-13 00:36:47 +00001840void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1841 EnqueueChildren(E);
1842 AddTypeLoc(E->getTypeSourceInfo());
1843}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001844void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1845 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1846 E = S->body_rend(); I != E; ++I) {
1847 AddStmt(*I);
1848 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001849}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001850void EnqueueVisitor::
1851VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1852 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1853 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001854 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1855 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001856 if (!E->isImplicitAccess())
1857 AddStmt(E->getBase());
1858}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001859void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1860 // Enqueue the initializer or constructor arguments.
1861 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1862 AddStmt(E->getConstructorArg(I-1));
1863 // Enqueue the array size, if any.
1864 AddStmt(E->getArraySize());
1865 // Enqueue the allocated type.
1866 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1867 // Enqueue the placement arguments.
1868 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1869 AddStmt(E->getPlacementArg(I-1));
1870}
Ted Kremenek28a71942010-11-13 00:36:47 +00001871void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001872 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1873 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001874 AddStmt(CE->getCallee());
1875 AddStmt(CE->getArg(0));
1876}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001877void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1878 // Visit the name of the type being destroyed.
1879 AddTypeLoc(E->getDestroyedTypeInfo());
1880 // Visit the scope type that looks disturbingly like the nested-name-specifier
1881 // but isn't.
1882 AddTypeLoc(E->getScopeTypeInfo());
1883 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001884 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1885 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001886 // Visit base expression.
1887 AddStmt(E->getBase());
1888}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001889void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1890 AddTypeLoc(E->getTypeSourceInfo());
1891}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001892void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1893 EnqueueChildren(E);
1894 AddTypeLoc(E->getTypeSourceInfo());
1895}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001896void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1897 EnqueueChildren(E);
1898 if (E->isTypeOperand())
1899 AddTypeLoc(E->getTypeOperandSourceInfo());
1900}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001901
1902void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1903 *E) {
1904 EnqueueChildren(E);
1905 AddTypeLoc(E->getTypeSourceInfo());
1906}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001907void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1908 EnqueueChildren(E);
1909 if (E->isTypeOperand())
1910 AddTypeLoc(E->getTypeOperandSourceInfo());
1911}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001912void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001913 if (DR->hasExplicitTemplateArgs()) {
1914 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1915 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001916 WL.push_back(DeclRefExprParts(DR, Parent));
1917}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001918void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1919 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1920 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001921 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001922}
Ted Kremenek035dc412010-11-13 00:36:50 +00001923void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1924 unsigned size = WL.size();
1925 bool isFirst = true;
1926 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1927 D != DEnd; ++D) {
1928 AddDecl(*D, isFirst);
1929 isFirst = false;
1930 }
1931 if (size == WL.size())
1932 return;
1933 // Now reverse the entries we just added. This will match the DFS
1934 // ordering performed by the worklist.
1935 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1936 std::reverse(I, E);
1937}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001938void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1939 AddStmt(E->getInit());
1940 typedef DesignatedInitExpr::Designator Designator;
1941 for (DesignatedInitExpr::reverse_designators_iterator
1942 D = E->designators_rbegin(), DEnd = E->designators_rend();
1943 D != DEnd; ++D) {
1944 if (D->isFieldDesignator()) {
1945 if (FieldDecl *Field = D->getField())
1946 AddMemberRef(Field, D->getFieldLoc());
1947 continue;
1948 }
1949 if (D->isArrayDesignator()) {
1950 AddStmt(E->getArrayIndex(*D));
1951 continue;
1952 }
1953 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1954 AddStmt(E->getArrayRangeEnd(*D));
1955 AddStmt(E->getArrayRangeStart(*D));
1956 }
1957}
Ted Kremenek28a71942010-11-13 00:36:47 +00001958void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1959 EnqueueChildren(E);
1960 AddTypeLoc(E->getTypeInfoAsWritten());
1961}
1962void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1963 AddStmt(FS->getBody());
1964 AddStmt(FS->getInc());
1965 AddStmt(FS->getCond());
1966 AddDecl(FS->getConditionVariable());
1967 AddStmt(FS->getInit());
1968}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001969void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1970 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1971}
Ted Kremenek28a71942010-11-13 00:36:47 +00001972void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1973 AddStmt(If->getElse());
1974 AddStmt(If->getThen());
1975 AddStmt(If->getCond());
1976 AddDecl(If->getConditionVariable());
1977}
1978void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1979 // We care about the syntactic form of the initializer list, only.
1980 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1981 IE = Syntactic;
1982 EnqueueChildren(IE);
1983}
1984void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001985 WL.push_back(MemberExprParts(M, Parent));
1986
1987 // If the base of the member access expression is an implicit 'this', don't
1988 // visit it.
1989 // FIXME: If we ever want to show these implicit accesses, this will be
1990 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001991 if (!M->isImplicitAccess())
1992 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001993}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001994void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1995 AddTypeLoc(E->getEncodedTypeSourceInfo());
1996}
Ted Kremenek28a71942010-11-13 00:36:47 +00001997void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1998 EnqueueChildren(M);
1999 AddTypeLoc(M->getClassReceiverTypeInfo());
2000}
Ted Kremenekcdba6592010-11-18 00:42:18 +00002001void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2002 // Visit the components of the offsetof expression.
2003 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2004 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2005 const OffsetOfNode &Node = E->getComponent(I-1);
2006 switch (Node.getKind()) {
2007 case OffsetOfNode::Array:
2008 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2009 break;
2010 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002011 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002012 break;
2013 case OffsetOfNode::Identifier:
2014 case OffsetOfNode::Base:
2015 continue;
2016 }
2017 }
2018 // Visit the type into which we're computing the offset.
2019 AddTypeLoc(E->getTypeSourceInfo());
2020}
Ted Kremenek28a71942010-11-13 00:36:47 +00002021void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002022 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002023 WL.push_back(OverloadExprParts(E, Parent));
2024}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002025void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2026 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002027 EnqueueChildren(E);
2028 if (E->isArgumentType())
2029 AddTypeLoc(E->getArgumentTypeInfo());
2030}
Ted Kremenek28a71942010-11-13 00:36:47 +00002031void EnqueueVisitor::VisitStmt(Stmt *S) {
2032 EnqueueChildren(S);
2033}
2034void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2035 AddStmt(S->getBody());
2036 AddStmt(S->getCond());
2037 AddDecl(S->getConditionVariable());
2038}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002039
Ted Kremenek28a71942010-11-13 00:36:47 +00002040void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2041 AddStmt(W->getBody());
2042 AddStmt(W->getCond());
2043 AddDecl(W->getConditionVariable());
2044}
John Wiegley21ff2e52011-04-28 00:16:57 +00002045
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002046void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2047 AddTypeLoc(E->getQueriedTypeSourceInfo());
2048}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002049
2050void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002051 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002052 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002053}
2054
John Wiegley21ff2e52011-04-28 00:16:57 +00002055void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2056 AddTypeLoc(E->getQueriedTypeSourceInfo());
2057}
2058
John Wiegley55262202011-04-25 06:54:41 +00002059void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2060 EnqueueChildren(E);
2061}
2062
Ted Kremenek28a71942010-11-13 00:36:47 +00002063void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2064 VisitOverloadExpr(U);
2065 if (!U->isImplicitAccess())
2066 AddStmt(U->getBase());
2067}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002068void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2069 AddStmt(E->getSubExpr());
2070 AddTypeLoc(E->getWrittenTypeInfo());
2071}
Douglas Gregor94d96292011-01-19 20:34:17 +00002072void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2073 WL.push_back(SizeOfPackExprParts(E, Parent));
2074}
Ted Kremenek60458782010-11-12 21:34:16 +00002075
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002076void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002077 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002078}
2079
2080bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2081 if (RegionOfInterest.isValid()) {
2082 SourceRange Range = getRawCursorExtent(C);
2083 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2084 return false;
2085 }
2086 return true;
2087}
2088
2089bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2090 while (!WL.empty()) {
2091 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002092 VisitorJob LI = WL.back();
2093 WL.pop_back();
2094
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002095 // Set the Parent field, then back to its old value once we're done.
2096 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2097
2098 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002099 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002100 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002101 if (!D)
2102 continue;
2103
2104 // For now, perform default visitation for Decls.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002105 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2106 cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002107 return true;
2108
2109 continue;
2110 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002111 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002112 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002113 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2114 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2115 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2116 Arg != ArgEnd; ++Arg) {
2117 if (VisitTemplateArgumentLoc(*Arg))
2118 return true;
2119 }
2120 continue;
2121 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002122 case VisitorJob::TypeLocVisitKind: {
2123 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002124 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002125 return true;
2126 continue;
2127 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002128 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002129 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002130 if (LabelStmt *stmt = LS->getStmt()) {
2131 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2132 TU))) {
2133 return true;
2134 }
2135 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002136 continue;
2137 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002138
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002139 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2140 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2141 if (VisitNestedNameSpecifierLoc(V->get()))
2142 return true;
2143 continue;
2144 }
2145
Ted Kremenekf64d8032010-11-18 00:02:32 +00002146 case VisitorJob::DeclarationNameInfoVisitKind: {
2147 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2148 ->get()))
2149 return true;
2150 continue;
2151 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002152 case VisitorJob::MemberRefVisitKind: {
2153 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2154 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2155 return true;
2156 continue;
2157 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002158 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002159 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002160 if (!S)
2161 continue;
2162
Ted Kremenekf1107452010-11-12 18:26:56 +00002163 // Update the current cursor.
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002164 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002165 if (!IsInRegionOfInterest(Cursor))
2166 continue;
2167 switch (Visitor(Cursor, Parent, ClientData)) {
2168 case CXChildVisit_Break: return true;
2169 case CXChildVisit_Continue: break;
2170 case CXChildVisit_Recurse:
2171 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002172 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002173 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002174 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002175 }
2176 case VisitorJob::MemberExprPartsKind: {
2177 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002178 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002179
2180 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002181 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2182 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002183 return true;
2184
2185 // Visit the declaration name.
2186 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2187 return true;
2188
2189 // Visit the explicitly-specified template arguments, if any.
2190 if (M->hasExplicitTemplateArgs()) {
2191 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2192 *ArgEnd = Arg + M->getNumTemplateArgs();
2193 Arg != ArgEnd; ++Arg) {
2194 if (VisitTemplateArgumentLoc(*Arg))
2195 return true;
2196 }
2197 }
2198 continue;
2199 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002200 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002201 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002202 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002203 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2204 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002205 return true;
2206 // Visit declaration name.
2207 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2208 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002209 continue;
2210 }
Ted Kremenek60458782010-11-12 21:34:16 +00002211 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002212 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002213 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002214 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2215 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002216 return true;
2217 // Visit the declaration name.
2218 if (VisitDeclarationNameInfo(O->getNameInfo()))
2219 return true;
2220 // Visit the overloaded declaration reference.
2221 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2222 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002223 continue;
2224 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002225 case VisitorJob::SizeOfPackExprPartsKind: {
2226 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2227 NamedDecl *Pack = E->getPack();
2228 if (isa<TemplateTypeParmDecl>(Pack)) {
2229 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2230 E->getPackLoc(), TU)))
2231 return true;
2232
2233 continue;
2234 }
2235
2236 if (isa<TemplateTemplateParmDecl>(Pack)) {
2237 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2238 E->getPackLoc(), TU)))
2239 return true;
2240
2241 continue;
2242 }
2243
2244 // Non-type template parameter packs and function parameter packs are
2245 // treated like DeclRefExpr cursors.
2246 continue;
2247 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002248 }
2249 }
2250 return false;
2251}
2252
Ted Kremenekcdba6592010-11-18 00:42:18 +00002253bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002254 VisitorWorkList *WL = 0;
2255 if (!WorkListFreeList.empty()) {
2256 WL = WorkListFreeList.back();
2257 WL->clear();
2258 WorkListFreeList.pop_back();
2259 }
2260 else {
2261 WL = new VisitorWorkList();
2262 WorkListCache.push_back(WL);
2263 }
2264 EnqueueWorkList(*WL, S);
2265 bool result = RunVisitorWorkList(*WL);
2266 WorkListFreeList.push_back(WL);
2267 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002268}
2269
Francois Pichet48a8d142011-07-25 22:00:44 +00002270namespace {
2271typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2272RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2273 const DeclarationNameInfo &NI,
2274 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002275 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002276 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2277 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2278 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2279
2280 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2281
2282 RefNamePieces Pieces;
2283
2284 if (WantQualifier && QLoc.isValid())
2285 Pieces.push_back(QLoc);
2286
2287 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2288 Pieces.push_back(NI.getLoc());
2289
2290 if (WantTemplateArgs && TemplateArgs)
2291 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2292 TemplateArgs->RAngleLoc));
2293
2294 if (Kind == DeclarationName::CXXOperatorName) {
2295 Pieces.push_back(SourceLocation::getFromRawEncoding(
2296 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2297 Pieces.push_back(SourceLocation::getFromRawEncoding(
2298 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2299 }
2300
2301 if (WantSinglePiece) {
2302 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2303 Pieces.clear();
2304 Pieces.push_back(R);
2305 }
2306
2307 return Pieces;
2308}
2309}
2310
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002311//===----------------------------------------------------------------------===//
2312// Misc. API hooks.
2313//===----------------------------------------------------------------------===//
2314
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002315static llvm::sys::Mutex EnableMultithreadingMutex;
2316static bool EnabledMultithreading;
2317
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002318extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002319CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2320 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002321 // Disable pretty stack trace functionality, which will otherwise be a very
2322 // poor citizen of the world and set up all sorts of signal handlers.
2323 llvm::DisablePrettyStackTrace = true;
2324
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002325 // We use crash recovery to make some of our APIs more reliable, implicitly
2326 // enable it.
2327 llvm::CrashRecoveryContext::Enable();
2328
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002329 // Enable support for multithreading in LLVM.
2330 {
2331 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2332 if (!EnabledMultithreading) {
2333 llvm::llvm_start_multithreaded();
2334 EnabledMultithreading = true;
2335 }
2336 }
2337
Douglas Gregora030b7c2010-01-22 20:35:53 +00002338 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002339 if (excludeDeclarationsFromPCH)
2340 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002341 if (displayDiagnostics)
2342 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002343 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002344}
2345
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002346void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002347 if (CIdx)
2348 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002349}
2350
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002351void clang_toggleCrashRecovery(unsigned isEnabled) {
2352 if (isEnabled)
2353 llvm::CrashRecoveryContext::Enable();
2354 else
2355 llvm::CrashRecoveryContext::Disable();
2356}
2357
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002358CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002359 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002360 if (!CIdx)
2361 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002362
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002363 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002364 FileSystemOptions FileSystemOpts;
2365 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002366
David Blaikied6471f72011-09-25 23:23:43 +00002367 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002368 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002369 CXXIdx->getOnlyLocalDecls(),
2370 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002371 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002372}
2373
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002374unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002375 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002376 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002377}
2378
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002379CXTranslationUnit
2380clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2381 const char *source_filename,
2382 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002383 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002384 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002385 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002386 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002387 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002388 return clang_parseTranslationUnit(CIdx, source_filename,
2389 command_line_args, num_command_line_args,
2390 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002391 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002392}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002393
2394struct ParseTranslationUnitInfo {
2395 CXIndex CIdx;
2396 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002397 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002398 int num_command_line_args;
2399 struct CXUnsavedFile *unsaved_files;
2400 unsigned num_unsaved_files;
2401 unsigned options;
2402 CXTranslationUnit result;
2403};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002404static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002405 ParseTranslationUnitInfo *PTUI =
2406 static_cast<ParseTranslationUnitInfo*>(UserData);
2407 CXIndex CIdx = PTUI->CIdx;
2408 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002409 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002410 int num_command_line_args = PTUI->num_command_line_args;
2411 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2412 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2413 unsigned options = PTUI->options;
2414 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002415
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002416 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002417 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002418
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002419 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2420
Douglas Gregor44c181a2010-07-23 00:33:23 +00002421 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002422 // FIXME: Add a flag for modules.
2423 TranslationUnitKind TUKind
2424 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002425 bool CacheCodeCompetionResults
2426 = options & CXTranslationUnit_CacheCompletionResults;
2427
Douglas Gregor5352ac02010-01-28 00:27:43 +00002428 // Configure the diagnostics.
2429 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002430 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002431 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2432 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002433
Ted Kremenek25a11e12011-03-22 01:15:24 +00002434 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002435 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2436 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002437 DiagCleanup(Diags.getPtr());
2438
2439 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2440 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2441
2442 // Recover resources if we crash before exiting this function.
2443 llvm::CrashRecoveryContextCleanupRegistrar<
2444 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2445
Douglas Gregor4db64a42010-01-23 00:14:00 +00002446 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002447 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002448 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002449 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002450 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2451 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002452 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002453
Ted Kremenek25a11e12011-03-22 01:15:24 +00002454 llvm::OwningPtr<std::vector<const char *> >
2455 Args(new std::vector<const char*>());
2456
2457 // Recover resources if we crash before exiting this method.
2458 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2459 ArgsCleanup(Args.get());
2460
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002461 // Since the Clang C library is primarily used by batch tools dealing with
2462 // (often very broken) source code, where spell-checking can have a
2463 // significant negative impact on performance (particularly when
2464 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002465 // Only do this if we haven't found a spell-checking-related argument.
2466 bool FoundSpellCheckingArgument = false;
2467 for (int I = 0; I != num_command_line_args; ++I) {
2468 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2469 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2470 FoundSpellCheckingArgument = true;
2471 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002472 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002473 }
2474 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002475 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002476
Ted Kremenek25a11e12011-03-22 01:15:24 +00002477 Args->insert(Args->end(), command_line_args,
2478 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002479
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002480 // The 'source_filename' argument is optional. If the caller does not
2481 // specify it then it is assumed that the source file is specified
2482 // in the actual argument list.
2483 // Put the source file after command_line_args otherwise if '-x' flag is
2484 // present it will be unused.
2485 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002486 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002487
Douglas Gregor44c181a2010-07-23 00:33:23 +00002488 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002489 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002490 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002491 Args->push_back("-Xclang");
2492 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002493 NestedMacroExpansions
2494 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002495 }
2496
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002497 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002498 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002499 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2500 /* vector::data() not portable */,
2501 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002502 Diags,
2503 CXXIdx->getClangResourcesPath(),
2504 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002505 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002506 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002507 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002508 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002509 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002510 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002511 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002512 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002513
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002514 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002515 // Make sure to check that 'Unit' is non-NULL.
2516 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2517 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2518 DEnd = Unit->stored_diag_end();
2519 D != DEnd; ++D) {
2520 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2521 CXString Msg = clang_formatDiagnostic(&Diag,
2522 clang_defaultDiagnosticDisplayOptions());
2523 fprintf(stderr, "%s\n", clang_getCString(Msg));
2524 clang_disposeString(Msg);
2525 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002526#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002527 // On Windows, force a flush, since there may be multiple copies of
2528 // stderr and stdout in the file system, all with different buffers
2529 // but writing to the same device.
2530 fflush(stderr);
2531#endif
2532 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002533 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002534
Ted Kremeneka60ed472010-11-16 08:15:36 +00002535 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002536}
2537CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2538 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002539 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002540 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002541 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002542 unsigned num_unsaved_files,
2543 unsigned options) {
2544 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002545 num_command_line_args, unsaved_files,
2546 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002547 llvm::CrashRecoveryContext CRC;
2548
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002549 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002550 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2551 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2552 fprintf(stderr, " 'command_line_args' : [");
2553 for (int i = 0; i != num_command_line_args; ++i) {
2554 if (i)
2555 fprintf(stderr, ", ");
2556 fprintf(stderr, "'%s'", command_line_args[i]);
2557 }
2558 fprintf(stderr, "],\n");
2559 fprintf(stderr, " 'unsaved_files' : [");
2560 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2561 if (i)
2562 fprintf(stderr, ", ");
2563 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2564 unsaved_files[i].Length);
2565 }
2566 fprintf(stderr, "],\n");
2567 fprintf(stderr, " 'options' : %d,\n", options);
2568 fprintf(stderr, "}\n");
2569
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002570 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002571 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2572 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002573 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002574
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002575 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002576}
2577
Douglas Gregor19998442010-08-13 15:35:05 +00002578unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2579 return CXSaveTranslationUnit_None;
2580}
2581
2582int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2583 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002584 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002585 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002586
Douglas Gregor39c411f2011-07-06 16:43:36 +00002587 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002588 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2589 PrintLibclangResourceUsage(TU);
2590 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002591}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002592
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002593void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002594 if (CTUnit) {
2595 // If the translation unit has been marked as unsafe to free, just discard
2596 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002597 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002598 return;
2599
Ted Kremeneka60ed472010-11-16 08:15:36 +00002600 delete static_cast<ASTUnit *>(CTUnit->TUData);
2601 disposeCXStringPool(CTUnit->StringPool);
2602 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002603 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002604}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002605
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002606unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2607 return CXReparse_None;
2608}
2609
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002610struct ReparseTranslationUnitInfo {
2611 CXTranslationUnit TU;
2612 unsigned num_unsaved_files;
2613 struct CXUnsavedFile *unsaved_files;
2614 unsigned options;
2615 int result;
2616};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002617
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002618static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002619 ReparseTranslationUnitInfo *RTUI =
2620 static_cast<ReparseTranslationUnitInfo*>(UserData);
2621 CXTranslationUnit TU = RTUI->TU;
2622 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2623 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2624 unsigned options = RTUI->options;
2625 (void) options;
2626 RTUI->result = 1;
2627
Douglas Gregorabc563f2010-07-19 21:46:24 +00002628 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002629 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002630
Ted Kremeneka60ed472010-11-16 08:15:36 +00002631 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002632 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002633
Ted Kremenek25a11e12011-03-22 01:15:24 +00002634 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2635 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2636
2637 // Recover resources if we crash before exiting this function.
2638 llvm::CrashRecoveryContextCleanupRegistrar<
2639 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2640
Douglas Gregorabc563f2010-07-19 21:46:24 +00002641 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002642 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002643 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002644 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002645 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2646 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002647 }
2648
Ted Kremenek4ee99262011-03-22 20:16:19 +00002649 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2650 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002651 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002652}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002653
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002654int clang_reparseTranslationUnit(CXTranslationUnit TU,
2655 unsigned num_unsaved_files,
2656 struct CXUnsavedFile *unsaved_files,
2657 unsigned options) {
2658 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2659 options, 0 };
2660 llvm::CrashRecoveryContext CRC;
2661
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002662 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002663 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002664 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002665 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002666 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2667 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002668
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002669 return RTUI.result;
2670}
2671
Douglas Gregordf95a132010-08-09 20:45:32 +00002672
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002673CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002674 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002675 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002676
Ted Kremeneka60ed472010-11-16 08:15:36 +00002677 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002678 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002679}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002680
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002681CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002682 CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002683 return Result;
2684}
2685
Ted Kremenekfb480492010-01-13 21:46:36 +00002686} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002687
Ted Kremenekfb480492010-01-13 21:46:36 +00002688//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002689// CXSourceLocation and CXSourceRange Operations.
2690//===----------------------------------------------------------------------===//
2691
Douglas Gregorb9790342010-01-22 21:44:22 +00002692extern "C" {
2693CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002694 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002695 return Result;
2696}
2697
2698unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002699 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2700 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2701 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002702}
2703
2704CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2705 CXFile file,
2706 unsigned line,
2707 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002708 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002709 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002710
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002711 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002712 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002713 const FileEntry *File = static_cast<const FileEntry *>(file);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002714 SourceLocation SLoc = CXXUnit->getLocation(File, line, column);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002715 if (SLoc.isInvalid()) {
2716 if (Logging)
2717 llvm::errs() << "clang_getLocation(\"" << File->getName()
2718 << "\", " << line << ", " << column << ") = invalid\n";
2719 return clang_getNullLocation();
2720 }
2721
2722 if (Logging)
2723 llvm::errs() << "clang_getLocation(\"" << File->getName()
2724 << "\", " << line << ", " << column << ") = "
2725 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002726
2727 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2728}
2729
2730CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2731 CXFile file,
2732 unsigned offset) {
2733 if (!tu || !file)
2734 return clang_getNullLocation();
2735
Ted Kremeneka60ed472010-11-16 08:15:36 +00002736 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002737 SourceLocation SLoc
2738 = CXXUnit->getLocation(static_cast<const FileEntry *>(file), offset);
David Chisnall83889a72010-10-15 17:07:39 +00002739 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002740
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002741 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002742}
2743
Douglas Gregor5352ac02010-01-28 00:27:43 +00002744CXSourceRange clang_getNullRange() {
2745 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2746 return Result;
2747}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002748
Douglas Gregor5352ac02010-01-28 00:27:43 +00002749CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2750 if (begin.ptr_data[0] != end.ptr_data[0] ||
2751 begin.ptr_data[1] != end.ptr_data[1])
2752 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002753
2754 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002755 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002756 return Result;
2757}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002758
2759unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2760{
2761 return range1.ptr_data[0] == range2.ptr_data[0]
2762 && range1.ptr_data[1] == range2.ptr_data[1]
2763 && range1.begin_int_data == range2.begin_int_data
2764 && range1.end_int_data == range2.end_int_data;
2765}
Argyrios Kyrtzidisde5db642011-09-28 18:14:21 +00002766
2767int clang_Range_isNull(CXSourceRange range) {
2768 return clang_equalRanges(range, clang_getNullRange());
2769}
2770
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002771} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002772
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002773static void createNullLocation(CXFile *file, unsigned *line,
2774 unsigned *column, unsigned *offset) {
2775 if (file)
2776 *file = 0;
2777 if (line)
2778 *line = 0;
2779 if (column)
2780 *column = 0;
2781 if (offset)
2782 *offset = 0;
2783 return;
2784}
2785
2786extern "C" {
Chandler Carruth20174222011-08-31 16:53:37 +00002787void clang_getExpansionLocation(CXSourceLocation location,
2788 CXFile *file,
2789 unsigned *line,
2790 unsigned *column,
2791 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002792 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2793
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002794 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002795 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002796 return;
2797 }
2798
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002799 const SourceManager &SM =
2800 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth20174222011-08-31 16:53:37 +00002801 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002802
Chandler Carruthcea731a2011-07-14 16:07:57 +00002803 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002804 // This can manifest in invalid code.
Chandler Carruth20174222011-08-31 16:53:37 +00002805 FileID fileID = SM.getFileID(ExpansionLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002806 bool Invalid = false;
2807 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2808 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002809 createNullLocation(file, line, column, offset);
2810 return;
2811 }
2812
Douglas Gregor1db19de2010-01-19 21:36:55 +00002813 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002814 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002815 if (line)
Chandler Carruth20174222011-08-31 16:53:37 +00002816 *line = SM.getExpansionLineNumber(ExpansionLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002817 if (column)
Chandler Carruth20174222011-08-31 16:53:37 +00002818 *column = SM.getExpansionColumnNumber(ExpansionLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002819 if (offset)
Chandler Carruth20174222011-08-31 16:53:37 +00002820 *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2821}
2822
Argyrios Kyrtzidise6be34d2011-09-13 21:49:08 +00002823void clang_getPresumedLocation(CXSourceLocation location,
2824 CXString *filename,
2825 unsigned *line,
2826 unsigned *column) {
2827 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2828
2829 if (!location.ptr_data[0] || Loc.isInvalid()) {
2830 if (filename)
2831 *filename = createCXString("");
2832 if (line)
2833 *line = 0;
2834 if (column)
2835 *column = 0;
2836 }
2837 else {
2838 const SourceManager &SM =
2839 *static_cast<const SourceManager*>(location.ptr_data[0]);
2840 PresumedLoc PreLoc = SM.getPresumedLoc(Loc);
2841
2842 if (filename)
2843 *filename = createCXString(PreLoc.getFilename());
2844 if (line)
2845 *line = PreLoc.getLine();
2846 if (column)
2847 *column = PreLoc.getColumn();
2848 }
2849}
2850
Chandler Carruth20174222011-08-31 16:53:37 +00002851void clang_getInstantiationLocation(CXSourceLocation location,
2852 CXFile *file,
2853 unsigned *line,
2854 unsigned *column,
2855 unsigned *offset) {
2856 // Redirect to new API.
2857 clang_getExpansionLocation(location, file, line, column, offset);
Douglas Gregore69517c2010-01-26 03:07:15 +00002858}
2859
Douglas Gregora9b06d42010-11-09 06:24:54 +00002860void clang_getSpellingLocation(CXSourceLocation location,
2861 CXFile *file,
2862 unsigned *line,
2863 unsigned *column,
2864 unsigned *offset) {
2865 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2866
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002867 if (!location.ptr_data[0] || Loc.isInvalid())
2868 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002869
2870 const SourceManager &SM =
2871 *static_cast<const SourceManager*>(location.ptr_data[0]);
2872 SourceLocation SpellLoc = Loc;
2873 if (SpellLoc.isMacroID()) {
2874 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2875 if (SimpleSpellingLoc.isFileID() &&
2876 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2877 SpellLoc = SimpleSpellingLoc;
2878 else
Chandler Carruth40278532011-07-25 16:49:02 +00002879 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002880 }
2881
2882 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2883 FileID FID = LocInfo.first;
2884 unsigned FileOffset = LocInfo.second;
2885
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002886 if (FID.isInvalid())
2887 return createNullLocation(file, line, column, offset);
2888
Douglas Gregora9b06d42010-11-09 06:24:54 +00002889 if (file)
2890 *file = (void *)SM.getFileEntryForID(FID);
2891 if (line)
2892 *line = SM.getLineNumber(FID, FileOffset);
2893 if (column)
2894 *column = SM.getColumnNumber(FID, FileOffset);
2895 if (offset)
2896 *offset = FileOffset;
2897}
2898
Douglas Gregor1db19de2010-01-19 21:36:55 +00002899CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002900 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002901 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002902 return Result;
2903}
2904
2905CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002906 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002907 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002908 return Result;
2909}
2910
Douglas Gregorb9790342010-01-22 21:44:22 +00002911} // end: extern "C"
2912
Douglas Gregor1db19de2010-01-19 21:36:55 +00002913//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002914// CXFile Operations.
2915//===----------------------------------------------------------------------===//
2916
2917extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002918CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002919 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002920 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002921
Steve Naroff88145032009-10-27 14:35:18 +00002922 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002923 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002924}
2925
2926time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002927 if (!SFile)
2928 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002929
Steve Naroff88145032009-10-27 14:35:18 +00002930 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2931 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002932}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002933
Douglas Gregorb9790342010-01-22 21:44:22 +00002934CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2935 if (!tu)
2936 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002937
Ted Kremeneka60ed472010-11-16 08:15:36 +00002938 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002939
Douglas Gregorb9790342010-01-22 21:44:22 +00002940 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002941 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002942}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002943
Douglas Gregordd3e5542011-05-04 00:14:37 +00002944unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2945 if (!tu || !file)
2946 return 0;
2947
2948 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2949 FileEntry *FEnt = static_cast<FileEntry *>(file);
2950 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2951 .isFileMultipleIncludeGuarded(FEnt);
2952}
2953
Ted Kremenekfb480492010-01-13 21:46:36 +00002954} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002955
Ted Kremenekfb480492010-01-13 21:46:36 +00002956//===----------------------------------------------------------------------===//
2957// CXCursor Operations.
2958//===----------------------------------------------------------------------===//
2959
Ted Kremenekfb480492010-01-13 21:46:36 +00002960static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002961 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002962 return getDeclFromExpr(CE->getSubExpr());
2963
Ted Kremenekfb480492010-01-13 21:46:36 +00002964 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2965 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002966 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2967 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002968 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2969 return ME->getMemberDecl();
2970 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2971 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002972 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002973 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002974
Ted Kremenekfb480492010-01-13 21:46:36 +00002975 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2976 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002977 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002978 if (!CE->isElidable())
2979 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002980 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2981 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002982
Douglas Gregordb1314e2010-10-01 21:11:22 +00002983 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2984 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002985 if (SubstNonTypeTemplateParmPackExpr *NTTP
2986 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2987 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002988 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2989 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2990 isa<ParmVarDecl>(SizeOfPack->getPack()))
2991 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002992
Ted Kremenekfb480492010-01-13 21:46:36 +00002993 return 0;
2994}
2995
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002996static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002997 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2998 return getLocationFromExpr(CE->getSubExpr());
2999
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003000 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3001 return /*FIXME:*/Msg->getLeftLoc();
3002 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3003 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00003004 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
3005 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003006 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3007 return Member->getMemberLoc();
3008 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3009 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00003010 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3011 return SizeOfPack->getPackLoc();
3012
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003013 return E->getLocStart();
3014}
3015
Ted Kremenekfb480492010-01-13 21:46:36 +00003016extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003017
3018unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003019 CXCursorVisitor visitor,
3020 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003021 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003022 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003023 return CursorVis.VisitChildren(parent);
3024}
3025
David Chisnall3387c652010-11-03 14:12:26 +00003026#ifndef __has_feature
3027#define __has_feature(x) 0
3028#endif
3029#if __has_feature(blocks)
3030typedef enum CXChildVisitResult
3031 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3032
3033static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3034 CXClientData client_data) {
3035 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3036 return block(cursor, parent);
3037}
3038#else
3039// If we are compiled with a compiler that doesn't have native blocks support,
3040// define and call the block manually, so the
3041typedef struct _CXChildVisitResult
3042{
3043 void *isa;
3044 int flags;
3045 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003046 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3047 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003048} *CXCursorVisitorBlock;
3049
3050static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3051 CXClientData client_data) {
3052 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3053 return block->invoke(block, cursor, parent);
3054}
3055#endif
3056
3057
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003058unsigned clang_visitChildrenWithBlock(CXCursor parent,
3059 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003060 return clang_visitChildren(parent, visitWithBlock, block);
3061}
3062
Douglas Gregor78205d42010-01-20 21:45:58 +00003063static CXString getDeclSpelling(Decl *D) {
3064 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003065 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003066 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003067 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3068 return createCXString(Property->getIdentifier()->getName());
3069
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003070 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003071 }
3072
Douglas Gregor78205d42010-01-20 21:45:58 +00003073 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003074 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003075
Douglas Gregor78205d42010-01-20 21:45:58 +00003076 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3077 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3078 // and returns different names. NamedDecl returns the class name and
3079 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003080 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003081
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003082 if (isa<UsingDirectiveDecl>(D))
3083 return createCXString("");
3084
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003085 llvm::SmallString<1024> S;
3086 llvm::raw_svector_ostream os(S);
3087 ND->printName(os);
3088
3089 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003090}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003091
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003092CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003093 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003094 return clang_getTranslationUnitSpelling(
3095 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003096
Steve Narofff334b4e2009-09-02 18:26:48 +00003097 if (clang_isReference(C.kind)) {
3098 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003099 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003100 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003101 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003102 }
3103 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003104 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003105 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003106 }
3107 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003108 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003109 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003110 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003111 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003112 case CXCursor_CXXBaseSpecifier: {
3113 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3114 return createCXString(B->getType().getAsString());
3115 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003116 case CXCursor_TypeRef: {
3117 TypeDecl *Type = getCursorTypeRef(C).first;
3118 assert(Type && "Missing type decl");
3119
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003120 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3121 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003122 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003123 case CXCursor_TemplateRef: {
3124 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003125 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003126
3127 return createCXString(Template->getNameAsString());
3128 }
Douglas Gregor69319002010-08-31 23:48:11 +00003129
3130 case CXCursor_NamespaceRef: {
3131 NamedDecl *NS = getCursorNamespaceRef(C).first;
3132 assert(NS && "Missing namespace decl");
3133
3134 return createCXString(NS->getNameAsString());
3135 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003136
Douglas Gregora67e03f2010-09-09 21:42:20 +00003137 case CXCursor_MemberRef: {
3138 FieldDecl *Field = getCursorMemberRef(C).first;
3139 assert(Field && "Missing member decl");
3140
3141 return createCXString(Field->getNameAsString());
3142 }
3143
Douglas Gregor36897b02010-09-10 00:22:18 +00003144 case CXCursor_LabelRef: {
3145 LabelStmt *Label = getCursorLabelRef(C).first;
3146 assert(Label && "Missing label");
3147
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003148 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003149 }
3150
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003151 case CXCursor_OverloadedDeclRef: {
3152 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3153 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3154 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3155 return createCXString(ND->getNameAsString());
3156 return createCXString("");
3157 }
3158 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3159 return createCXString(E->getName().getAsString());
3160 OverloadedTemplateStorage *Ovl
3161 = Storage.get<OverloadedTemplateStorage*>();
3162 if (Ovl->size() == 0)
3163 return createCXString("");
3164 return createCXString((*Ovl->begin())->getNameAsString());
3165 }
3166
Daniel Dunbaracca7252009-11-30 20:42:49 +00003167 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003168 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003169 }
3170 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003171
3172 if (clang_isExpression(C.kind)) {
3173 Decl *D = getDeclFromExpr(getCursorExpr(C));
3174 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003175 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003176 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003177 }
3178
Douglas Gregor36897b02010-09-10 00:22:18 +00003179 if (clang_isStatement(C.kind)) {
3180 Stmt *S = getCursorStmt(C);
3181 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003182 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003183
3184 return createCXString("");
3185 }
3186
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003187 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003188 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003189 ->getNameStart());
3190
Douglas Gregor572feb22010-03-18 18:04:21 +00003191 if (C.kind == CXCursor_MacroDefinition)
3192 return createCXString(getCursorMacroDefinition(C)->getName()
3193 ->getNameStart());
3194
Douglas Gregorecdcb882010-10-20 22:00:55 +00003195 if (C.kind == CXCursor_InclusionDirective)
3196 return createCXString(getCursorInclusionDirective(C)->getFileName());
3197
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003198 if (clang_isDeclaration(C.kind))
3199 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003200
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003201 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003202}
3203
Douglas Gregor358559d2010-10-02 22:49:11 +00003204CXString clang_getCursorDisplayName(CXCursor C) {
3205 if (!clang_isDeclaration(C.kind))
3206 return clang_getCursorSpelling(C);
3207
3208 Decl *D = getCursorDecl(C);
3209 if (!D)
3210 return createCXString("");
3211
Douglas Gregor30c42402011-09-27 22:38:19 +00003212 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Douglas Gregor358559d2010-10-02 22:49:11 +00003213 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3214 D = FunTmpl->getTemplatedDecl();
3215
3216 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3217 llvm::SmallString<64> Str;
3218 llvm::raw_svector_ostream OS(Str);
3219 OS << Function->getNameAsString();
3220 if (Function->getPrimaryTemplate())
3221 OS << "<>";
3222 OS << "(";
3223 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3224 if (I)
3225 OS << ", ";
3226 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3227 }
3228
3229 if (Function->isVariadic()) {
3230 if (Function->getNumParams())
3231 OS << ", ";
3232 OS << "...";
3233 }
3234 OS << ")";
3235 return createCXString(OS.str());
3236 }
3237
3238 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3239 llvm::SmallString<64> Str;
3240 llvm::raw_svector_ostream OS(Str);
3241 OS << ClassTemplate->getNameAsString();
3242 OS << "<";
3243 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3244 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3245 if (I)
3246 OS << ", ";
3247
3248 NamedDecl *Param = Params->getParam(I);
3249 if (Param->getIdentifier()) {
3250 OS << Param->getIdentifier()->getName();
3251 continue;
3252 }
3253
3254 // There is no parameter name, which makes this tricky. Try to come up
3255 // with something useful that isn't too long.
3256 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3257 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3258 else if (NonTypeTemplateParmDecl *NTTP
3259 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3260 OS << NTTP->getType().getAsString(Policy);
3261 else
3262 OS << "template<...> class";
3263 }
3264
3265 OS << ">";
3266 return createCXString(OS.str());
3267 }
3268
3269 if (ClassTemplateSpecializationDecl *ClassSpec
3270 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3271 // If the type was explicitly written, use that.
3272 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3273 return createCXString(TSInfo->getType().getAsString(Policy));
3274
3275 llvm::SmallString<64> Str;
3276 llvm::raw_svector_ostream OS(Str);
3277 OS << ClassSpec->getNameAsString();
3278 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003279 ClassSpec->getTemplateArgs().data(),
3280 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003281 Policy);
3282 return createCXString(OS.str());
3283 }
3284
3285 return clang_getCursorSpelling(C);
3286}
3287
Ted Kremeneke68fff62010-02-17 00:41:32 +00003288CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003289 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003290 case CXCursor_FunctionDecl:
3291 return createCXString("FunctionDecl");
3292 case CXCursor_TypedefDecl:
3293 return createCXString("TypedefDecl");
3294 case CXCursor_EnumDecl:
3295 return createCXString("EnumDecl");
3296 case CXCursor_EnumConstantDecl:
3297 return createCXString("EnumConstantDecl");
3298 case CXCursor_StructDecl:
3299 return createCXString("StructDecl");
3300 case CXCursor_UnionDecl:
3301 return createCXString("UnionDecl");
3302 case CXCursor_ClassDecl:
3303 return createCXString("ClassDecl");
3304 case CXCursor_FieldDecl:
3305 return createCXString("FieldDecl");
3306 case CXCursor_VarDecl:
3307 return createCXString("VarDecl");
3308 case CXCursor_ParmDecl:
3309 return createCXString("ParmDecl");
3310 case CXCursor_ObjCInterfaceDecl:
3311 return createCXString("ObjCInterfaceDecl");
3312 case CXCursor_ObjCCategoryDecl:
3313 return createCXString("ObjCCategoryDecl");
3314 case CXCursor_ObjCProtocolDecl:
3315 return createCXString("ObjCProtocolDecl");
3316 case CXCursor_ObjCPropertyDecl:
3317 return createCXString("ObjCPropertyDecl");
3318 case CXCursor_ObjCIvarDecl:
3319 return createCXString("ObjCIvarDecl");
3320 case CXCursor_ObjCInstanceMethodDecl:
3321 return createCXString("ObjCInstanceMethodDecl");
3322 case CXCursor_ObjCClassMethodDecl:
3323 return createCXString("ObjCClassMethodDecl");
3324 case CXCursor_ObjCImplementationDecl:
3325 return createCXString("ObjCImplementationDecl");
3326 case CXCursor_ObjCCategoryImplDecl:
3327 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003328 case CXCursor_CXXMethod:
3329 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003330 case CXCursor_UnexposedDecl:
3331 return createCXString("UnexposedDecl");
3332 case CXCursor_ObjCSuperClassRef:
3333 return createCXString("ObjCSuperClassRef");
3334 case CXCursor_ObjCProtocolRef:
3335 return createCXString("ObjCProtocolRef");
3336 case CXCursor_ObjCClassRef:
3337 return createCXString("ObjCClassRef");
3338 case CXCursor_TypeRef:
3339 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003340 case CXCursor_TemplateRef:
3341 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003342 case CXCursor_NamespaceRef:
3343 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003344 case CXCursor_MemberRef:
3345 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003346 case CXCursor_LabelRef:
3347 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003348 case CXCursor_OverloadedDeclRef:
3349 return createCXString("OverloadedDeclRef");
Douglas Gregor42b29842011-10-05 19:00:14 +00003350 case CXCursor_IntegerLiteral:
3351 return createCXString("IntegerLiteral");
3352 case CXCursor_FloatingLiteral:
3353 return createCXString("FloatingLiteral");
3354 case CXCursor_ImaginaryLiteral:
3355 return createCXString("ImaginaryLiteral");
3356 case CXCursor_StringLiteral:
3357 return createCXString("StringLiteral");
3358 case CXCursor_CharacterLiteral:
3359 return createCXString("CharacterLiteral");
3360 case CXCursor_ParenExpr:
3361 return createCXString("ParenExpr");
3362 case CXCursor_UnaryOperator:
3363 return createCXString("UnaryOperator");
3364 case CXCursor_ArraySubscriptExpr:
3365 return createCXString("ArraySubscriptExpr");
3366 case CXCursor_BinaryOperator:
3367 return createCXString("BinaryOperator");
3368 case CXCursor_CompoundAssignOperator:
3369 return createCXString("CompoundAssignOperator");
3370 case CXCursor_ConditionalOperator:
3371 return createCXString("ConditionalOperator");
3372 case CXCursor_CStyleCastExpr:
3373 return createCXString("CStyleCastExpr");
3374 case CXCursor_CompoundLiteralExpr:
3375 return createCXString("CompoundLiteralExpr");
3376 case CXCursor_InitListExpr:
3377 return createCXString("InitListExpr");
3378 case CXCursor_AddrLabelExpr:
3379 return createCXString("AddrLabelExpr");
3380 case CXCursor_StmtExpr:
3381 return createCXString("StmtExpr");
3382 case CXCursor_GenericSelectionExpr:
3383 return createCXString("GenericSelectionExpr");
3384 case CXCursor_GNUNullExpr:
3385 return createCXString("GNUNullExpr");
3386 case CXCursor_CXXStaticCastExpr:
3387 return createCXString("CXXStaticCastExpr");
3388 case CXCursor_CXXDynamicCastExpr:
3389 return createCXString("CXXDynamicCastExpr");
3390 case CXCursor_CXXReinterpretCastExpr:
3391 return createCXString("CXXReinterpretCastExpr");
3392 case CXCursor_CXXConstCastExpr:
3393 return createCXString("CXXConstCastExpr");
3394 case CXCursor_CXXFunctionalCastExpr:
3395 return createCXString("CXXFunctionalCastExpr");
3396 case CXCursor_CXXTypeidExpr:
3397 return createCXString("CXXTypeidExpr");
3398 case CXCursor_CXXBoolLiteralExpr:
3399 return createCXString("CXXBoolLiteralExpr");
3400 case CXCursor_CXXNullPtrLiteralExpr:
3401 return createCXString("CXXNullPtrLiteralExpr");
3402 case CXCursor_CXXThisExpr:
3403 return createCXString("CXXThisExpr");
3404 case CXCursor_CXXThrowExpr:
3405 return createCXString("CXXThrowExpr");
3406 case CXCursor_CXXNewExpr:
3407 return createCXString("CXXNewExpr");
3408 case CXCursor_CXXDeleteExpr:
3409 return createCXString("CXXDeleteExpr");
3410 case CXCursor_UnaryExpr:
3411 return createCXString("UnaryExpr");
3412 case CXCursor_ObjCStringLiteral:
3413 return createCXString("ObjCStringLiteral");
3414 case CXCursor_ObjCEncodeExpr:
3415 return createCXString("ObjCEncodeExpr");
3416 case CXCursor_ObjCSelectorExpr:
3417 return createCXString("ObjCSelectorExpr");
3418 case CXCursor_ObjCProtocolExpr:
3419 return createCXString("ObjCProtocolExpr");
3420 case CXCursor_ObjCBridgedCastExpr:
3421 return createCXString("ObjCBridgedCastExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003422 case CXCursor_BlockExpr:
3423 return createCXString("BlockExpr");
Douglas Gregor42b29842011-10-05 19:00:14 +00003424 case CXCursor_PackExpansionExpr:
3425 return createCXString("PackExpansionExpr");
3426 case CXCursor_SizeOfPackExpr:
3427 return createCXString("SizeOfPackExpr");
3428 case CXCursor_UnexposedExpr:
3429 return createCXString("UnexposedExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003430 case CXCursor_DeclRefExpr:
3431 return createCXString("DeclRefExpr");
3432 case CXCursor_MemberRefExpr:
3433 return createCXString("MemberRefExpr");
3434 case CXCursor_CallExpr:
3435 return createCXString("CallExpr");
3436 case CXCursor_ObjCMessageExpr:
3437 return createCXString("ObjCMessageExpr");
3438 case CXCursor_UnexposedStmt:
3439 return createCXString("UnexposedStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003440 case CXCursor_DeclStmt:
3441 return createCXString("DeclStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003442 case CXCursor_LabelStmt:
3443 return createCXString("LabelStmt");
Douglas Gregor42b29842011-10-05 19:00:14 +00003444 case CXCursor_CompoundStmt:
3445 return createCXString("CompoundStmt");
3446 case CXCursor_CaseStmt:
3447 return createCXString("CaseStmt");
3448 case CXCursor_DefaultStmt:
3449 return createCXString("DefaultStmt");
3450 case CXCursor_IfStmt:
3451 return createCXString("IfStmt");
3452 case CXCursor_SwitchStmt:
3453 return createCXString("SwitchStmt");
3454 case CXCursor_WhileStmt:
3455 return createCXString("WhileStmt");
3456 case CXCursor_DoStmt:
3457 return createCXString("DoStmt");
3458 case CXCursor_ForStmt:
3459 return createCXString("ForStmt");
3460 case CXCursor_GotoStmt:
3461 return createCXString("GotoStmt");
3462 case CXCursor_IndirectGotoStmt:
3463 return createCXString("IndirectGotoStmt");
3464 case CXCursor_ContinueStmt:
3465 return createCXString("ContinueStmt");
3466 case CXCursor_BreakStmt:
3467 return createCXString("BreakStmt");
3468 case CXCursor_ReturnStmt:
3469 return createCXString("ReturnStmt");
3470 case CXCursor_AsmStmt:
3471 return createCXString("AsmStmt");
3472 case CXCursor_ObjCAtTryStmt:
3473 return createCXString("ObjCAtTryStmt");
3474 case CXCursor_ObjCAtCatchStmt:
3475 return createCXString("ObjCAtCatchStmt");
3476 case CXCursor_ObjCAtFinallyStmt:
3477 return createCXString("ObjCAtFinallyStmt");
3478 case CXCursor_ObjCAtThrowStmt:
3479 return createCXString("ObjCAtThrowStmt");
3480 case CXCursor_ObjCAtSynchronizedStmt:
3481 return createCXString("ObjCAtSynchronizedStmt");
3482 case CXCursor_ObjCAutoreleasePoolStmt:
3483 return createCXString("ObjCAutoreleasePoolStmt");
3484 case CXCursor_ObjCForCollectionStmt:
3485 return createCXString("ObjCForCollectionStmt");
3486 case CXCursor_CXXCatchStmt:
3487 return createCXString("CXXCatchStmt");
3488 case CXCursor_CXXTryStmt:
3489 return createCXString("CXXTryStmt");
3490 case CXCursor_CXXForRangeStmt:
3491 return createCXString("CXXForRangeStmt");
3492 case CXCursor_SEHTryStmt:
3493 return createCXString("SEHTryStmt");
3494 case CXCursor_SEHExceptStmt:
3495 return createCXString("SEHExceptStmt");
3496 case CXCursor_SEHFinallyStmt:
3497 return createCXString("SEHFinallyStmt");
3498 case CXCursor_NullStmt:
3499 return createCXString("NullStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003500 case CXCursor_InvalidFile:
3501 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003502 case CXCursor_InvalidCode:
3503 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003504 case CXCursor_NoDeclFound:
3505 return createCXString("NoDeclFound");
3506 case CXCursor_NotImplemented:
3507 return createCXString("NotImplemented");
3508 case CXCursor_TranslationUnit:
3509 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003510 case CXCursor_UnexposedAttr:
3511 return createCXString("UnexposedAttr");
3512 case CXCursor_IBActionAttr:
3513 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003514 case CXCursor_IBOutletAttr:
3515 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003516 case CXCursor_IBOutletCollectionAttr:
3517 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003518 case CXCursor_CXXFinalAttr:
3519 return createCXString("attribute(final)");
3520 case CXCursor_CXXOverrideAttr:
3521 return createCXString("attribute(override)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003522 case CXCursor_PreprocessingDirective:
3523 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003524 case CXCursor_MacroDefinition:
3525 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003526 case CXCursor_MacroExpansion:
3527 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003528 case CXCursor_InclusionDirective:
3529 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003530 case CXCursor_Namespace:
3531 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003532 case CXCursor_LinkageSpec:
3533 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003534 case CXCursor_CXXBaseSpecifier:
3535 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003536 case CXCursor_Constructor:
3537 return createCXString("CXXConstructor");
3538 case CXCursor_Destructor:
3539 return createCXString("CXXDestructor");
3540 case CXCursor_ConversionFunction:
3541 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003542 case CXCursor_TemplateTypeParameter:
3543 return createCXString("TemplateTypeParameter");
3544 case CXCursor_NonTypeTemplateParameter:
3545 return createCXString("NonTypeTemplateParameter");
3546 case CXCursor_TemplateTemplateParameter:
3547 return createCXString("TemplateTemplateParameter");
3548 case CXCursor_FunctionTemplate:
3549 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003550 case CXCursor_ClassTemplate:
3551 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003552 case CXCursor_ClassTemplatePartialSpecialization:
3553 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003554 case CXCursor_NamespaceAlias:
3555 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003556 case CXCursor_UsingDirective:
3557 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003558 case CXCursor_UsingDeclaration:
3559 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003560 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003561 return createCXString("TypeAliasDecl");
3562 case CXCursor_ObjCSynthesizeDecl:
3563 return createCXString("ObjCSynthesizeDecl");
3564 case CXCursor_ObjCDynamicDecl:
3565 return createCXString("ObjCDynamicDecl");
Argyrios Kyrtzidis2dfdb942011-09-30 17:58:23 +00003566 case CXCursor_CXXAccessSpecifier:
3567 return createCXString("CXXAccessSpecifier");
Steve Naroff89922f82009-08-31 00:59:03 +00003568 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003569
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003570 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003571 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003572}
Steve Naroff89922f82009-08-31 00:59:03 +00003573
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003574struct GetCursorData {
3575 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003576 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003577 CXCursor &BestCursor;
3578
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003579 GetCursorData(SourceManager &SM,
3580 SourceLocation tokenBegin, CXCursor &outputCursor)
3581 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3582 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3583 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003584};
3585
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003586static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3587 CXCursor parent,
3588 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003589 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3590 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003591
3592 // If we point inside a macro argument we should provide info of what the
3593 // token is so use the actual cursor, don't replace it with a macro expansion
3594 // cursor.
3595 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3596 return CXChildVisit_Recurse;
Argyrios Kyrtzidis65ab9072011-09-26 19:05:37 +00003597
3598 if (clang_isDeclaration(cursor.kind)) {
3599 // Avoid having the implicit methods override the property decls.
3600 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(getCursorDecl(cursor)))
3601 if (MD->isImplicit())
3602 return CXChildVisit_Break;
3603 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003604
3605 if (clang_isExpression(cursor.kind) &&
3606 clang_isDeclaration(BestCursor->kind)) {
3607 Decl *D = getCursorDecl(*BestCursor);
3608
3609 // Avoid having the cursor of an expression replace the declaration cursor
3610 // when the expression source range overlaps the declaration range.
3611 // This can happen for C++ constructor expressions whose range generally
3612 // include the variable declaration, e.g.:
3613 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3614 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3615 D->getLocation() == Data->TokenBeginLoc)
3616 return CXChildVisit_Break;
3617 }
3618
Douglas Gregor93798e22010-11-05 21:11:19 +00003619 // If our current best cursor is the construction of a temporary object,
3620 // don't replace that cursor with a type reference, because we want
3621 // clang_getCursor() to point at the constructor.
3622 if (clang_isExpression(BestCursor->kind) &&
3623 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003624 cursor.kind == CXCursor_TypeRef) {
3625 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3626 // as having the actual point on the type reference.
3627 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
Douglas Gregor93798e22010-11-05 21:11:19 +00003628 return CXChildVisit_Recurse;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003629 }
Douglas Gregor93798e22010-11-05 21:11:19 +00003630
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003631 *BestCursor = cursor;
3632 return CXChildVisit_Recurse;
3633}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003634
Douglas Gregorb9790342010-01-22 21:44:22 +00003635CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3636 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003637 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003638
Ted Kremeneka60ed472010-11-16 08:15:36 +00003639 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003640 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3641
Ted Kremeneka297de22010-01-25 22:34:44 +00003642 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003643 CXCursor Result = cxcursor::getCursor(TU, SLoc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003644
Douglas Gregor40749ee2010-11-03 00:35:38 +00003645 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregor40749ee2010-11-03 00:35:38 +00003646 if (Logging) {
3647 CXFile SearchFile;
3648 unsigned SearchLine, SearchColumn;
3649 CXFile ResultFile;
3650 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003651 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3652 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003653 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3654
Chandler Carruth20174222011-08-31 16:53:37 +00003655 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3656 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3657 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003658 SearchFileName = clang_getFileName(SearchFile);
3659 ResultFileName = clang_getFileName(ResultFile);
3660 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003661 USR = clang_getCursorUSR(Result);
3662 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003663 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3664 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003665 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3666 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003667 clang_disposeString(SearchFileName);
3668 clang_disposeString(ResultFileName);
3669 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003670 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003671
3672 CXCursor Definition = clang_getCursorDefinition(Result);
3673 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3674 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3675 CXString DefinitionKindSpelling
3676 = clang_getCursorKindSpelling(Definition.kind);
3677 CXFile DefinitionFile;
3678 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003679 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3680 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003681 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3682 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3683 clang_getCString(DefinitionKindSpelling),
3684 clang_getCString(DefinitionFileName),
3685 DefinitionLine, DefinitionColumn);
3686 clang_disposeString(DefinitionFileName);
3687 clang_disposeString(DefinitionKindSpelling);
3688 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003689 }
3690
Ted Kremeneke68fff62010-02-17 00:41:32 +00003691 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003692}
3693
Ted Kremenek73885552009-11-17 19:28:59 +00003694CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003695 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003696}
3697
3698unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003699 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003700}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003701
Douglas Gregor9ce55842010-11-20 00:09:34 +00003702unsigned clang_hashCursor(CXCursor C) {
3703 unsigned Index = 0;
3704 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3705 Index = 1;
3706
3707 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3708 std::make_pair(C.kind, C.data[Index]));
3709}
3710
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003711unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003712 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3713}
3714
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003715unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003716 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3717}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003718
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003719unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003720 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3721}
3722
Douglas Gregor97b98722010-01-19 23:20:36 +00003723unsigned clang_isExpression(enum CXCursorKind K) {
3724 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3725}
3726
3727unsigned clang_isStatement(enum CXCursorKind K) {
3728 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3729}
3730
Douglas Gregor8be80e12011-07-06 03:00:34 +00003731unsigned clang_isAttribute(enum CXCursorKind K) {
3732 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3733}
3734
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003735unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3736 return K == CXCursor_TranslationUnit;
3737}
3738
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003739unsigned clang_isPreprocessing(enum CXCursorKind K) {
3740 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3741}
3742
Ted Kremenekad6eff62010-03-08 21:17:29 +00003743unsigned clang_isUnexposed(enum CXCursorKind K) {
3744 switch (K) {
3745 case CXCursor_UnexposedDecl:
3746 case CXCursor_UnexposedExpr:
3747 case CXCursor_UnexposedStmt:
3748 case CXCursor_UnexposedAttr:
3749 return true;
3750 default:
3751 return false;
3752 }
3753}
3754
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003755CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003756 return C.kind;
3757}
3758
Douglas Gregor98258af2010-01-18 22:46:11 +00003759CXSourceLocation clang_getCursorLocation(CXCursor C) {
3760 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003761 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003762 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003763 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3764 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003765 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003766 }
3767
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003768 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003769 std::pair<ObjCProtocolDecl *, SourceLocation> P
3770 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003771 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003772 }
3773
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003774 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003775 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3776 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003777 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003778 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003779
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003780 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003781 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003782 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003783 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003784
3785 case CXCursor_TemplateRef: {
3786 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3787 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3788 }
3789
Douglas Gregor69319002010-08-31 23:48:11 +00003790 case CXCursor_NamespaceRef: {
3791 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3792 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3793 }
3794
Douglas Gregora67e03f2010-09-09 21:42:20 +00003795 case CXCursor_MemberRef: {
3796 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3797 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3798 }
3799
Ted Kremenek3064ef92010-08-27 21:34:58 +00003800 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003801 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3802 if (!BaseSpec)
3803 return clang_getNullLocation();
3804
3805 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3806 return cxloc::translateSourceLocation(getCursorContext(C),
3807 TSInfo->getTypeLoc().getBeginLoc());
3808
3809 return cxloc::translateSourceLocation(getCursorContext(C),
3810 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003811 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003812
Douglas Gregor36897b02010-09-10 00:22:18 +00003813 case CXCursor_LabelRef: {
3814 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3815 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3816 }
3817
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003818 case CXCursor_OverloadedDeclRef:
3819 return cxloc::translateSourceLocation(getCursorContext(C),
3820 getCursorOverloadedDeclRef(C).second);
3821
Douglas Gregorf46034a2010-01-18 23:41:10 +00003822 default:
3823 // FIXME: Need a way to enumerate all non-reference cases.
3824 llvm_unreachable("Missed a reference kind");
3825 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003826 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003827
3828 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003829 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003830 getLocationFromExpr(getCursorExpr(C)));
3831
Douglas Gregor36897b02010-09-10 00:22:18 +00003832 if (clang_isStatement(C.kind))
3833 return cxloc::translateSourceLocation(getCursorContext(C),
3834 getCursorStmt(C)->getLocStart());
3835
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003836 if (C.kind == CXCursor_PreprocessingDirective) {
3837 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3838 return cxloc::translateSourceLocation(getCursorContext(C), L);
3839 }
Douglas Gregor48072312010-03-18 15:23:44 +00003840
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003841 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003842 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003843 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003844 return cxloc::translateSourceLocation(getCursorContext(C), L);
3845 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003846
3847 if (C.kind == CXCursor_MacroDefinition) {
3848 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3849 return cxloc::translateSourceLocation(getCursorContext(C), L);
3850 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003851
3852 if (C.kind == CXCursor_InclusionDirective) {
3853 SourceLocation L
3854 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3855 return cxloc::translateSourceLocation(getCursorContext(C), L);
3856 }
3857
Ted Kremenek9a700d22010-05-12 06:16:13 +00003858 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003859 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003860
Douglas Gregorf46034a2010-01-18 23:41:10 +00003861 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003862 SourceLocation Loc = D->getLocation();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003863 // FIXME: Multiple variables declared in a single declaration
3864 // currently lack the information needed to correctly determine their
3865 // ranges when accounting for the type-specifier. We use context
3866 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3867 // and if so, whether it is the first decl.
3868 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3869 if (!cxcursor::isFirstInDeclGroup(C))
3870 Loc = VD->getLocation();
3871 }
3872
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003873 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003874}
Douglas Gregora7bde202010-01-19 00:34:46 +00003875
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003876} // end extern "C"
3877
Argyrios Kyrtzidis671436e2011-09-27 00:30:33 +00003878CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3879 assert(TU);
3880
3881 // Guard against an invalid SourceLocation, or we may assert in one
3882 // of the following calls.
3883 if (SLoc.isInvalid())
3884 return clang_getNullCursor();
3885
3886 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3887
3888 // Translate the given source location to make it point at the beginning of
3889 // the token under the cursor.
3890 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3891 CXXUnit->getASTContext().getLangOptions());
3892
3893 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3894 if (SLoc.isValid()) {
3895 // FIXME: Would be great to have a "hint" cursor, then walk from that
3896 // hint cursor upward until we find a cursor whose source range encloses
3897 // the region of interest, rather than starting from the translation unit.
3898 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
3899 CXCursor Parent = clang_getTranslationUnitCursor(TU);
3900 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3901 /*VisitPreprocessorLast=*/true,
3902 SourceLocation(SLoc));
3903 CursorVis.VisitChildren(Parent);
3904 }
3905
3906 return Result;
3907}
3908
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003909static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003910 if (clang_isReference(C.kind)) {
3911 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003912 case CXCursor_ObjCSuperClassRef:
3913 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003914
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003915 case CXCursor_ObjCProtocolRef:
3916 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003917
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003918 case CXCursor_ObjCClassRef:
3919 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003920
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003921 case CXCursor_TypeRef:
3922 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003923
3924 case CXCursor_TemplateRef:
3925 return getCursorTemplateRef(C).second;
3926
Douglas Gregor69319002010-08-31 23:48:11 +00003927 case CXCursor_NamespaceRef:
3928 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003929
3930 case CXCursor_MemberRef:
3931 return getCursorMemberRef(C).second;
3932
Ted Kremenek3064ef92010-08-27 21:34:58 +00003933 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003934 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003935
Douglas Gregor36897b02010-09-10 00:22:18 +00003936 case CXCursor_LabelRef:
3937 return getCursorLabelRef(C).second;
3938
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003939 case CXCursor_OverloadedDeclRef:
3940 return getCursorOverloadedDeclRef(C).second;
3941
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003942 default:
3943 // FIXME: Need a way to enumerate all non-reference cases.
3944 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003945 }
3946 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003947
3948 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003949 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003950
3951 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003952 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003953
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003954 if (clang_isAttribute(C.kind))
3955 return getCursorAttr(C)->getRange();
3956
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003957 if (C.kind == CXCursor_PreprocessingDirective)
3958 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003959
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003960 if (C.kind == CXCursor_MacroExpansion) {
3961 ASTUnit *TU = getCursorASTUnit(C);
3962 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3963 return TU->mapRangeFromPreamble(Range);
3964 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003965
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003966 if (C.kind == CXCursor_MacroDefinition) {
3967 ASTUnit *TU = getCursorASTUnit(C);
3968 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3969 return TU->mapRangeFromPreamble(Range);
3970 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003971
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003972 if (C.kind == CXCursor_InclusionDirective) {
3973 ASTUnit *TU = getCursorASTUnit(C);
3974 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3975 return TU->mapRangeFromPreamble(Range);
3976 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003977
Ted Kremenek007a7c92010-11-01 23:26:51 +00003978 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3979 Decl *D = cxcursor::getCursorDecl(C);
3980 SourceRange R = D->getSourceRange();
3981 // FIXME: Multiple variables declared in a single declaration
3982 // currently lack the information needed to correctly determine their
3983 // ranges when accounting for the type-specifier. We use context
3984 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3985 // and if so, whether it is the first decl.
3986 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3987 if (!cxcursor::isFirstInDeclGroup(C))
3988 R.setBegin(VD->getLocation());
3989 }
3990 return R;
3991 }
Douglas Gregor66537982010-11-17 17:14:07 +00003992 return SourceRange();
3993}
3994
3995/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3996/// the decl-specifier-seq for declarations.
3997static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3998 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3999 Decl *D = cxcursor::getCursorDecl(C);
4000 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00004001
Douglas Gregor2494dd02011-03-01 01:34:45 +00004002 // Adjust the start of the location for declarations preceded by
4003 // declaration specifiers.
4004 SourceLocation StartLoc;
4005 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4006 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4007 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4008 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4009 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4010 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4011 }
4012
4013 if (StartLoc.isValid() && R.getBegin().isValid() &&
4014 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4015 R.setBegin(StartLoc);
4016
4017 // FIXME: Multiple variables declared in a single declaration
4018 // currently lack the information needed to correctly determine their
4019 // ranges when accounting for the type-specifier. We use context
4020 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4021 // and if so, whether it is the first decl.
4022 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4023 if (!cxcursor::isFirstInDeclGroup(C))
4024 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00004025 }
4026
4027 return R;
4028 }
4029
4030 return getRawCursorExtent(C);
4031}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004032
4033extern "C" {
4034
4035CXSourceRange clang_getCursorExtent(CXCursor C) {
4036 SourceRange R = getRawCursorExtent(C);
4037 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00004038 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004039
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004040 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00004041}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004042
4043CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004044 if (clang_isInvalid(C.kind))
4045 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004046
Ted Kremeneka60ed472010-11-16 08:15:36 +00004047 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004048 if (clang_isDeclaration(C.kind)) {
4049 Decl *D = getCursorDecl(C);
4050 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004051 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004052 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004053 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004054 if (ObjCForwardProtocolDecl *Protocols
4055 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004056 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004057 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00004058 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4059 return MakeCXCursor(Property, tu);
4060
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004061 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004062 }
4063
Douglas Gregor97b98722010-01-19 23:20:36 +00004064 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004065 Expr *E = getCursorExpr(C);
4066 Decl *D = getDeclFromExpr(E);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00004067 if (D) {
4068 CXCursor declCursor = MakeCXCursor(D, tu);
4069 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4070 declCursor);
4071 return declCursor;
4072 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004073
4074 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004075 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004076
Douglas Gregor97b98722010-01-19 23:20:36 +00004077 return clang_getNullCursor();
4078 }
4079
Douglas Gregor36897b02010-09-10 00:22:18 +00004080 if (clang_isStatement(C.kind)) {
4081 Stmt *S = getCursorStmt(C);
4082 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00004083 if (LabelDecl *label = Goto->getLabel())
4084 if (LabelStmt *labelS = label->getStmt())
4085 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004086
4087 return clang_getNullCursor();
4088 }
4089
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004090 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00004091 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004092 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004093 }
4094
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004095 if (!clang_isReference(C.kind))
4096 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004097
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004098 switch (C.kind) {
4099 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004100 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004101
4102 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004103 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004104
4105 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004106 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00004107
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004108 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004109 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004110
4111 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004112 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00004113
Douglas Gregor69319002010-08-31 23:48:11 +00004114 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004115 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00004116
Douglas Gregora67e03f2010-09-09 21:42:20 +00004117 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004118 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00004119
Ted Kremenek3064ef92010-08-27 21:34:58 +00004120 case CXCursor_CXXBaseSpecifier: {
4121 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4122 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004123 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00004124 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004125
Douglas Gregor36897b02010-09-10 00:22:18 +00004126 case CXCursor_LabelRef:
4127 // FIXME: We end up faking the "parent" declaration here because we
4128 // don't want to make CXCursor larger.
4129 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004130 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4131 .getTranslationUnitDecl(),
4132 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00004133
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004134 case CXCursor_OverloadedDeclRef:
4135 return C;
4136
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004137 default:
4138 // We would prefer to enumerate all non-reference cursor kinds here.
4139 llvm_unreachable("Unhandled reference cursor kind");
4140 break;
4141 }
4142 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004143
Douglas Gregorc5d1e932010-01-19 01:20:04 +00004144 return clang_getNullCursor();
4145}
4146
Douglas Gregorb6998662010-01-19 19:34:47 +00004147CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004148 if (clang_isInvalid(C.kind))
4149 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004150
Ted Kremeneka60ed472010-11-16 08:15:36 +00004151 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004152
Douglas Gregorb6998662010-01-19 19:34:47 +00004153 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00004154 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00004155 C = clang_getCursorReferenced(C);
4156 WasReference = true;
4157 }
4158
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004159 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00004160 return clang_getCursorReferenced(C);
4161
Douglas Gregorb6998662010-01-19 19:34:47 +00004162 if (!clang_isDeclaration(C.kind))
4163 return clang_getNullCursor();
4164
4165 Decl *D = getCursorDecl(C);
4166 if (!D)
4167 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004168
Douglas Gregorb6998662010-01-19 19:34:47 +00004169 switch (D->getKind()) {
4170 // Declaration kinds that don't really separate the notions of
4171 // declaration and definition.
4172 case Decl::Namespace:
4173 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004174 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004175 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004176 case Decl::TemplateTypeParm:
4177 case Decl::EnumConstant:
4178 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004179 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004180 case Decl::ObjCIvar:
4181 case Decl::ObjCAtDefsField:
4182 case Decl::ImplicitParam:
4183 case Decl::ParmVar:
4184 case Decl::NonTypeTemplateParm:
4185 case Decl::TemplateTemplateParm:
4186 case Decl::ObjCCategoryImpl:
4187 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004188 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004189 case Decl::LinkageSpec:
4190 case Decl::ObjCPropertyImpl:
4191 case Decl::FileScopeAsm:
4192 case Decl::StaticAssert:
4193 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004194 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004195 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004196 return C;
4197
4198 // Declaration kinds that don't make any sense here, but are
4199 // nonetheless harmless.
4200 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004201 break;
4202
4203 // Declaration kinds for which the definition is not resolvable.
4204 case Decl::UnresolvedUsingTypename:
4205 case Decl::UnresolvedUsingValue:
4206 break;
4207
4208 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004209 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004210 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004211
4212 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004213 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004214
4215 case Decl::Enum:
4216 case Decl::Record:
4217 case Decl::CXXRecord:
4218 case Decl::ClassTemplateSpecialization:
4219 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004220 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004221 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004222 return clang_getNullCursor();
4223
4224 case Decl::Function:
4225 case Decl::CXXMethod:
4226 case Decl::CXXConstructor:
4227 case Decl::CXXDestructor:
4228 case Decl::CXXConversion: {
4229 const FunctionDecl *Def = 0;
4230 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004231 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004232 return clang_getNullCursor();
4233 }
4234
4235 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004236 // Ask the variable if it has a definition.
4237 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004238 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004239 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004240 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004241
Douglas Gregorb6998662010-01-19 19:34:47 +00004242 case Decl::FunctionTemplate: {
4243 const FunctionDecl *Def = 0;
4244 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004245 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004246 return clang_getNullCursor();
4247 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004248
Douglas Gregorb6998662010-01-19 19:34:47 +00004249 case Decl::ClassTemplate: {
4250 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004251 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004252 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004253 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004254 return clang_getNullCursor();
4255 }
4256
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004257 case Decl::Using:
4258 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004259 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004260
4261 case Decl::UsingShadow:
4262 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004263 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004264 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004265
4266 case Decl::ObjCMethod: {
4267 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4268 if (Method->isThisDeclarationADefinition())
4269 return C;
4270
4271 // Dig out the method definition in the associated
4272 // @implementation, if we have it.
4273 // FIXME: The ASTs should make finding the definition easier.
4274 if (ObjCInterfaceDecl *Class
4275 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4276 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4277 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4278 Method->isInstanceMethod()))
4279 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004280 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004281
4282 return clang_getNullCursor();
4283 }
4284
4285 case Decl::ObjCCategory:
4286 if (ObjCCategoryImplDecl *Impl
4287 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004288 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004289 return clang_getNullCursor();
4290
4291 case Decl::ObjCProtocol:
4292 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4293 return C;
4294 return clang_getNullCursor();
4295
4296 case Decl::ObjCInterface:
4297 // There are two notions of a "definition" for an Objective-C
4298 // class: the interface and its implementation. When we resolved a
4299 // reference to an Objective-C class, produce the @interface as
4300 // the definition; when we were provided with the interface,
4301 // produce the @implementation as the definition.
4302 if (WasReference) {
4303 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4304 return C;
4305 } else if (ObjCImplementationDecl *Impl
4306 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004307 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004308 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004309
Douglas Gregorb6998662010-01-19 19:34:47 +00004310 case Decl::ObjCProperty:
4311 // FIXME: We don't really know where to find the
4312 // ObjCPropertyImplDecls that implement this property.
4313 return clang_getNullCursor();
4314
4315 case Decl::ObjCCompatibleAlias:
4316 if (ObjCInterfaceDecl *Class
4317 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4318 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004319 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004320
Douglas Gregorb6998662010-01-19 19:34:47 +00004321 return clang_getNullCursor();
4322
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004323 case Decl::ObjCForwardProtocol:
4324 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004325 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004326
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004327 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004328 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004329 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004330
4331 case Decl::Friend:
4332 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004333 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004334 return clang_getNullCursor();
4335
4336 case Decl::FriendTemplate:
4337 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004338 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004339 return clang_getNullCursor();
4340 }
4341
4342 return clang_getNullCursor();
4343}
4344
4345unsigned clang_isCursorDefinition(CXCursor C) {
4346 if (!clang_isDeclaration(C.kind))
4347 return 0;
4348
4349 return clang_getCursorDefinition(C) == C;
4350}
4351
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004352CXCursor clang_getCanonicalCursor(CXCursor C) {
4353 if (!clang_isDeclaration(C.kind))
4354 return C;
4355
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004356 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004357 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4358 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4359 return MakeCXCursor(CatD, getCursorTU(C));
4360
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004361 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4362 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4363 return MakeCXCursor(IFD, getCursorTU(C));
4364
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004365 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004366 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004367
4368 return C;
4369}
4370
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004371unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004372 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004373 return 0;
4374
4375 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4376 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4377 return E->getNumDecls();
4378
4379 if (OverloadedTemplateStorage *S
4380 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4381 return S->size();
4382
4383 Decl *D = Storage.get<Decl*>();
4384 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004385 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004386 if (isa<ObjCClassDecl>(D))
4387 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004388 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4389 return Protocols->protocol_size();
4390
4391 return 0;
4392}
4393
4394CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004395 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004396 return clang_getNullCursor();
4397
4398 if (index >= clang_getNumOverloadedDecls(cursor))
4399 return clang_getNullCursor();
4400
Ted Kremeneka60ed472010-11-16 08:15:36 +00004401 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004402 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4403 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004404 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004405
4406 if (OverloadedTemplateStorage *S
4407 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004408 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004409
4410 Decl *D = Storage.get<Decl*>();
4411 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4412 // FIXME: This is, unfortunately, linear time.
4413 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4414 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004415 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004416 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004417 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004418 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004419 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004420 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004421
4422 return clang_getNullCursor();
4423}
4424
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004425void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004426 const char **startBuf,
4427 const char **endBuf,
4428 unsigned *startLine,
4429 unsigned *startColumn,
4430 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004431 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004432 assert(getCursorDecl(C) && "CXCursor has null decl");
4433 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004434 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4435 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004436
Steve Naroff4ade6d62009-09-23 17:52:52 +00004437 SourceManager &SM = FD->getASTContext().getSourceManager();
4438 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4439 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4440 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4441 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4442 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4443 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4444}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004445
Douglas Gregor430d7a12011-07-25 17:48:11 +00004446
4447CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4448 unsigned PieceIndex) {
4449 RefNamePieces Pieces;
4450
4451 switch (C.kind) {
4452 case CXCursor_MemberRefExpr:
4453 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4454 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4455 E->getQualifierLoc().getSourceRange());
4456 break;
4457
4458 case CXCursor_DeclRefExpr:
4459 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4460 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4461 E->getQualifierLoc().getSourceRange(),
4462 E->getExplicitTemplateArgsOpt());
4463 break;
4464
4465 case CXCursor_CallExpr:
4466 if (CXXOperatorCallExpr *OCE =
4467 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4468 Expr *Callee = OCE->getCallee();
4469 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4470 Callee = ICE->getSubExpr();
4471
4472 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4473 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4474 DRE->getQualifierLoc().getSourceRange());
4475 }
4476 break;
4477
4478 default:
4479 break;
4480 }
4481
4482 if (Pieces.empty()) {
4483 if (PieceIndex == 0)
4484 return clang_getCursorExtent(C);
4485 } else if (PieceIndex < Pieces.size()) {
4486 SourceRange R = Pieces[PieceIndex];
4487 if (R.isValid())
4488 return cxloc::translateSourceRange(getCursorContext(C), R);
4489 }
4490
4491 return clang_getNullRange();
4492}
4493
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004494void clang_enableStackTraces(void) {
4495 llvm::sys::PrintStackTraceOnErrorSignal();
4496}
4497
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004498void clang_executeOnThread(void (*fn)(void*), void *user_data,
4499 unsigned stack_size) {
4500 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4501}
4502
Ted Kremenekfb480492010-01-13 21:46:36 +00004503} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004504
Ted Kremenekfb480492010-01-13 21:46:36 +00004505//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004506// Token-based Operations.
4507//===----------------------------------------------------------------------===//
4508
4509/* CXToken layout:
4510 * int_data[0]: a CXTokenKind
4511 * int_data[1]: starting token location
4512 * int_data[2]: token length
4513 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004514 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004515 * otherwise unused.
4516 */
4517extern "C" {
4518
4519CXTokenKind clang_getTokenKind(CXToken CXTok) {
4520 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4521}
4522
4523CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4524 switch (clang_getTokenKind(CXTok)) {
4525 case CXToken_Identifier:
4526 case CXToken_Keyword:
4527 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004528 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4529 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004530
4531 case CXToken_Literal: {
4532 // We have stashed the starting pointer in the ptr_data field. Use it.
4533 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004534 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004535 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004536
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004537 case CXToken_Punctuation:
4538 case CXToken_Comment:
4539 break;
4540 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004541
4542 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004543 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004544 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004545 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004546 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004547
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004548 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4549 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004550 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004551 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004552 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004553 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4554 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004555 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004556
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004557 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004558}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004559
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004560CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004561 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004562 if (!CXXUnit)
4563 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004564
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004565 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4566 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4567}
4568
4569CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004570 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004571 if (!CXXUnit)
4572 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004573
4574 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004575 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4576}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004577
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004578static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4579 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004580 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4581 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004582 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004583 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004584 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004585
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004586 // Cannot tokenize across files.
4587 if (BeginLocInfo.first != EndLocInfo.first)
4588 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004589
4590 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004591 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004592 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004593 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004594 if (Invalid)
4595 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004596
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004597 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4598 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004599 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004600 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004601
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004602 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004603 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004604 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004605 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004606 do {
4607 // Lex the next token
4608 Lex.LexFromRawLexer(Tok);
4609 if (Tok.is(tok::eof))
4610 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004611
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004612 // Initialize the CXToken.
4613 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004614
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004615 // - Common fields
4616 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4617 CXTok.int_data[2] = Tok.getLength();
4618 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004619
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004620 // - Kind-specific fields
4621 if (Tok.isLiteral()) {
4622 CXTok.int_data[0] = CXToken_Literal;
4623 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004624 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004625 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004626 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004627 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004628
David Chisnall096428b2010-10-13 21:44:48 +00004629 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004630 CXTok.int_data[0] = CXToken_Keyword;
4631 }
4632 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004633 CXTok.int_data[0] = Tok.is(tok::identifier)
4634 ? CXToken_Identifier
4635 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004636 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004637 CXTok.ptr_data = II;
4638 } else if (Tok.is(tok::comment)) {
4639 CXTok.int_data[0] = CXToken_Comment;
4640 CXTok.ptr_data = 0;
4641 } else {
4642 CXTok.int_data[0] = CXToken_Punctuation;
4643 CXTok.ptr_data = 0;
4644 }
4645 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004646 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004647 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004648}
4649
4650void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4651 CXToken **Tokens, unsigned *NumTokens) {
4652 if (Tokens)
4653 *Tokens = 0;
4654 if (NumTokens)
4655 *NumTokens = 0;
4656
4657 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4658 if (!CXXUnit || !Tokens || !NumTokens)
4659 return;
4660
4661 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4662
4663 SourceRange R = cxloc::translateCXSourceRange(Range);
4664 if (R.isInvalid())
4665 return;
4666
4667 SmallVector<CXToken, 32> CXTokens;
4668 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004669
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004670 if (CXTokens.empty())
4671 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004672
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004673 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4674 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4675 *NumTokens = CXTokens.size();
4676}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004677
Ted Kremenek6db61092010-05-05 00:55:15 +00004678void clang_disposeTokens(CXTranslationUnit TU,
4679 CXToken *Tokens, unsigned NumTokens) {
4680 free(Tokens);
4681}
4682
4683} // end: extern "C"
4684
4685//===----------------------------------------------------------------------===//
4686// Token annotation APIs.
4687//===----------------------------------------------------------------------===//
4688
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004689typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004690static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4691 CXCursor parent,
4692 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004693namespace {
4694class AnnotateTokensWorker {
4695 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004696 CXToken *Tokens;
4697 CXCursor *Cursors;
4698 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004699 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004700 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004701 CursorVisitor AnnotateVis;
4702 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004703 bool HasContextSensitiveKeywords;
4704
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004705 bool MoreTokens() const { return TokIdx < NumTokens; }
4706 unsigned NextToken() const { return TokIdx; }
4707 void AdvanceToken() { ++TokIdx; }
4708 SourceLocation GetTokenLoc(unsigned tokI) {
4709 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4710 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004711 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004712 return Tokens[tokI].int_data[3] != 0;
4713 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004714 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004715 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4716 }
4717
4718 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004719 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4720 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004721
Ted Kremenek6db61092010-05-05 00:55:15 +00004722public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004723 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004724 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004725 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004726 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004727 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004728 AnnotateVis(tu,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00004729 AnnotateTokensVisitor, this, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004730 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4731 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004732
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004733 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004734 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004735 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004736 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004737 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004738 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004739
4740 /// \brief Determine whether the annotator saw any cursors that have
4741 /// context-sensitive keywords.
4742 bool hasContextSensitiveKeywords() const {
4743 return HasContextSensitiveKeywords;
4744 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004745};
4746}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004747
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004748void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4749 // Walk the AST within the region of interest, annotating tokens
4750 // along the way.
4751 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004752
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004753 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4754 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004755 if (Pos != Annotated.end() &&
4756 (clang_isInvalid(Cursors[I].kind) ||
4757 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004758 Cursors[I] = Pos->second;
4759 }
4760
4761 // Finish up annotating any tokens left.
4762 if (!MoreTokens())
4763 return;
4764
4765 const CXCursor &C = clang_getNullCursor();
4766 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4767 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4768 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004769 }
4770}
4771
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004772/// \brief It annotates and advances tokens with a cursor until the comparison
4773//// between the cursor location and the source range is the same as
4774/// \arg compResult.
4775///
4776/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4777/// Pass RangeOverlap to annotate tokens inside a range.
4778void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4779 RangeComparisonResult compResult,
4780 SourceRange range) {
4781 while (MoreTokens()) {
4782 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004783 if (isFunctionMacroToken(I))
4784 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004785
4786 SourceLocation TokLoc = GetTokenLoc(I);
4787 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4788 Cursors[I] = updateC;
4789 AdvanceToken();
4790 continue;
4791 }
4792 break;
4793 }
4794}
4795
4796/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004797void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4798 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004799 RangeComparisonResult compResult,
4800 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004801 assert(MoreTokens());
4802 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004803 "Should be called only for macro arg tokens");
4804
4805 // This works differently than annotateAndAdvanceTokens; because expanded
4806 // macro arguments can have arbitrary translation-unit source order, we do not
4807 // advance the token index one by one until a token fails the range test.
4808 // We only advance once past all of the macro arg tokens if all of them
4809 // pass the range test. If one of them fails we keep the token index pointing
4810 // at the start of the macro arg tokens so that the failing token will be
4811 // annotated by a subsequent annotation try.
4812
4813 bool atLeastOneCompFail = false;
4814
4815 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004816 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4817 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004818 if (TokLoc.isFileID())
4819 continue; // not macro arg token, it's parens or comma.
4820 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4821 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4822 Cursors[I] = updateC;
4823 } else
4824 atLeastOneCompFail = true;
4825 }
4826
4827 if (!atLeastOneCompFail)
4828 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4829}
4830
Ted Kremenek6db61092010-05-05 00:55:15 +00004831enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004832AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004833 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004834 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004835 if (cursorRange.isInvalid())
4836 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004837
4838 if (!HasContextSensitiveKeywords) {
4839 // Objective-C properties can have context-sensitive keywords.
4840 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4841 if (ObjCPropertyDecl *Property
4842 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4843 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4844 }
4845 // Objective-C methods can have context-sensitive keywords.
4846 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4847 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4848 if (ObjCMethodDecl *Method
4849 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4850 if (Method->getObjCDeclQualifier())
4851 HasContextSensitiveKeywords = true;
4852 else {
4853 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4854 PEnd = Method->param_end();
4855 P != PEnd; ++P) {
4856 if ((*P)->getObjCDeclQualifier()) {
4857 HasContextSensitiveKeywords = true;
4858 break;
4859 }
4860 }
4861 }
4862 }
4863 }
4864 // C++ methods can have context-sensitive keywords.
4865 else if (cursor.kind == CXCursor_CXXMethod) {
4866 if (CXXMethodDecl *Method
4867 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4868 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4869 HasContextSensitiveKeywords = true;
4870 }
4871 }
4872 // C++ classes can have context-sensitive keywords.
4873 else if (cursor.kind == CXCursor_StructDecl ||
4874 cursor.kind == CXCursor_ClassDecl ||
4875 cursor.kind == CXCursor_ClassTemplate ||
4876 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4877 if (Decl *D = getCursorDecl(cursor))
4878 if (D->hasAttr<FinalAttr>())
4879 HasContextSensitiveKeywords = true;
4880 }
4881 }
4882
Douglas Gregor4419b672010-10-21 06:10:04 +00004883 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004884 // For macro expansions, just note where the beginning of the macro
4885 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004886 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004887 Annotated[Loc.int_data] = cursor;
4888 return CXChildVisit_Recurse;
4889 }
4890
Douglas Gregor4419b672010-10-21 06:10:04 +00004891 // Items in the preprocessing record are kept separate from items in
4892 // declarations, so we keep a separate token index.
4893 unsigned SavedTokIdx = TokIdx;
4894 TokIdx = PreprocessingTokIdx;
4895
4896 // Skip tokens up until we catch up to the beginning of the preprocessing
4897 // entry.
4898 while (MoreTokens()) {
4899 const unsigned I = NextToken();
4900 SourceLocation TokLoc = GetTokenLoc(I);
4901 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4902 case RangeBefore:
4903 AdvanceToken();
4904 continue;
4905 case RangeAfter:
4906 case RangeOverlap:
4907 break;
4908 }
4909 break;
4910 }
4911
4912 // Look at all of the tokens within this range.
4913 while (MoreTokens()) {
4914 const unsigned I = NextToken();
4915 SourceLocation TokLoc = GetTokenLoc(I);
4916 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4917 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004918 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004919 case RangeAfter:
4920 break;
4921 case RangeOverlap:
4922 Cursors[I] = cursor;
4923 AdvanceToken();
4924 continue;
4925 }
4926 break;
4927 }
4928
4929 // Save the preprocessing token index; restore the non-preprocessing
4930 // token index.
4931 PreprocessingTokIdx = TokIdx;
4932 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004933 return CXChildVisit_Recurse;
4934 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004935
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004936 if (cursorRange.isInvalid())
4937 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004938
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004939 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4940
Ted Kremeneka333c662010-05-12 05:29:33 +00004941 // Adjust the annotated range based specific declarations.
4942 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4943 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004944 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004945
4946 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004947 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004948 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4949 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4950 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4951 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4952 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004953 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004954
4955 if (StartLoc.isValid() && L.isValid() &&
4956 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4957 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004958 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004959
Ted Kremenek3f404602010-08-14 01:14:06 +00004960 // If the location of the cursor occurs within a macro instantiation, record
4961 // the spelling location of the cursor in our annotation map. We can then
4962 // paper over the token labelings during a post-processing step to try and
4963 // get cursor mappings for tokens that are the *arguments* of a macro
4964 // instantiation.
4965 if (L.isMacroID()) {
4966 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4967 // Only invalidate the old annotation if it isn't part of a preprocessing
4968 // directive. Here we assume that the default construction of CXCursor
4969 // results in CXCursor.kind being an initialized value (i.e., 0). If
4970 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004971
Ted Kremenek3f404602010-08-14 01:14:06 +00004972 CXCursor &oldC = Annotated[rawEncoding];
4973 if (!clang_isPreprocessing(oldC.kind))
4974 oldC = cursor;
4975 }
4976
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004977 const enum CXCursorKind K = clang_getCursorKind(parent);
4978 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004979 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4980 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004981
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004982 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004983
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004984 // Avoid having the cursor of an expression "overwrite" the annotation of the
4985 // variable declaration that it belongs to.
4986 // This can happen for C++ constructor expressions whose range generally
4987 // include the variable declaration, e.g.:
4988 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4989 if (clang_isExpression(cursorK)) {
4990 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004991 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004992 const unsigned I = NextToken();
4993 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4994 E->getLocStart() == D->getLocation() &&
4995 E->getLocStart() == GetTokenLoc(I)) {
4996 Cursors[I] = updateC;
4997 AdvanceToken();
4998 }
4999 }
5000 }
5001
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005002 // Visit children to get their cursor information.
5003 const unsigned BeforeChildren = NextToken();
5004 VisitChildren(cursor);
5005 const unsigned AfterChildren = NextToken();
5006
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005007 // Scan the tokens that are at the end of the cursor, but are not captured
5008 // but the child cursors.
5009 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00005010
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005011 // Scan the tokens that are at the beginning of the cursor, but are not
5012 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005013 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5014 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5015 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00005016
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005017 Cursors[I] = cursor;
5018 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005019
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005020 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005021}
5022
Ted Kremenek6db61092010-05-05 00:55:15 +00005023static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5024 CXCursor parent,
5025 CXClientData client_data) {
5026 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5027}
5028
Ted Kremenek6628a612011-03-18 22:51:30 +00005029namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005030
5031/// \brief Uses the macro expansions in the preprocessing record to find
5032/// and mark tokens that are macro arguments. This info is used by the
5033/// AnnotateTokensWorker.
5034class MarkMacroArgTokensVisitor {
5035 SourceManager &SM;
5036 CXToken *Tokens;
5037 unsigned NumTokens;
5038 unsigned CurIdx;
5039
5040public:
5041 MarkMacroArgTokensVisitor(SourceManager &SM,
5042 CXToken *tokens, unsigned numTokens)
5043 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5044
5045 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5046 if (cursor.kind != CXCursor_MacroExpansion)
5047 return CXChildVisit_Continue;
5048
5049 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5050 if (macroRange.getBegin() == macroRange.getEnd())
5051 return CXChildVisit_Continue; // it's not a function macro.
5052
5053 for (; CurIdx < NumTokens; ++CurIdx) {
5054 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5055 macroRange.getBegin()))
5056 break;
5057 }
5058
5059 if (CurIdx == NumTokens)
5060 return CXChildVisit_Break;
5061
5062 for (; CurIdx < NumTokens; ++CurIdx) {
5063 SourceLocation tokLoc = getTokenLoc(CurIdx);
5064 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5065 break;
5066
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005067 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005068 }
5069
5070 if (CurIdx == NumTokens)
5071 return CXChildVisit_Break;
5072
5073 return CXChildVisit_Continue;
5074 }
5075
5076private:
5077 SourceLocation getTokenLoc(unsigned tokI) {
5078 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5079 }
5080
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00005081 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005082 // The third field is reserved and currently not used. Use it here
5083 // to mark macro arg expanded tokens with their expanded locations.
5084 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5085 }
5086};
5087
5088} // end anonymous namespace
5089
5090static CXChildVisitResult
5091MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5092 CXClientData client_data) {
5093 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5094 parent);
5095}
5096
5097namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00005098 struct clang_annotateTokens_Data {
5099 CXTranslationUnit TU;
5100 ASTUnit *CXXUnit;
5101 CXToken *Tokens;
5102 unsigned NumTokens;
5103 CXCursor *Cursors;
5104 };
5105}
5106
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005107static void annotatePreprocessorTokens(CXTranslationUnit TU,
5108 SourceRange RegionOfInterest,
5109 AnnotateTokensData &Annotated) {
5110 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5111
5112 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5113 std::pair<FileID, unsigned> BeginLocInfo
5114 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5115 std::pair<FileID, unsigned> EndLocInfo
5116 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5117
5118 if (BeginLocInfo.first != EndLocInfo.first)
5119 return;
5120
5121 StringRef Buffer;
5122 bool Invalid = false;
5123 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5124 if (Buffer.empty() || Invalid)
5125 return;
5126
5127 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5128 CXXUnit->getASTContext().getLangOptions(),
5129 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5130 Buffer.end());
5131 Lex.SetCommentRetentionState(true);
5132
5133 // Lex tokens in raw mode until we hit the end of the range, to avoid
5134 // entering #includes or expanding macros.
5135 while (true) {
5136 Token Tok;
5137 Lex.LexFromRawLexer(Tok);
5138
5139 reprocess:
5140 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5141 // We have found a preprocessing directive. Gobble it up so that we
5142 // don't see it while preprocessing these tokens later, but keep track
5143 // of all of the token locations inside this preprocessing directive so
5144 // that we can annotate them appropriately.
5145 //
5146 // FIXME: Some simple tests here could identify macro definitions and
5147 // #undefs, to provide specific cursor kinds for those.
5148 SmallVector<SourceLocation, 32> Locations;
5149 do {
5150 Locations.push_back(Tok.getLocation());
5151 Lex.LexFromRawLexer(Tok);
5152 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5153
5154 using namespace cxcursor;
5155 CXCursor Cursor
5156 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5157 Locations.back()),
5158 TU);
5159 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5160 Annotated[Locations[I].getRawEncoding()] = Cursor;
5161 }
5162
5163 if (Tok.isAtStartOfLine())
5164 goto reprocess;
5165
5166 continue;
5167 }
5168
5169 if (Tok.is(tok::eof))
5170 break;
5171 }
5172}
5173
Ted Kremenekab979612010-11-11 08:05:23 +00005174// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005175static void clang_annotateTokensImpl(void *UserData) {
5176 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5177 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5178 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5179 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5180 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5181
5182 // Determine the region of interest, which contains all of the tokens.
5183 SourceRange RegionOfInterest;
5184 RegionOfInterest.setBegin(
5185 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5186 RegionOfInterest.setEnd(
5187 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5188 Tokens[NumTokens-1])));
5189
5190 // A mapping from the source locations found when re-lexing or traversing the
5191 // region of interest to the corresponding cursors.
5192 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005193
Ted Kremenek6628a612011-03-18 22:51:30 +00005194 // Relex the tokens within the source range to look for preprocessing
5195 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005196 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005197
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005198 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5199 // Search and mark tokens that are macro argument expansions.
5200 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5201 Tokens, NumTokens);
5202 CursorVisitor MacroArgMarker(TU,
5203 MarkMacroArgTokensVisitorDelegate, &Visitor,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00005204 true, RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005205 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5206 }
5207
Ted Kremenek6628a612011-03-18 22:51:30 +00005208 // Annotate all of the source locations in the region of interest that map to
5209 // a specific cursor.
5210 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5211 TU, RegionOfInterest);
5212
5213 // FIXME: We use a ridiculous stack size here because the data-recursion
5214 // algorithm uses a large stack frame than the non-data recursive version,
5215 // and AnnotationTokensWorker currently transforms the data-recursion
5216 // algorithm back into a traditional recursion by explicitly calling
5217 // VisitChildren(). We will need to remove this explicit recursive call.
5218 W.AnnotateTokens();
5219
5220 // If we ran into any entities that involve context-sensitive keywords,
5221 // take another pass through the tokens to mark them as such.
5222 if (W.hasContextSensitiveKeywords()) {
5223 for (unsigned I = 0; I != NumTokens; ++I) {
5224 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5225 continue;
5226
5227 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5228 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5229 if (ObjCPropertyDecl *Property
5230 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5231 if (Property->getPropertyAttributesAsWritten() != 0 &&
5232 llvm::StringSwitch<bool>(II->getName())
5233 .Case("readonly", true)
5234 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005235 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005236 .Case("readwrite", true)
5237 .Case("retain", true)
5238 .Case("copy", true)
5239 .Case("nonatomic", true)
5240 .Case("atomic", true)
5241 .Case("getter", true)
5242 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005243 .Case("strong", true)
5244 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005245 .Default(false))
5246 Tokens[I].int_data[0] = CXToken_Keyword;
5247 }
5248 continue;
5249 }
5250
5251 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5252 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5253 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5254 if (llvm::StringSwitch<bool>(II->getName())
5255 .Case("in", true)
5256 .Case("out", true)
5257 .Case("inout", true)
5258 .Case("oneway", true)
5259 .Case("bycopy", true)
5260 .Case("byref", true)
5261 .Default(false))
5262 Tokens[I].int_data[0] = CXToken_Keyword;
5263 continue;
5264 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005265
5266 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5267 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5268 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005269 continue;
5270 }
5271 }
5272 }
Ted Kremenekab979612010-11-11 08:05:23 +00005273}
5274
Ted Kremenek6db61092010-05-05 00:55:15 +00005275extern "C" {
5276
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005277void clang_annotateTokens(CXTranslationUnit TU,
5278 CXToken *Tokens, unsigned NumTokens,
5279 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005280
5281 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005282 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005283
Douglas Gregor4419b672010-10-21 06:10:04 +00005284 // Any token we don't specifically annotate will have a NULL cursor.
5285 CXCursor C = clang_getNullCursor();
5286 for (unsigned I = 0; I != NumTokens; ++I)
5287 Cursors[I] = C;
5288
Ted Kremeneka60ed472010-11-16 08:15:36 +00005289 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005290 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005291 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005292
Douglas Gregorbdf60622010-03-05 21:16:25 +00005293 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005294
5295 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005296 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005297 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005298 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005299 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5300 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005301}
Ted Kremenek6628a612011-03-18 22:51:30 +00005302
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005303} // end: extern "C"
5304
5305//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005306// Operations for querying linkage of a cursor.
5307//===----------------------------------------------------------------------===//
5308
5309extern "C" {
5310CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005311 if (!clang_isDeclaration(cursor.kind))
5312 return CXLinkage_Invalid;
5313
Ted Kremenek16b42592010-03-03 06:36:57 +00005314 Decl *D = cxcursor::getCursorDecl(cursor);
5315 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5316 switch (ND->getLinkage()) {
5317 case NoLinkage: return CXLinkage_NoLinkage;
5318 case InternalLinkage: return CXLinkage_Internal;
5319 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5320 case ExternalLinkage: return CXLinkage_External;
5321 };
5322
5323 return CXLinkage_Invalid;
5324}
5325} // end: extern "C"
5326
5327//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005328// Operations for querying language of a cursor.
5329//===----------------------------------------------------------------------===//
5330
5331static CXLanguageKind getDeclLanguage(const Decl *D) {
5332 switch (D->getKind()) {
5333 default:
5334 break;
5335 case Decl::ImplicitParam:
5336 case Decl::ObjCAtDefsField:
5337 case Decl::ObjCCategory:
5338 case Decl::ObjCCategoryImpl:
5339 case Decl::ObjCClass:
5340 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005341 case Decl::ObjCForwardProtocol:
5342 case Decl::ObjCImplementation:
5343 case Decl::ObjCInterface:
5344 case Decl::ObjCIvar:
5345 case Decl::ObjCMethod:
5346 case Decl::ObjCProperty:
5347 case Decl::ObjCPropertyImpl:
5348 case Decl::ObjCProtocol:
5349 return CXLanguage_ObjC;
5350 case Decl::CXXConstructor:
5351 case Decl::CXXConversion:
5352 case Decl::CXXDestructor:
5353 case Decl::CXXMethod:
5354 case Decl::CXXRecord:
5355 case Decl::ClassTemplate:
5356 case Decl::ClassTemplatePartialSpecialization:
5357 case Decl::ClassTemplateSpecialization:
5358 case Decl::Friend:
5359 case Decl::FriendTemplate:
5360 case Decl::FunctionTemplate:
5361 case Decl::LinkageSpec:
5362 case Decl::Namespace:
5363 case Decl::NamespaceAlias:
5364 case Decl::NonTypeTemplateParm:
5365 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005366 case Decl::TemplateTemplateParm:
5367 case Decl::TemplateTypeParm:
5368 case Decl::UnresolvedUsingTypename:
5369 case Decl::UnresolvedUsingValue:
5370 case Decl::Using:
5371 case Decl::UsingDirective:
5372 case Decl::UsingShadow:
5373 return CXLanguage_CPlusPlus;
5374 }
5375
5376 return CXLanguage_C;
5377}
5378
5379extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005380
5381enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5382 if (clang_isDeclaration(cursor.kind))
5383 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005384 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005385 return CXAvailability_Available;
5386
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005387 switch (D->getAvailability()) {
5388 case AR_Available:
5389 case AR_NotYetIntroduced:
5390 return CXAvailability_Available;
5391
5392 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005393 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005394
5395 case AR_Unavailable:
5396 return CXAvailability_NotAvailable;
5397 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005398 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005399
Douglas Gregor58ddb602010-08-23 23:00:57 +00005400 return CXAvailability_Available;
5401}
5402
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005403CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5404 if (clang_isDeclaration(cursor.kind))
5405 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5406
5407 return CXLanguage_Invalid;
5408}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005409
5410 /// \brief If the given cursor is the "templated" declaration
5411 /// descibing a class or function template, return the class or
5412 /// function template.
5413static Decl *maybeGetTemplateCursor(Decl *D) {
5414 if (!D)
5415 return 0;
5416
5417 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5418 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5419 return FunTmpl;
5420
5421 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5422 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5423 return ClassTmpl;
5424
5425 return D;
5426}
5427
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005428CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5429 if (clang_isDeclaration(cursor.kind)) {
5430 if (Decl *D = getCursorDecl(cursor)) {
5431 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005432 if (!DC)
5433 return clang_getNullCursor();
5434
5435 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5436 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005437 }
5438 }
5439
5440 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5441 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005442 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005443 }
5444
5445 return clang_getNullCursor();
5446}
5447
5448CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5449 if (clang_isDeclaration(cursor.kind)) {
5450 if (Decl *D = getCursorDecl(cursor)) {
5451 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005452 if (!DC)
5453 return clang_getNullCursor();
5454
5455 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5456 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005457 }
5458 }
5459
5460 // FIXME: Note that we can't easily compute the lexical context of a
5461 // statement or expression, so we return nothing.
5462 return clang_getNullCursor();
5463}
5464
Douglas Gregor9f592342010-10-01 20:25:15 +00005465void clang_getOverriddenCursors(CXCursor cursor,
5466 CXCursor **overridden,
5467 unsigned *num_overridden) {
5468 if (overridden)
5469 *overridden = 0;
5470 if (num_overridden)
5471 *num_overridden = 0;
5472 if (!overridden || !num_overridden)
5473 return;
5474
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005475 SmallVector<CXCursor, 8> Overridden;
5476 cxcursor::getOverriddenCursors(cursor, Overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005477
Argyrios Kyrtzidisb11be042011-10-06 07:00:46 +00005478 *num_overridden = Overridden.size();
5479 *overridden = new CXCursor [Overridden.size()];
5480 std::copy(Overridden.begin(), Overridden.end(), *overridden);
Douglas Gregor9f592342010-10-01 20:25:15 +00005481}
5482
5483void clang_disposeOverriddenCursors(CXCursor *overridden) {
5484 delete [] overridden;
5485}
5486
Douglas Gregorecdcb882010-10-20 22:00:55 +00005487CXFile clang_getIncludedFile(CXCursor cursor) {
5488 if (cursor.kind != CXCursor_InclusionDirective)
5489 return 0;
5490
5491 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5492 return (void *)ID->getFile();
5493}
5494
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005495} // end: extern "C"
5496
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005497
5498//===----------------------------------------------------------------------===//
5499// C++ AST instrospection.
5500//===----------------------------------------------------------------------===//
5501
5502extern "C" {
5503unsigned clang_CXXMethod_isStatic(CXCursor C) {
5504 if (!clang_isDeclaration(C.kind))
5505 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005506
5507 CXXMethodDecl *Method = 0;
5508 Decl *D = cxcursor::getCursorDecl(C);
5509 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5510 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5511 else
5512 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5513 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005514}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005515
Douglas Gregor211924b2011-05-12 15:17:24 +00005516unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5517 if (!clang_isDeclaration(C.kind))
5518 return 0;
5519
5520 CXXMethodDecl *Method = 0;
5521 Decl *D = cxcursor::getCursorDecl(C);
5522 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5523 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5524 else
5525 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5526 return (Method && Method->isVirtual()) ? 1 : 0;
5527}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005528} // end: extern "C"
5529
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005530//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005531// Attribute introspection.
5532//===----------------------------------------------------------------------===//
5533
5534extern "C" {
5535CXType clang_getIBOutletCollectionType(CXCursor C) {
5536 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005537 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005538
5539 IBOutletCollectionAttr *A =
5540 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5541
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005542 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005543}
5544} // end: extern "C"
5545
5546//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005547// Inspecting memory usage.
5548//===----------------------------------------------------------------------===//
5549
Ted Kremenekf7870022011-04-20 16:41:07 +00005550typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005551
Ted Kremenekf7870022011-04-20 16:41:07 +00005552static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5553 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005554 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005555 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005556 entries.push_back(entry);
5557}
5558
5559extern "C" {
5560
Ted Kremenekf7870022011-04-20 16:41:07 +00005561const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005562 const char *str = "";
5563 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005564 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005565 str = "ASTContext: expressions, declarations, and types";
5566 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005567 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005568 str = "ASTContext: identifiers";
5569 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005570 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005571 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005572 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005573 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005574 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005575 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005576 case CXTUResourceUsage_SourceManagerContentCache:
5577 str = "SourceManager: content cache allocator";
5578 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005579 case CXTUResourceUsage_AST_SideTables:
5580 str = "ASTContext: side tables";
5581 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005582 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5583 str = "SourceManager: malloc'ed memory buffers";
5584 break;
5585 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5586 str = "SourceManager: mmap'ed memory buffers";
5587 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005588 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5589 str = "ExternalASTSource: malloc'ed memory buffers";
5590 break;
5591 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5592 str = "ExternalASTSource: mmap'ed memory buffers";
5593 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005594 case CXTUResourceUsage_Preprocessor:
5595 str = "Preprocessor: malloc'ed memory";
5596 break;
5597 case CXTUResourceUsage_PreprocessingRecord:
5598 str = "Preprocessor: PreprocessingRecord";
5599 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005600 case CXTUResourceUsage_SourceManager_DataStructures:
5601 str = "SourceManager: data structures and tables";
5602 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005603 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5604 str = "Preprocessor: header search tables";
5605 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005606 }
5607 return str;
5608}
5609
Ted Kremenekf7870022011-04-20 16:41:07 +00005610CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005611 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005612 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005613 return usage;
5614 }
5615
5616 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5617 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5618 ASTContext &astContext = astUnit->getASTContext();
5619
5620 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005621 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005622 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005623
5624 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005625 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005626 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5627
5628 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005629 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005630 (unsigned long) astContext.Selectors.getTotalMemory());
5631
Ted Kremenekba29bd22011-04-28 04:53:38 +00005632 // How much memory is used by ASTContext's side tables?
5633 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5634 (unsigned long) astContext.getSideTableAllocatedMemory());
5635
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005636 // How much memory is used for caching global code completion results?
5637 unsigned long completionBytes = 0;
5638 if (GlobalCodeCompletionAllocator *completionAllocator =
5639 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005640 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005641 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005642 createCXTUResourceUsageEntry(*entries,
5643 CXTUResourceUsage_GlobalCompletionResults,
5644 completionBytes);
5645
5646 // How much memory is being used by SourceManager's content cache?
5647 createCXTUResourceUsageEntry(*entries,
5648 CXTUResourceUsage_SourceManagerContentCache,
5649 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005650
5651 // How much memory is being used by the MemoryBuffer's in SourceManager?
5652 const SourceManager::MemoryBufferSizes &srcBufs =
5653 astUnit->getSourceManager().getMemoryBufferSizes();
5654
5655 createCXTUResourceUsageEntry(*entries,
5656 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5657 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005658 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005659 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5660 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005661 createCXTUResourceUsageEntry(*entries,
5662 CXTUResourceUsage_SourceManager_DataStructures,
5663 (unsigned long) astContext.getSourceManager()
5664 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005665
5666 // How much memory is being used by the ExternalASTSource?
5667 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5668 const ExternalASTSource::MemoryBufferSizes &sizes =
5669 esrc->getMemoryBufferSizes();
5670
5671 createCXTUResourceUsageEntry(*entries,
5672 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5673 (unsigned long) sizes.malloc_bytes);
5674 createCXTUResourceUsageEntry(*entries,
5675 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5676 (unsigned long) sizes.mmap_bytes);
5677 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005678
5679 // How much memory is being used by the Preprocessor?
5680 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005681 createCXTUResourceUsageEntry(*entries,
5682 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005683 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005684
5685 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5686 createCXTUResourceUsageEntry(*entries,
5687 CXTUResourceUsage_PreprocessingRecord,
5688 pRec->getTotalMemory());
5689 }
5690
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005691 createCXTUResourceUsageEntry(*entries,
5692 CXTUResourceUsage_Preprocessor_HeaderSearch,
5693 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005694
Ted Kremenekf7870022011-04-20 16:41:07 +00005695 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005696 (unsigned) entries->size(),
5697 entries->size() ? &(*entries)[0] : 0 };
5698 entries.take();
5699 return usage;
5700}
5701
Ted Kremenekf7870022011-04-20 16:41:07 +00005702void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005703 if (usage.data)
5704 delete (MemUsageEntries*) usage.data;
5705}
5706
5707} // end extern "C"
5708
Douglas Gregor6df78732011-05-05 20:27:22 +00005709void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5710 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5711 for (unsigned I = 0; I != Usage.numEntries; ++I)
5712 fprintf(stderr, " %s: %lu\n",
5713 clang_getTUResourceUsageName(Usage.entries[I].kind),
5714 Usage.entries[I].amount);
5715
5716 clang_disposeCXTUResourceUsage(Usage);
5717}
5718
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005719//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005720// Misc. utility functions.
5721//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005722
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005723/// Default to using an 8 MB stack size on "safety" threads.
5724static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005725
5726namespace clang {
5727
5728bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005729 void (*Fn)(void*), void *UserData,
5730 unsigned Size) {
5731 if (!Size)
5732 Size = GetSafetyThreadStackSize();
5733 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005734 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5735 return CRC.RunSafely(Fn, UserData);
5736}
5737
5738unsigned GetSafetyThreadStackSize() {
5739 return SafetyStackThreadSize;
5740}
5741
5742void SetSafetyThreadStackSize(unsigned Value) {
5743 SafetyStackThreadSize = Value;
5744}
5745
5746}
5747
Ted Kremenek04bb7162010-01-22 22:44:15 +00005748extern "C" {
5749
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005750CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005751 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005752}
5753
5754} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005755