blob: 30db13190c4f9ac8d9bde8db57bed39d45834480 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek0a90d322010-11-17 23:24:11 +000017#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000018#include "CXString.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000019#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000020#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000021#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022
Ted Kremenek04bb7162010-01-22 22:44:15 +000023#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000024
Steve Naroff50398192009-08-28 15:28:48 +000025#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000028#include "clang/Basic/Diagnostic.h"
29#include "clang/Frontend/ASTUnit.h"
30#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000032#include "clang/Lex/Lexer.h"
Douglas Gregordd3e5542011-05-04 00:14:37 +000033#include "clang/Lex/HeaderSearch.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000034#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000035#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000036#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000037#include "llvm/ADT/Optional.h"
Douglas Gregorf5251602011-03-08 17:10:18 +000038#include "llvm/ADT/StringSwitch.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000039#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000040#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000041#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000042#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000043#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000044#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000045#include "llvm/Support/Mutex.h"
46#include "llvm/Support/Program.h"
47#include "llvm/Support/Signals.h"
48#include "llvm/Support/Threading.h"
Ted Kremenek37f1ea02010-11-15 23:11:54 +000049#include "llvm/Support/Compiler.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000050
Steve Naroff50398192009-08-28 15:28:48 +000051using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000052using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000053using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000054
Ted Kremeneka60ed472010-11-16 08:15:36 +000055static CXTranslationUnit MakeCXTranslationUnit(ASTUnit *TU) {
56 if (!TU)
57 return 0;
58 CXTranslationUnit D = new CXTranslationUnitImpl();
59 D->TUData = TU;
60 D->StringPool = createCXStringPool();
61 return D;
62}
63
Douglas Gregor33e9abd2010-01-22 19:49:59 +000064/// \brief The result of comparing two source ranges.
65enum RangeComparisonResult {
66 /// \brief Either the ranges overlap or one of the ranges is invalid.
67 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000068
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 /// \brief The first range ends before the second range starts.
70 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000071
Douglas Gregor33e9abd2010-01-22 19:49:59 +000072 /// \brief The first range starts after the second range ends.
73 RangeAfter
74};
75
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000078static RangeComparisonResult RangeCompare(SourceManager &SM,
79 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000080 SourceRange R2) {
81 assert(R1.isValid() && "First range is invalid?");
82 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000083 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000084 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000085 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000086 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000087 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000088 return RangeAfter;
89 return RangeOverlap;
90}
91
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000092/// \brief Determine if a source location falls within, before, or after a
93/// a given source range.
94static RangeComparisonResult LocationCompare(SourceManager &SM,
95 SourceLocation L, SourceRange R) {
96 assert(R.isValid() && "First range is invalid?");
97 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000098 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000099 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000100 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
101 return RangeBefore;
102 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
103 return RangeAfter;
104 return RangeOverlap;
105}
106
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107/// \brief Translate a Clang source range into a CIndex source range.
108///
109/// Clang internally represents ranges where the end location points to the
110/// start of the token at the end. However, for external clients it is more
111/// useful to have a CXSourceRange be a proper half-open interval. This routine
112/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000113CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000114 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000116 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000117 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000118 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000119 if (EndLoc.isValid() && EndLoc.isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000120 EndLoc = SM.getExpansionRange(EndLoc).second;
Chris Lattner0a76aae2010-06-18 22:45:06 +0000121 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000122 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000123 EndLoc = EndLoc.getLocWithOffset(Length);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000124 }
125
126 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
127 R.getBegin().getRawEncoding(),
128 EndLoc.getRawEncoding() };
129 return Result;
130}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000131
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000132//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000133// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000134//===----------------------------------------------------------------------===//
135
Steve Naroff89922f82009-08-31 00:59:03 +0000136namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000137
138class VisitorJob {
139public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000140 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremeneke4979cc2010-11-13 00:58:18 +0000141 TypeLocVisitKind, OverloadExprPartsKind,
Ted Kremenek60608ec2010-11-17 00:50:47 +0000142 DeclRefExprPartsKind, LabelRefVisitKind,
Ted Kremenekf64d8032010-11-18 00:02:32 +0000143 ExplicitTemplateArgsVisitKind,
Douglas Gregorf3db29f2011-02-25 18:19:59 +0000144 NestedNameSpecifierLocVisitKind,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000145 DeclarationNameInfoVisitKind,
Douglas Gregor94d96292011-01-19 20:34:17 +0000146 MemberRefVisitKind, SizeOfPackExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000147protected:
Ted Kremenekf64d8032010-11-18 00:02:32 +0000148 void *data[3];
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000149 CXCursor parent;
150 Kind K;
Ted Kremenekf64d8032010-11-18 00:02:32 +0000151 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0, void *d3 = 0)
152 : parent(C), K(k) {
153 data[0] = d1;
154 data[1] = d2;
155 data[2] = d3;
156 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000157public:
158 Kind getKind() const { return K; }
159 const CXCursor &getParent() const { return parent; }
160 static bool classof(VisitorJob *VJ) { return true; }
161};
162
Chris Lattner5f9e2722011-07-23 10:55:15 +0000163typedef SmallVector<VisitorJob, 10> VisitorWorkList;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000164
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000166class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Ted Kremenekcdba6592010-11-18 00:42:18 +0000167 public TypeLocVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000168{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000169 /// \brief The translation unit we are traversing.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000170 CXTranslationUnit TU;
171 ASTUnit *AU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000172
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000174 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000175
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176 /// \brief The declaration that serves at the parent of any statement or
177 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000178 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000180 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000181 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000182
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000183 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000185
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000186 /// \brief Whether we should visit the preprocessing record entries last,
187 /// after visiting other declarations.
188 bool VisitPreprocessorLast;
189
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 /// \brief When valid, a source range to which the cursor should restrict
191 /// its search.
192 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000194 // FIXME: Eventually remove. This part of a hack to support proper
195 // iteration over all Decls contained lexically within an ObjC container.
196 DeclContext::decl_iterator *DI_current;
197 DeclContext::decl_iterator DE_current;
198
Ted Kremenekd1ded662010-11-15 23:31:32 +0000199 // Cache of pre-allocated worklists for data-recursion walk of Stmts.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000200 SmallVector<VisitorWorkList*, 5> WorkListFreeList;
201 SmallVector<VisitorWorkList*, 5> WorkListCache;
Ted Kremenekd1ded662010-11-15 23:31:32 +0000202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
206 /// \brief Determine whether this particular source range comes before, comes
207 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000209 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
211
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000212 class SetParentRAII {
213 CXCursor &Parent;
214 Decl *&StmtParent;
215 CXCursor OldParent;
216
217 public:
218 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
219 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
220 {
221 Parent = NewParent;
222 if (clang_isDeclaration(Parent.kind))
223 StmtParent = getCursorDecl(Parent);
224 }
225
226 ~SetParentRAII() {
227 Parent = OldParent;
228 if (clang_isDeclaration(Parent.kind))
229 StmtParent = getCursorDecl(Parent);
230 }
231 };
232
Steve Naroff89922f82009-08-31 00:59:03 +0000233public:
Ted Kremeneka60ed472010-11-16 08:15:36 +0000234 CursorVisitor(CXTranslationUnit TU, CXCursorVisitor Visitor,
235 CXClientData ClientData,
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000236 bool VisitPreprocessorLast,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 SourceRange RegionOfInterest = SourceRange())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000238 : TU(TU), AU(static_cast<ASTUnit*>(TU->TUData)),
239 Visitor(Visitor), ClientData(ClientData),
Douglas Gregor08e0bc12011-09-10 00:09:20 +0000240 VisitPreprocessorLast(VisitPreprocessorLast),
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000241 RegionOfInterest(RegionOfInterest), DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000242 {
243 Parent.kind = CXCursor_NoDeclFound;
244 Parent.data[0] = 0;
245 Parent.data[1] = 0;
246 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000248 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000249
Ted Kremenekd1ded662010-11-15 23:31:32 +0000250 ~CursorVisitor() {
251 // Free the pre-allocated worklists for data-recursion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000252 for (SmallVectorImpl<VisitorWorkList*>::iterator
Ted Kremenekd1ded662010-11-15 23:31:32 +0000253 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) {
254 delete *I;
255 }
256 }
257
Ted Kremeneka60ed472010-11-16 08:15:36 +0000258 ASTUnit *getASTUnit() const { return static_cast<ASTUnit*>(TU->TUData); }
259 CXTranslationUnit getTU() const { return TU; }
Ted Kremenekab979612010-11-11 08:05:23 +0000260
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000261 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000262
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000263 bool visitPreprocessedEntitiesInRegion();
264
265 template<typename InputIterator>
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000266 bool visitPreprocessedEntities(InputIterator First, InputIterator Last);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000267
Douglas Gregorb1373d02010-01-20 20:59:29 +0000268 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000269
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000270 // Declaration visitors
Richard Smith162e1c12011-04-15 14:24:37 +0000271 bool VisitTypeAliasDecl(TypeAliasDecl *D);
Ted Kremenek09dfa372010-02-18 05:46:33 +0000272 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000273 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000274 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000275 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000276 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000277 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
278 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000279 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000280 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000281 bool VisitClassTemplatePartialSpecializationDecl(
282 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000283 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000284 bool VisitEnumConstantDecl(EnumConstantDecl *D);
285 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
286 bool VisitFunctionDecl(FunctionDecl *ND);
287 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000288 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000289 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000290 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000291 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000292 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000293 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
294 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
295 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
296 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000297 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
299 bool VisitObjCImplDecl(ObjCImplDecl *D);
300 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
301 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000302 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
303 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
304 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregora4ffd852010-11-17 01:03:52 +0000305 bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000306 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000307 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000308 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000309 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000310 bool VisitUsingDecl(UsingDecl *D);
311 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
312 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000313
Douglas Gregor01829d32010-08-31 14:41:23 +0000314 // Name visitor
315 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000316 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregordc355712011-02-25 00:36:19 +0000317 bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Douglas Gregor01829d32010-08-31 14:41:23 +0000318
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000319 // Template visitors
320 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000321 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000322 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
323
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000324 // Type visitors
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000325#define ABSTRACT_TYPELOC(CLASS, PARENT)
326#define TYPELOC(CLASS, PARENT) \
327 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
328#include "clang/AST/TypeLocNodes.def"
329
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +0000332 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
333
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000334 // Data-recursive visitor functions.
335 bool IsInRegionOfInterest(CXCursor C);
336 bool RunVisitorWorkList(VisitorWorkList &WL);
337 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
Ted Kremenekcdba6592010-11-18 00:42:18 +0000338 LLVM_ATTRIBUTE_NOINLINE bool Visit(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000339};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000340
Ted Kremenekab188932010-01-05 19:32:54 +0000341} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000342
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000343static SourceRange getRawCursorExtent(CXCursor C);
Douglas Gregor66537982010-11-17 17:14:07 +0000344static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
345
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000346
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000347RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000348 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000349}
350
Douglas Gregorb1373d02010-01-20 20:59:29 +0000351/// \brief Visit the given cursor and, if requested by the visitor,
352/// its children.
353///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000354/// \param Cursor the cursor to visit.
355///
356/// \param CheckRegionOfInterest if true, then the caller already checked that
357/// this cursor is within the region of interest.
358///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000359/// \returns true if the visitation should be aborted, false if it
360/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000362 if (clang_isInvalid(Cursor.kind))
363 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000364
Douglas Gregorb1373d02010-01-20 20:59:29 +0000365 if (clang_isDeclaration(Cursor.kind)) {
366 Decl *D = getCursorDecl(Cursor);
367 assert(D && "Invalid declaration cursor");
Douglas Gregorb1373d02010-01-20 20:59:29 +0000368 if (D->isImplicit())
369 return false;
370 }
371
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372 // If we have a range of interest, and this cursor doesn't intersect with it,
373 // we're done.
374 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000375 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000376 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000377 return false;
378 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000379
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380 switch (Visitor(Cursor, Parent, ClientData)) {
381 case CXChildVisit_Break:
382 return true;
383
384 case CXChildVisit_Continue:
385 return false;
386
387 case CXChildVisit_Recurse:
388 return VisitChildren(Cursor);
389 }
390
Douglas Gregorfd643772010-01-25 16:45:46 +0000391 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392}
393
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000394bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
Douglas Gregor788f5a12010-03-20 00:41:21 +0000395 PreprocessingRecord &PPRec
Ted Kremeneka60ed472010-11-16 08:15:36 +0000396 = *AU->getPreprocessor().getPreprocessingRecord();
Douglas Gregor788f5a12010-03-20 00:41:21 +0000397
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000398 if (RegionOfInterest.isValid()) {
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000399 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000400 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +0000401 Entities = PPRec.getPreprocessedEntitiesInRange(MappedRange);
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000402 return visitPreprocessedEntities(Entities.first, Entities.second);
403 }
404
Douglas Gregor788f5a12010-03-20 00:41:21 +0000405 bool OnlyLocalDecls
Douglas Gregor32038bb2010-12-21 19:07:48 +0000406 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
407
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000408 if (OnlyLocalDecls)
409 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000410
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000411 return visitPreprocessedEntities(PPRec.begin(), PPRec.end());
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000412}
413
414template<typename InputIterator>
415bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
416 InputIterator Last) {
417 for (; First != Last; ++First) {
418 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*First)) {
419 if (Visit(MakeMacroExpansionCursor(ME, TU)))
420 return true;
421
422 continue;
423 }
424
425 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*First)) {
426 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
427 return true;
428
429 continue;
430 }
431
432 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*First)) {
433 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
434 return true;
435
436 continue;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000437 }
438 }
439
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000440 return false;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000441}
442
Douglas Gregorb1373d02010-01-20 20:59:29 +0000443/// \brief Visit the children of the given cursor.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000444///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445/// \returns true if the visitation should be aborted, false if it
446/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000447bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregorc314aa42011-03-02 19:17:03 +0000448 if (clang_isReference(Cursor.kind) &&
449 Cursor.kind != CXCursor_CXXBaseSpecifier) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000450 // By definition, references have no children.
451 return false;
452 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000453
454 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000456 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458 if (clang_isDeclaration(Cursor.kind)) {
459 Decl *D = getCursorDecl(Cursor);
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000460 if (!D)
461 return false;
462
Ted Kremenek539311e2010-02-18 18:47:01 +0000463 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000464 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000465
Douglas Gregor06d9b1a2011-04-14 21:41:34 +0000466 if (clang_isStatement(Cursor.kind)) {
467 if (Stmt *S = getCursorStmt(Cursor))
468 return Visit(S);
469
470 return false;
471 }
472
473 if (clang_isExpression(Cursor.kind)) {
474 if (Expr *E = getCursorExpr(Cursor))
475 return Visit(E);
476
477 return false;
478 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480 if (clang_isTranslationUnit(Cursor.kind)) {
Ted Kremeneka60ed472010-11-16 08:15:36 +0000481 CXTranslationUnit tu = getCursorTU(Cursor);
482 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000483
484 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
485 for (unsigned I = 0; I != 2; ++I) {
486 if (VisitOrder[I]) {
487 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
488 RegionOfInterest.isInvalid()) {
489 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
490 TLEnd = CXXUnit->top_level_end();
491 TL != TLEnd; ++TL) {
492 if (Visit(MakeCXCursor(*TL, tu), true))
493 return true;
494 }
495 } else if (VisitDeclContext(
496 CXXUnit->getASTContext().getTranslationUnitDecl()))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000497 return true;
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000498 continue;
Douglas Gregor7b691f332010-01-20 21:13:59 +0000499 }
Bob Wilson3178cb62010-03-19 03:57:57 +0000500
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000501 // Walk the preprocessing record.
Douglas Gregor4c30bb12011-07-21 00:47:40 +0000502 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
503 visitPreprocessedEntitiesInRegion();
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 }
Douglas Gregor04a9eb32011-03-16 23:23:30 +0000505
Douglas Gregor7b691f332010-01-20 21:13:59 +0000506 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000507 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000508
Douglas Gregorc314aa42011-03-02 19:17:03 +0000509 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
510 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
511 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
512 return Visit(BaseTSInfo->getTypeLoc());
513 }
514 }
515 }
Argyrios Kyrtzidis221d5a52011-09-13 18:49:56 +0000516
517 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
518 IBOutletCollectionAttr *A =
519 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
520 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
521 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
522 A->getInterfaceLoc(), TU));
523 }
524
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 return false;
527}
528
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000529bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
Douglas Gregor13c8ccb2011-04-22 23:49:24 +0000530 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
531 if (Visit(TSInfo->getTypeLoc()))
532 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533
Ted Kremenek664cffd2010-07-22 11:30:19 +0000534 if (Stmt *Body = B->getBody())
535 return Visit(MakeCXCursor(Body, StmtParent, TU));
536
537 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000538}
539
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000540llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
541 if (RegionOfInterest.isValid()) {
Douglas Gregor66537982010-11-17 17:14:07 +0000542 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000543 if (Range.isInvalid())
544 return llvm::Optional<bool>();
Douglas Gregor66537982010-11-17 17:14:07 +0000545
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000546 switch (CompareRegionOfInterest(Range)) {
547 case RangeBefore:
548 // This declaration comes before the region of interest; skip it.
549 return llvm::Optional<bool>();
550
551 case RangeAfter:
552 // This declaration comes after the region of interest; we're done.
553 return false;
554
555 case RangeOverlap:
556 // This declaration overlaps the region of interest; visit it.
557 break;
558 }
559 }
560 return true;
561}
562
563bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
564 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
565
566 // FIXME: Eventually remove. This part of a hack to support proper
567 // iteration over all Decls contained lexically within an ObjC container.
568 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
569 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
570
571 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000572 Decl *D = *I;
573 if (D->getLexicalDeclContext() != DC)
574 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000575 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000576 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
577 if (!V.hasValue())
578 continue;
579 if (!V.getValue())
580 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000581 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582 return true;
583 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000585}
586
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000587bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
588 llvm_unreachable("Translation units are visited directly by Visit()");
589 return false;
590}
591
Richard Smith162e1c12011-04-15 14:24:37 +0000592bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
593 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
594 return Visit(TSInfo->getTypeLoc());
595
596 return false;
597}
598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
600 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
601 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000602
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000603 return false;
604}
605
606bool CursorVisitor::VisitTagDecl(TagDecl *D) {
607 return VisitDeclContext(D);
608}
609
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000610bool CursorVisitor::VisitClassTemplateSpecializationDecl(
611 ClassTemplateSpecializationDecl *D) {
612 bool ShouldVisitBody = false;
613 switch (D->getSpecializationKind()) {
614 case TSK_Undeclared:
615 case TSK_ImplicitInstantiation:
616 // Nothing to visit
617 return false;
618
619 case TSK_ExplicitInstantiationDeclaration:
620 case TSK_ExplicitInstantiationDefinition:
621 break;
622
623 case TSK_ExplicitSpecialization:
624 ShouldVisitBody = true;
625 break;
626 }
627
628 // Visit the template arguments used in the specialization.
629 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
630 TypeLoc TL = SpecType->getTypeLoc();
631 if (TemplateSpecializationTypeLoc *TSTLoc
632 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
633 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
634 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
635 return true;
636 }
637 }
638
639 if (ShouldVisitBody && VisitCXXRecordDecl(D))
640 return true;
641
642 return false;
643}
644
Douglas Gregor74dbe642010-08-31 19:31:58 +0000645bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
646 ClassTemplatePartialSpecializationDecl *D) {
647 // FIXME: Visit the "outer" template parameter lists on the TagDecl
648 // before visiting these template parameters.
649 if (VisitTemplateParameters(D->getTemplateParameters()))
650 return true;
651
652 // Visit the partial specialization arguments.
653 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
654 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
655 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
656 return true;
657
658 return VisitCXXRecordDecl(D);
659}
660
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000661bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000662 // Visit the default argument.
663 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
664 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
665 if (Visit(DefArg->getTypeLoc()))
666 return true;
667
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000668 return false;
669}
670
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000671bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
672 if (Expr *Init = D->getInitExpr())
673 return Visit(MakeCXCursor(Init, StmtParent, TU));
674 return false;
675}
676
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000677bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
678 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
679 if (Visit(TSInfo->getTypeLoc()))
680 return true;
681
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000682 // Visit the nested-name-specifier, if present.
683 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
684 if (VisitNestedNameSpecifierLoc(QualifierLoc))
685 return true;
686
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000687 return false;
688}
689
Douglas Gregora67e03f2010-09-09 21:42:20 +0000690/// \brief Compare two base or member initializers based on their source order.
Sean Huntcbb67482011-01-08 20:30:50 +0000691static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
692 CXXCtorInitializer const * const *X
693 = static_cast<CXXCtorInitializer const * const *>(Xp);
694 CXXCtorInitializer const * const *Y
695 = static_cast<CXXCtorInitializer const * const *>(Yp);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000696
697 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
698 return -1;
699 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
700 return 1;
701 else
702 return 0;
703}
704
Douglas Gregorb1373d02010-01-20 20:59:29 +0000705bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000706 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
707 // Visit the function declaration's syntactic components in the order
708 // written. This requires a bit of work.
Abramo Bagnara723df242010-12-14 22:11:44 +0000709 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor01829d32010-08-31 14:41:23 +0000710 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
711
712 // If we have a function declared directly (without the use of a typedef),
713 // visit just the return type. Otherwise, just visit the function's type
714 // now.
715 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
716 (!FTL && Visit(TL)))
717 return true;
718
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000719 // Visit the nested-name-specifier, if present.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000720 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
721 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000722 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000723
724 // Visit the declaration name.
725 if (VisitDeclarationNameInfo(ND->getNameInfo()))
726 return true;
727
728 // FIXME: Visit explicitly-specified template arguments!
729
730 // Visit the function parameters, if we have a function type.
731 if (FTL && VisitFunctionTypeLoc(*FTL, true))
732 return true;
733
734 // FIXME: Attributes?
735 }
736
Sean Hunt10620eb2011-05-06 20:44:56 +0000737 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
Douglas Gregora67e03f2010-09-09 21:42:20 +0000738 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
739 // Find the initializers that were written in the source.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000740 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Douglas Gregora67e03f2010-09-09 21:42:20 +0000741 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
742 IEnd = Constructor->init_end();
743 I != IEnd; ++I) {
744 if (!(*I)->isWritten())
745 continue;
746
747 WrittenInits.push_back(*I);
748 }
749
750 // Sort the initializers in source order
751 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
Sean Huntcbb67482011-01-08 20:30:50 +0000752 &CompareCXXCtorInitializers);
Douglas Gregora67e03f2010-09-09 21:42:20 +0000753
754 // Visit the initializers in source order
755 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000756 CXXCtorInitializer *Init = WrittenInits[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000757 if (Init->isAnyMemberInitializer()) {
758 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
Douglas Gregora67e03f2010-09-09 21:42:20 +0000759 Init->getMemberLocation(), TU)))
760 return true;
761 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
762 if (Visit(BaseInfo->getTypeLoc()))
763 return true;
764 }
765
766 // Visit the initializer value.
767 if (Expr *Initializer = Init->getInit())
768 if (Visit(MakeCXCursor(Initializer, ND, TU)))
769 return true;
770 }
771 }
772
773 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
774 return true;
775 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregorb1373d02010-01-20 20:59:29 +0000777 return false;
778}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000779
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000780bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
781 if (VisitDeclaratorDecl(D))
782 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000784 if (Expr *BitWidth = D->getBitWidth())
785 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 return false;
788}
789
790bool CursorVisitor::VisitVarDecl(VarDecl *D) {
791 if (VisitDeclaratorDecl(D))
792 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000793
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000794 if (Expr *Init = D->getInit())
795 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 return false;
798}
799
Douglas Gregor84b51d72010-09-01 20:16:53 +0000800bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
801 if (VisitDeclaratorDecl(D))
802 return true;
803
804 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
805 if (Expr *DefArg = D->getDefaultArgument())
806 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
807
808 return false;
809}
810
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000811bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
812 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
813 // before visiting these template parameters.
814 if (VisitTemplateParameters(D->getTemplateParameters()))
815 return true;
816
817 return VisitFunctionDecl(D->getTemplatedDecl());
818}
819
Douglas Gregor39d6f072010-08-31 19:02:00 +0000820bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
821 // FIXME: Visit the "outer" template parameter lists on the TagDecl
822 // before visiting these template parameters.
823 if (VisitTemplateParameters(D->getTemplateParameters()))
824 return true;
825
826 return VisitCXXRecordDecl(D->getTemplatedDecl());
827}
828
Douglas Gregor84b51d72010-09-01 20:16:53 +0000829bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
830 if (VisitTemplateParameters(D->getTemplateParameters()))
831 return true;
832
833 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
834 VisitTemplateArgumentLoc(D->getDefaultArgument()))
835 return true;
836
837 return false;
838}
839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000841 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
842 if (Visit(TSInfo->getTypeLoc()))
843 return true;
844
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000846 PEnd = ND->param_end();
847 P != PEnd; ++P) {
848 if (Visit(MakeCXCursor(*P, TU)))
849 return true;
850 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000851
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000852 if (ND->isThisDeclarationADefinition() &&
853 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
854 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000855
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856 return false;
857}
858
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000859namespace {
860 struct ContainerDeclsSort {
861 SourceManager &SM;
862 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
863 bool operator()(Decl *A, Decl *B) {
864 SourceLocation L_A = A->getLocStart();
865 SourceLocation L_B = B->getLocStart();
866 assert(L_A.isValid() && L_B.isValid());
867 return SM.isBeforeInTranslationUnit(L_A, L_B);
868 }
869 };
870}
871
Douglas Gregora59e3902010-01-21 23:27:09 +0000872bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000873 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
874 // an @implementation can lexically contain Decls that are not properly
875 // nested in the AST. When we identify such cases, we need to retrofit
876 // this nesting here.
877 if (!DI_current)
878 return VisitDeclContext(D);
879
880 // Scan the Decls that immediately come after the container
881 // in the current DeclContext. If any fall within the
882 // container's lexical region, stash them into a vector
883 // for later processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000884 SmallVector<Decl *, 24> DeclsInContainer;
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000885 SourceLocation EndLoc = D->getSourceRange().getEnd();
Ted Kremeneka60ed472010-11-16 08:15:36 +0000886 SourceManager &SM = AU->getSourceManager();
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000887 if (EndLoc.isValid()) {
888 DeclContext::decl_iterator next = *DI_current;
889 while (++next != DE_current) {
890 Decl *D_next = *next;
891 if (!D_next)
892 break;
893 SourceLocation L = D_next->getLocStart();
894 if (!L.isValid())
895 break;
896 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
897 *DI_current = next;
898 DeclsInContainer.push_back(D_next);
899 continue;
900 }
901 break;
902 }
903 }
904
905 // The common case.
906 if (DeclsInContainer.empty())
907 return VisitDeclContext(D);
908
909 // Get all the Decls in the DeclContext, and sort them with the
910 // additional ones we've collected. Then visit them.
911 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
912 I!=E; ++I) {
913 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000914 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
915 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000916 continue;
917 DeclsInContainer.push_back(subDecl);
918 }
919
920 // Now sort the Decls so that they appear in lexical order.
921 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
922 ContainerDeclsSort(SM));
923
924 // Now visit the decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000925 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000926 E = DeclsInContainer.end(); I != E; ++I) {
927 CXCursor Cursor = MakeCXCursor(*I, TU);
928 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
929 if (!V.hasValue())
930 continue;
931 if (!V.getValue())
932 return false;
933 if (Visit(Cursor, true))
934 return true;
935 }
936 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000937}
938
Douglas Gregorb1373d02010-01-20 20:59:29 +0000939bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000940 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
941 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000942 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000943
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000944 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
945 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
946 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000947 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000948 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregora59e3902010-01-21 23:27:09 +0000950 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000951}
952
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000953bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
954 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
955 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
956 E = PID->protocol_end(); I != E; ++I, ++PL)
957 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
958 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000959
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000960 return VisitObjCContainerDecl(PID);
961}
962
Ted Kremenek23173d72010-05-18 21:09:07 +0000963bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000964 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000965 return true;
966
Ted Kremenek23173d72010-05-18 21:09:07 +0000967 // FIXME: This implements a workaround with @property declarations also being
968 // installed in the DeclContext for the @interface. Eventually this code
969 // should be removed.
970 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
971 if (!CDecl || !CDecl->IsClassExtension())
972 return false;
973
974 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
975 if (!ID)
976 return false;
977
978 IdentifierInfo *PropertyId = PD->getIdentifier();
979 ObjCPropertyDecl *prevDecl =
980 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
981
982 if (!prevDecl)
983 return false;
984
985 // Visit synthesized methods since they will be skipped when visiting
986 // the @interface.
987 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000988 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000989 if (Visit(MakeCXCursor(MD, TU)))
990 return true;
991
992 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000993 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000994 if (Visit(MakeCXCursor(MD, TU)))
995 return true;
996
997 return false;
998}
999
Douglas Gregorb1373d02010-01-20 20:59:29 +00001000bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001001 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001002 if (D->getSuperClass() &&
1003 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001004 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001005 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001006 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001007
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001008 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1009 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1010 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001011 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001012 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013
Douglas Gregora59e3902010-01-21 23:27:09 +00001014 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001015}
1016
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001017bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1018 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001019}
1020
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001021bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001022 // 'ID' could be null when dealing with invalid code.
1023 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1024 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1025 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001027 return VisitObjCImplDecl(D);
1028}
1029
1030bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1031#if 0
1032 // Issue callbacks for super class.
1033 // FIXME: No source location information!
1034 if (D->getSuperClass() &&
1035 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001036 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001037 TU)))
1038 return true;
1039#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001040
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001041 return VisitObjCImplDecl(D);
1042}
1043
1044bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1045 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1046 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1047 E = D->protocol_end();
1048 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001049 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001050 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001051
1052 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001053}
1054
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001055bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00001056 if (Visit(MakeCursorObjCClassRef(D->getForwardInterfaceDecl(),
1057 D->getForwardDecl()->getLocation(), TU)))
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001058 return true;
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001059 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001060}
1061
Douglas Gregora4ffd852010-11-17 01:03:52 +00001062bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1063 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1064 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1065
1066 return false;
1067}
1068
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001069bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1070 return VisitDeclContext(D);
1071}
1072
Douglas Gregor69319002010-08-31 23:48:11 +00001073bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001074 // Visit nested-name-specifier.
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00001075 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1076 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001077 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001078
1079 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1080 D->getTargetNameLoc(), TU));
1081}
1082
Douglas Gregor7e242562010-09-01 19:52:22 +00001083bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001084 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001085 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1086 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001087 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001088 }
Douglas Gregor7e242562010-09-01 19:52:22 +00001089
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001090 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1091 return true;
1092
Douglas Gregor7e242562010-09-01 19:52:22 +00001093 return VisitDeclarationNameInfo(D->getNameInfo());
1094}
1095
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001096bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001097 // Visit nested-name-specifier.
Douglas Gregordb992412011-02-25 16:33:46 +00001098 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1099 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001100 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001101
1102 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1103 D->getIdentLocation(), TU));
1104}
1105
Douglas Gregor7e242562010-09-01 19:52:22 +00001106bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001107 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001108 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1109 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 return true;
Douglas Gregordc355712011-02-25 00:36:19 +00001111 }
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001112
Douglas Gregor7e242562010-09-01 19:52:22 +00001113 return VisitDeclarationNameInfo(D->getNameInfo());
1114}
1115
1116bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1117 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001118 // Visit nested-name-specifier.
Douglas Gregordc355712011-02-25 00:36:19 +00001119 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1120 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001121 return true;
1122
Douglas Gregor7e242562010-09-01 19:52:22 +00001123 return false;
1124}
1125
Douglas Gregor01829d32010-08-31 14:41:23 +00001126bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1127 switch (Name.getName().getNameKind()) {
1128 case clang::DeclarationName::Identifier:
1129 case clang::DeclarationName::CXXLiteralOperatorName:
1130 case clang::DeclarationName::CXXOperatorName:
1131 case clang::DeclarationName::CXXUsingDirective:
1132 return false;
1133
1134 case clang::DeclarationName::CXXConstructorName:
1135 case clang::DeclarationName::CXXDestructorName:
1136 case clang::DeclarationName::CXXConversionFunctionName:
1137 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1138 return Visit(TSInfo->getTypeLoc());
1139 return false;
1140
1141 case clang::DeclarationName::ObjCZeroArgSelector:
1142 case clang::DeclarationName::ObjCOneArgSelector:
1143 case clang::DeclarationName::ObjCMultiArgSelector:
1144 // FIXME: Per-identifier location info?
1145 return false;
1146 }
1147
1148 return false;
1149}
1150
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001151bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1152 SourceRange Range) {
1153 // FIXME: This whole routine is a hack to work around the lack of proper
1154 // source information in nested-name-specifiers (PR5791). Since we do have
1155 // a beginning source location, we can visit the first component of the
1156 // nested-name-specifier, if it's a single-token component.
1157 if (!NNS)
1158 return false;
1159
1160 // Get the first component in the nested-name-specifier.
1161 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1162 NNS = Prefix;
1163
1164 switch (NNS->getKind()) {
1165 case NestedNameSpecifier::Namespace:
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001166 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1167 TU));
1168
Douglas Gregor14aba762011-02-24 02:36:08 +00001169 case NestedNameSpecifier::NamespaceAlias:
1170 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1171 Range.getBegin(), TU));
1172
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001173 case NestedNameSpecifier::TypeSpec: {
1174 // If the type has a form where we know that the beginning of the source
1175 // range matches up with a reference cursor. Visit the appropriate reference
1176 // cursor.
John McCallf4c73712011-01-19 06:33:43 +00001177 const Type *T = NNS->getAsType();
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001178 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1179 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1180 if (const TagType *Tag = dyn_cast<TagType>(T))
1181 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1182 if (const TemplateSpecializationType *TST
1183 = dyn_cast<TemplateSpecializationType>(T))
1184 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1185 break;
1186 }
1187
1188 case NestedNameSpecifier::TypeSpecWithTemplate:
1189 case NestedNameSpecifier::Global:
1190 case NestedNameSpecifier::Identifier:
1191 break;
1192 }
1193
1194 return false;
1195}
1196
Douglas Gregordc355712011-02-25 00:36:19 +00001197bool
1198CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001199 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
Douglas Gregordc355712011-02-25 00:36:19 +00001200 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1201 Qualifiers.push_back(Qualifier);
1202
1203 while (!Qualifiers.empty()) {
1204 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1205 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1206 switch (NNS->getKind()) {
1207 case NestedNameSpecifier::Namespace:
1208 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001209 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001210 TU)))
1211 return true;
1212
1213 break;
1214
1215 case NestedNameSpecifier::NamespaceAlias:
1216 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001217 Q.getLocalBeginLoc(),
Douglas Gregordc355712011-02-25 00:36:19 +00001218 TU)))
1219 return true;
1220
1221 break;
1222
1223 case NestedNameSpecifier::TypeSpec:
1224 case NestedNameSpecifier::TypeSpecWithTemplate:
1225 if (Visit(Q.getTypeLoc()))
1226 return true;
1227
1228 break;
1229
1230 case NestedNameSpecifier::Global:
1231 case NestedNameSpecifier::Identifier:
1232 break;
1233 }
1234 }
1235
1236 return false;
1237}
1238
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001239bool CursorVisitor::VisitTemplateParameters(
1240 const TemplateParameterList *Params) {
1241 if (!Params)
1242 return false;
1243
1244 for (TemplateParameterList::const_iterator P = Params->begin(),
1245 PEnd = Params->end();
1246 P != PEnd; ++P) {
1247 if (Visit(MakeCXCursor(*P, TU)))
1248 return true;
1249 }
1250
1251 return false;
1252}
1253
Douglas Gregor0b36e612010-08-31 20:37:03 +00001254bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1255 switch (Name.getKind()) {
1256 case TemplateName::Template:
1257 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1258
1259 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001260 // Visit the overloaded template set.
1261 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1262 return true;
1263
Douglas Gregor0b36e612010-08-31 20:37:03 +00001264 return false;
1265
1266 case TemplateName::DependentTemplate:
1267 // FIXME: Visit nested-name-specifier.
1268 return false;
1269
1270 case TemplateName::QualifiedTemplate:
1271 // FIXME: Visit nested-name-specifier.
1272 return Visit(MakeCursorTemplateRef(
1273 Name.getAsQualifiedTemplateName()->getDecl(),
1274 Loc, TU));
John McCall14606042011-06-30 08:33:18 +00001275
1276 case TemplateName::SubstTemplateTemplateParm:
1277 return Visit(MakeCursorTemplateRef(
1278 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1279 Loc, TU));
Douglas Gregor1aee05d2011-01-15 06:45:20 +00001280
1281 case TemplateName::SubstTemplateTemplateParmPack:
1282 return Visit(MakeCursorTemplateRef(
1283 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1284 Loc, TU));
Douglas Gregor0b36e612010-08-31 20:37:03 +00001285 }
1286
1287 return false;
1288}
1289
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001290bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1291 switch (TAL.getArgument().getKind()) {
1292 case TemplateArgument::Null:
1293 case TemplateArgument::Integral:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001294 case TemplateArgument::Pack:
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001295 return false;
1296
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001297 case TemplateArgument::Type:
1298 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1299 return Visit(TSInfo->getTypeLoc());
1300 return false;
1301
1302 case TemplateArgument::Declaration:
1303 if (Expr *E = TAL.getSourceDeclExpression())
1304 return Visit(MakeCXCursor(E, StmtParent, TU));
1305 return false;
1306
1307 case TemplateArgument::Expression:
1308 if (Expr *E = TAL.getSourceExpression())
1309 return Visit(MakeCXCursor(E, StmtParent, TU));
1310 return false;
1311
1312 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001313 case TemplateArgument::TemplateExpansion:
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001314 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1315 return true;
1316
Douglas Gregora7fc9012011-01-05 18:58:31 +00001317 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
Douglas Gregor0b36e612010-08-31 20:37:03 +00001318 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001319 }
1320
1321 return false;
1322}
1323
Ted Kremeneka0536d82010-05-07 01:04:29 +00001324bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1325 return VisitDeclContext(D);
1326}
1327
Douglas Gregor01829d32010-08-31 14:41:23 +00001328bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1329 return Visit(TL.getUnqualifiedLoc());
1330}
1331
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001332bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00001333 ASTContext &Context = AU->getASTContext();
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334
1335 // Some builtin types (such as Objective-C's "id", "sel", and
1336 // "Class") have associated declarations. Create cursors for those.
1337 QualType VisitType;
1338 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001339 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001341 case BuiltinType::Char_U:
1342 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001343 case BuiltinType::Char16:
1344 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001345 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001346 case BuiltinType::UInt:
1347 case BuiltinType::ULong:
1348 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001349 case BuiltinType::UInt128:
1350 case BuiltinType::Char_S:
1351 case BuiltinType::SChar:
Chris Lattner3f59c972010-12-25 23:25:43 +00001352 case BuiltinType::WChar_U:
1353 case BuiltinType::WChar_S:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001354 case BuiltinType::Short:
1355 case BuiltinType::Int:
1356 case BuiltinType::Long:
1357 case BuiltinType::LongLong:
1358 case BuiltinType::Int128:
1359 case BuiltinType::Float:
1360 case BuiltinType::Double:
1361 case BuiltinType::LongDouble:
1362 case BuiltinType::NullPtr:
1363 case BuiltinType::Overload:
John McCall864c0412011-04-26 20:42:42 +00001364 case BuiltinType::BoundMember:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001365 case BuiltinType::Dependent:
John McCall1de4d4e2011-04-07 08:22:57 +00001366 case BuiltinType::UnknownAny:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001368
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001369 case BuiltinType::ObjCId:
1370 VisitType = Context.getObjCIdType();
1371 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001372
1373 case BuiltinType::ObjCClass:
1374 VisitType = Context.getObjCClassType();
1375 break;
1376
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001377 case BuiltinType::ObjCSel:
1378 VisitType = Context.getObjCSelType();
1379 break;
1380 }
1381
1382 if (!VisitType.isNull()) {
1383 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001385 TU));
1386 }
1387
1388 return false;
1389}
1390
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001391bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith162e1c12011-04-15 14:24:37 +00001392 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001393}
1394
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001395bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1396 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1397}
1398
1399bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
Argyrios Kyrtzidis6f155de2011-08-25 22:24:47 +00001400 if (TL.isDefinition())
1401 return Visit(MakeCXCursor(TL.getDecl(), TU));
1402
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001403 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1404}
1405
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001406bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Chandler Carruth960d13d2011-05-01 09:53:37 +00001407 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001408}
1409
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001410bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1411 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1412 return true;
1413
John McCallc12c5bb2010-05-15 11:32:37 +00001414 return false;
1415}
1416
1417bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1418 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1419 return true;
1420
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001421 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1422 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1423 TU)))
1424 return true;
1425 }
1426
1427 return false;
1428}
1429
1430bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001431 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001432}
1433
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001434bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1435 return Visit(TL.getInnerLoc());
1436}
1437
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001438bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1439 return Visit(TL.getPointeeLoc());
1440}
1441
1442bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1443 return Visit(TL.getPointeeLoc());
1444}
1445
1446bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1447 return Visit(TL.getPointeeLoc());
1448}
1449
1450bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001451 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001452}
1453
1454bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001455 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001456}
1457
Argyrios Kyrtzidis3422fbc2011-08-15 18:44:43 +00001458bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1459 return Visit(TL.getModifiedLoc());
1460}
1461
Douglas Gregor01829d32010-08-31 14:41:23 +00001462bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1463 bool SkipResultType) {
1464 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001465 return true;
1466
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001467 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001468 if (Decl *D = TL.getArg(I))
1469 if (Visit(MakeCXCursor(D, TU)))
1470 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001471
1472 return false;
1473}
1474
1475bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1476 if (Visit(TL.getElementLoc()))
1477 return true;
1478
1479 if (Expr *Size = TL.getSizeExpr())
1480 return Visit(MakeCXCursor(Size, StmtParent, TU));
1481
1482 return false;
1483}
1484
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001485bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1486 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001487 // Visit the template name.
1488 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1489 TL.getTemplateNameLoc()))
1490 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001491
1492 // Visit the template arguments.
1493 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1494 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1495 return true;
1496
1497 return false;
1498}
1499
Douglas Gregor2332c112010-01-21 20:48:56 +00001500bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1501 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1502}
1503
1504bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1505 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1506 return Visit(TSInfo->getTypeLoc());
1507
1508 return false;
1509}
1510
Sean Huntca63c202011-05-24 22:41:36 +00001511bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1512 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1513 return Visit(TSInfo->getTypeLoc());
1514
1515 return false;
1516}
1517
Douglas Gregor2494dd02011-03-01 01:34:45 +00001518bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1519 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1520 return true;
1521
1522 return false;
1523}
1524
Douglas Gregor94fdffa2011-03-01 20:11:18 +00001525bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1526 DependentTemplateSpecializationTypeLoc TL) {
1527 // Visit the nested-name-specifier, if there is one.
1528 if (TL.getQualifierLoc() &&
1529 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1530 return true;
1531
1532 // Visit the template arguments.
1533 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1534 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1535 return true;
1536
1537 return false;
1538}
1539
Douglas Gregor9e876872011-03-01 18:12:44 +00001540bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1541 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1542 return true;
1543
1544 return Visit(TL.getNamedTypeLoc());
1545}
1546
Douglas Gregor7536dd52010-12-20 02:24:11 +00001547bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1548 return Visit(TL.getPatternLoc());
1549}
1550
Argyrios Kyrtzidis427964e2011-08-15 22:40:24 +00001551bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1552 if (Expr *E = TL.getUnderlyingExpr())
1553 return Visit(MakeCXCursor(E, StmtParent, TU));
1554
1555 return false;
1556}
1557
1558bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1559 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1560}
1561
1562#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1563bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1564 return Visit##PARENT##Loc(TL); \
1565}
1566
1567DEFAULT_TYPELOC_IMPL(Complex, Type)
1568DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1569DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1570DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1571DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1572DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1573DEFAULT_TYPELOC_IMPL(Vector, Type)
1574DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1575DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1576DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1577DEFAULT_TYPELOC_IMPL(Record, TagType)
1578DEFAULT_TYPELOC_IMPL(Enum, TagType)
1579DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1580DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1581DEFAULT_TYPELOC_IMPL(Auto, Type)
1582
Ted Kremenek3064ef92010-08-27 21:34:58 +00001583bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001584 // Visit the nested-name-specifier, if present.
1585 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1586 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1587 return true;
1588
Ted Kremenek3064ef92010-08-27 21:34:58 +00001589 if (D->isDefinition()) {
1590 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1591 E = D->bases_end(); I != E; ++I) {
1592 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1593 return true;
1594 }
1595 }
1596
1597 return VisitTagDecl(D);
1598}
1599
Ted Kremenek09dfa372010-02-18 05:46:33 +00001600bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001601 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1602 i != e; ++i)
1603 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001604 return true;
1605
1606 return false;
1607}
1608
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001609//===----------------------------------------------------------------------===//
1610// Data-recursive visitor methods.
1611//===----------------------------------------------------------------------===//
1612
Ted Kremenek28a71942010-11-13 00:36:47 +00001613namespace {
Ted Kremenek035dc412010-11-13 00:36:50 +00001614#define DEF_JOB(NAME, DATA, KIND)\
1615class NAME : public VisitorJob {\
1616public:\
1617 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1618 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekf64d8032010-11-18 00:02:32 +00001619 DATA *get() const { return static_cast<DATA*>(data[0]); }\
Ted Kremenek035dc412010-11-13 00:36:50 +00001620};
1621
1622DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1623DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001624DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001625DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001626DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
Ted Kremenek60608ec2010-11-17 00:50:47 +00001627 ExplicitTemplateArgsVisitKind)
Douglas Gregor94d96292011-01-19 20:34:17 +00001628DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
Ted Kremenek035dc412010-11-13 00:36:50 +00001629#undef DEF_JOB
1630
1631class DeclVisit : public VisitorJob {
1632public:
1633 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1634 VisitorJob(parent, VisitorJob::DeclVisitKind,
1635 d, isFirst ? (void*) 1 : (void*) 0) {}
1636 static bool classof(const VisitorJob *VJ) {
Ted Kremenek82f3c502010-11-15 22:23:26 +00001637 return VJ->getKind() == DeclVisitKind;
Ted Kremenek035dc412010-11-13 00:36:50 +00001638 }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001639 Decl *get() const { return static_cast<Decl*>(data[0]); }
1640 bool isFirst() const { return data[1] ? true : false; }
Ted Kremenek035dc412010-11-13 00:36:50 +00001641};
Ted Kremenek035dc412010-11-13 00:36:50 +00001642class TypeLocVisit : public VisitorJob {
1643public:
1644 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1645 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1646 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1647
1648 static bool classof(const VisitorJob *VJ) {
1649 return VJ->getKind() == TypeLocVisitKind;
1650 }
1651
Ted Kremenek82f3c502010-11-15 22:23:26 +00001652 TypeLoc get() const {
Ted Kremenekf64d8032010-11-18 00:02:32 +00001653 QualType T = QualType::getFromOpaquePtr(data[0]);
1654 return TypeLoc(T, data[1]);
Ted Kremenek035dc412010-11-13 00:36:50 +00001655 }
1656};
1657
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001658class LabelRefVisit : public VisitorJob {
1659public:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001660 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1661 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001662 labelLoc.getPtrEncoding()) {}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001663
1664 static bool classof(const VisitorJob *VJ) {
1665 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1666 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001667 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001668 SourceLocation getLoc() const {
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001669 return SourceLocation::getFromPtrEncoding(data[1]); }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001670};
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001671
1672class NestedNameSpecifierLocVisit : public VisitorJob {
1673public:
1674 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1675 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1676 Qualifier.getNestedNameSpecifier(),
1677 Qualifier.getOpaqueData()) { }
1678
1679 static bool classof(const VisitorJob *VJ) {
1680 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1681 }
1682
1683 NestedNameSpecifierLoc get() const {
1684 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1685 data[1]);
1686 }
1687};
1688
Ted Kremenekf64d8032010-11-18 00:02:32 +00001689class DeclarationNameInfoVisit : public VisitorJob {
1690public:
1691 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1692 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1693 static bool classof(const VisitorJob *VJ) {
1694 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1695 }
1696 DeclarationNameInfo get() const {
1697 Stmt *S = static_cast<Stmt*>(data[0]);
1698 switch (S->getStmtClass()) {
1699 default:
1700 llvm_unreachable("Unhandled Stmt");
1701 case Stmt::CXXDependentScopeMemberExprClass:
1702 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1703 case Stmt::DependentScopeDeclRefExprClass:
1704 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1705 }
1706 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001707};
Ted Kremenekcdba6592010-11-18 00:42:18 +00001708class MemberRefVisit : public VisitorJob {
1709public:
1710 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1711 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001712 L.getPtrEncoding()) {}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001713 static bool classof(const VisitorJob *VJ) {
1714 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1715 }
1716 FieldDecl *get() const {
1717 return static_cast<FieldDecl*>(data[0]);
1718 }
1719 SourceLocation getLoc() const {
1720 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1721 }
1722};
Ted Kremenek28a71942010-11-13 00:36:47 +00001723class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1724 VisitorWorkList &WL;
1725 CXCursor Parent;
1726public:
1727 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1728 : WL(wl), Parent(parent) {}
1729
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001730 void VisitAddrLabelExpr(AddrLabelExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001731 void VisitBlockExpr(BlockExpr *B);
Ted Kremenek28a71942010-11-13 00:36:47 +00001732 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek083c7e22010-11-13 05:38:03 +00001733 void VisitCompoundStmt(CompoundStmt *S);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001734 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
Ted Kremenekf64d8032010-11-18 00:02:32 +00001735 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001736 void VisitCXXNewExpr(CXXNewExpr *E);
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001737 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001738 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001739 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001740 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001741 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
Ted Kremenek55b933a2010-11-17 00:50:36 +00001742 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001743 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001744 void VisitDeclRefExpr(DeclRefExpr *D);
Ted Kremenek035dc412010-11-13 00:36:50 +00001745 void VisitDeclStmt(DeclStmt *S);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001746 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001747 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001748 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1749 void VisitForStmt(ForStmt *FS);
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001750 void VisitGotoStmt(GotoStmt *GS);
Ted Kremenek28a71942010-11-13 00:36:47 +00001751 void VisitIfStmt(IfStmt *If);
1752 void VisitInitListExpr(InitListExpr *IE);
1753 void VisitMemberExpr(MemberExpr *M);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001754 void VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek73d15c42010-11-13 01:09:29 +00001755 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001756 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1757 void VisitOverloadExpr(OverloadExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001758 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001759 void VisitStmt(Stmt *S);
1760 void VisitSwitchStmt(SwitchStmt *S);
1761 void VisitWhileStmt(WhileStmt *W);
Ted Kremenek2939b6f2010-11-17 00:50:50 +00001762 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Francois Pichet6ad6f282010-12-07 00:08:36 +00001763 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
John Wiegley21ff2e52011-04-28 00:16:57 +00001764 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
John Wiegley55262202011-04-25 06:54:41 +00001765 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
Ted Kremenek28a71942010-11-13 00:36:47 +00001766 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
Ted Kremenek9d3bf792010-11-17 00:50:43 +00001767 void VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor94d96292011-01-19 20:34:17 +00001768 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001769
Ted Kremenek28a71942010-11-13 00:36:47 +00001770private:
Ted Kremenekf64d8032010-11-18 00:02:32 +00001771 void AddDeclarationNameInfo(Stmt *S);
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001772 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001773 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001774 void AddMemberRef(FieldDecl *D, SourceLocation L);
Ted Kremenek28a71942010-11-13 00:36:47 +00001775 void AddStmt(Stmt *S);
Ted Kremenek035dc412010-11-13 00:36:50 +00001776 void AddDecl(Decl *D, bool isFirst = true);
Ted Kremenek28a71942010-11-13 00:36:47 +00001777 void AddTypeLoc(TypeSourceInfo *TI);
1778 void EnqueueChildren(Stmt *S);
1779};
1780} // end anonyous namespace
1781
Ted Kremenekf64d8032010-11-18 00:02:32 +00001782void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1783 // 'S' should always be non-null, since it comes from the
1784 // statement we are visiting.
1785 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1786}
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001787
1788void
1789EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1790 if (Qualifier)
1791 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1792}
1793
Ted Kremenek28a71942010-11-13 00:36:47 +00001794void EnqueueVisitor::AddStmt(Stmt *S) {
1795 if (S)
1796 WL.push_back(StmtVisit(S, Parent));
1797}
Ted Kremenek035dc412010-11-13 00:36:50 +00001798void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001799 if (D)
Ted Kremenek035dc412010-11-13 00:36:50 +00001800 WL.push_back(DeclVisit(D, Parent, isFirst));
Ted Kremenek28a71942010-11-13 00:36:47 +00001801}
Ted Kremenek60608ec2010-11-17 00:50:47 +00001802void EnqueueVisitor::
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001803 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001804 if (A)
1805 WL.push_back(ExplicitTemplateArgsVisit(
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00001806 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
Ted Kremenek60608ec2010-11-17 00:50:47 +00001807}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001808void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1809 if (D)
1810 WL.push_back(MemberRefVisit(D, L, Parent));
1811}
Ted Kremenek28a71942010-11-13 00:36:47 +00001812void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1813 if (TI)
1814 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1815 }
1816void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001817 unsigned size = WL.size();
John McCall7502c1d2011-02-13 04:07:26 +00001818 for (Stmt::child_range Child = S->children(); Child; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001819 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001820 }
1821 if (size == WL.size())
1822 return;
1823 // Now reverse the entries we just added. This will match the DFS
1824 // ordering performed by the worklist.
1825 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1826 std::reverse(I, E);
1827}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001828void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1829 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1830}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001831void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1832 AddDecl(B->getBlockDecl());
1833}
Ted Kremenek28a71942010-11-13 00:36:47 +00001834void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1835 EnqueueChildren(E);
1836 AddTypeLoc(E->getTypeSourceInfo());
1837}
Ted Kremenek083c7e22010-11-13 05:38:03 +00001838void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1839 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1840 E = S->body_rend(); I != E; ++I) {
1841 AddStmt(*I);
1842 }
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001843}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001844void EnqueueVisitor::
1845VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1846 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1847 AddDeclarationNameInfo(E);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001848 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1849 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekf64d8032010-11-18 00:02:32 +00001850 if (!E->isImplicitAccess())
1851 AddStmt(E->getBase());
1852}
Ted Kremenek11b8e3e2010-11-13 05:55:53 +00001853void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1854 // Enqueue the initializer or constructor arguments.
1855 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I)
1856 AddStmt(E->getConstructorArg(I-1));
1857 // Enqueue the array size, if any.
1858 AddStmt(E->getArraySize());
1859 // Enqueue the allocated type.
1860 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1861 // Enqueue the placement arguments.
1862 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1863 AddStmt(E->getPlacementArg(I-1));
1864}
Ted Kremenek28a71942010-11-13 00:36:47 +00001865void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Ted Kremenek8b8d8c92010-11-13 05:55:56 +00001866 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1867 AddStmt(CE->getArg(I-1));
Ted Kremenek28a71942010-11-13 00:36:47 +00001868 AddStmt(CE->getCallee());
1869 AddStmt(CE->getArg(0));
1870}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001871void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1872 // Visit the name of the type being destroyed.
1873 AddTypeLoc(E->getDestroyedTypeInfo());
1874 // Visit the scope type that looks disturbingly like the nested-name-specifier
1875 // but isn't.
1876 AddTypeLoc(E->getScopeTypeInfo());
1877 // Visit the nested-name-specifier.
Douglas Gregorf3db29f2011-02-25 18:19:59 +00001878 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1879 AddNestedNameSpecifierLoc(QualifierLoc);
Ted Kremenekcdba6592010-11-18 00:42:18 +00001880 // Visit base expression.
1881 AddStmt(E->getBase());
1882}
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00001883void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1884 AddTypeLoc(E->getTypeSourceInfo());
1885}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001886void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1887 EnqueueChildren(E);
1888 AddTypeLoc(E->getTypeSourceInfo());
1889}
Ted Kremenekb8dd1ca2010-11-17 00:50:41 +00001890void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1891 EnqueueChildren(E);
1892 if (E->isTypeOperand())
1893 AddTypeLoc(E->getTypeOperandSourceInfo());
1894}
Ted Kremenek55b933a2010-11-17 00:50:36 +00001895
1896void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1897 *E) {
1898 EnqueueChildren(E);
1899 AddTypeLoc(E->getTypeSourceInfo());
1900}
Ted Kremenek1e7e8772010-11-17 00:50:52 +00001901void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1902 EnqueueChildren(E);
1903 if (E->isTypeOperand())
1904 AddTypeLoc(E->getTypeOperandSourceInfo());
1905}
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001906void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00001907 if (DR->hasExplicitTemplateArgs()) {
1908 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1909 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00001910 WL.push_back(DeclRefExprParts(DR, Parent));
1911}
Ted Kremenekf64d8032010-11-18 00:02:32 +00001912void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1913 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1914 AddDeclarationNameInfo(E);
Douglas Gregor00cf3cc2011-02-25 20:49:16 +00001915 AddNestedNameSpecifierLoc(E->getQualifierLoc());
Ted Kremenekf64d8032010-11-18 00:02:32 +00001916}
Ted Kremenek035dc412010-11-13 00:36:50 +00001917void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1918 unsigned size = WL.size();
1919 bool isFirst = true;
1920 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1921 D != DEnd; ++D) {
1922 AddDecl(*D, isFirst);
1923 isFirst = false;
1924 }
1925 if (size == WL.size())
1926 return;
1927 // Now reverse the entries we just added. This will match the DFS
1928 // ordering performed by the worklist.
1929 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1930 std::reverse(I, E);
1931}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001932void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1933 AddStmt(E->getInit());
1934 typedef DesignatedInitExpr::Designator Designator;
1935 for (DesignatedInitExpr::reverse_designators_iterator
1936 D = E->designators_rbegin(), DEnd = E->designators_rend();
1937 D != DEnd; ++D) {
1938 if (D->isFieldDesignator()) {
1939 if (FieldDecl *Field = D->getField())
1940 AddMemberRef(Field, D->getFieldLoc());
1941 continue;
1942 }
1943 if (D->isArrayDesignator()) {
1944 AddStmt(E->getArrayIndex(*D));
1945 continue;
1946 }
1947 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1948 AddStmt(E->getArrayRangeEnd(*D));
1949 AddStmt(E->getArrayRangeStart(*D));
1950 }
1951}
Ted Kremenek28a71942010-11-13 00:36:47 +00001952void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1953 EnqueueChildren(E);
1954 AddTypeLoc(E->getTypeInfoAsWritten());
1955}
1956void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1957 AddStmt(FS->getBody());
1958 AddStmt(FS->getInc());
1959 AddStmt(FS->getCond());
1960 AddDecl(FS->getConditionVariable());
1961 AddStmt(FS->getInit());
1962}
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00001963void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1964 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1965}
Ted Kremenek28a71942010-11-13 00:36:47 +00001966void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1967 AddStmt(If->getElse());
1968 AddStmt(If->getThen());
1969 AddStmt(If->getCond());
1970 AddDecl(If->getConditionVariable());
1971}
1972void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1973 // We care about the syntactic form of the initializer list, only.
1974 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1975 IE = Syntactic;
1976 EnqueueChildren(IE);
1977}
1978void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
Douglas Gregor89629a72010-11-17 17:15:08 +00001979 WL.push_back(MemberExprParts(M, Parent));
1980
1981 // If the base of the member access expression is an implicit 'this', don't
1982 // visit it.
1983 // FIXME: If we ever want to show these implicit accesses, this will be
1984 // unfortunate. However, clang_getCursor() relies on this behavior.
Douglas Gregor75e85042011-03-02 21:06:53 +00001985 if (!M->isImplicitAccess())
1986 AddStmt(M->getBase());
Ted Kremenek28a71942010-11-13 00:36:47 +00001987}
Ted Kremenek73d15c42010-11-13 01:09:29 +00001988void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1989 AddTypeLoc(E->getEncodedTypeSourceInfo());
1990}
Ted Kremenek28a71942010-11-13 00:36:47 +00001991void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1992 EnqueueChildren(M);
1993 AddTypeLoc(M->getClassReceiverTypeInfo());
1994}
Ted Kremenekcdba6592010-11-18 00:42:18 +00001995void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1996 // Visit the components of the offsetof expression.
1997 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
1998 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1999 const OffsetOfNode &Node = E->getComponent(I-1);
2000 switch (Node.getKind()) {
2001 case OffsetOfNode::Array:
2002 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2003 break;
2004 case OffsetOfNode::Field:
Abramo Bagnara06dec892011-03-12 09:45:03 +00002005 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
Ted Kremenekcdba6592010-11-18 00:42:18 +00002006 break;
2007 case OffsetOfNode::Identifier:
2008 case OffsetOfNode::Base:
2009 continue;
2010 }
2011 }
2012 // Visit the type into which we're computing the offset.
2013 AddTypeLoc(E->getTypeSourceInfo());
2014}
Ted Kremenek28a71942010-11-13 00:36:47 +00002015void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60608ec2010-11-17 00:50:47 +00002016 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
Ted Kremenek60458782010-11-12 21:34:16 +00002017 WL.push_back(OverloadExprParts(E, Parent));
2018}
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002019void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2020 UnaryExprOrTypeTraitExpr *E) {
Ted Kremenek6d0a00d2010-11-17 02:18:35 +00002021 EnqueueChildren(E);
2022 if (E->isArgumentType())
2023 AddTypeLoc(E->getArgumentTypeInfo());
2024}
Ted Kremenek28a71942010-11-13 00:36:47 +00002025void EnqueueVisitor::VisitStmt(Stmt *S) {
2026 EnqueueChildren(S);
2027}
2028void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2029 AddStmt(S->getBody());
2030 AddStmt(S->getCond());
2031 AddDecl(S->getConditionVariable());
2032}
Ted Kremenekfafa75a2010-11-17 00:50:39 +00002033
Ted Kremenek28a71942010-11-13 00:36:47 +00002034void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2035 AddStmt(W->getBody());
2036 AddStmt(W->getCond());
2037 AddDecl(W->getConditionVariable());
2038}
John Wiegley21ff2e52011-04-28 00:16:57 +00002039
Ted Kremenek2939b6f2010-11-17 00:50:50 +00002040void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2041 AddTypeLoc(E->getQueriedTypeSourceInfo());
2042}
Francois Pichet6ad6f282010-12-07 00:08:36 +00002043
2044void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002045 AddTypeLoc(E->getRhsTypeSourceInfo());
Francois Pichet0a03a3f2010-12-08 09:11:05 +00002046 AddTypeLoc(E->getLhsTypeSourceInfo());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002047}
2048
John Wiegley21ff2e52011-04-28 00:16:57 +00002049void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2050 AddTypeLoc(E->getQueriedTypeSourceInfo());
2051}
2052
John Wiegley55262202011-04-25 06:54:41 +00002053void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2054 EnqueueChildren(E);
2055}
2056
Ted Kremenek28a71942010-11-13 00:36:47 +00002057void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2058 VisitOverloadExpr(U);
2059 if (!U->isImplicitAccess())
2060 AddStmt(U->getBase());
2061}
Ted Kremenek9d3bf792010-11-17 00:50:43 +00002062void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2063 AddStmt(E->getSubExpr());
2064 AddTypeLoc(E->getWrittenTypeInfo());
2065}
Douglas Gregor94d96292011-01-19 20:34:17 +00002066void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2067 WL.push_back(SizeOfPackExprParts(E, Parent));
2068}
Ted Kremenek60458782010-11-12 21:34:16 +00002069
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002070void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00002071 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002072}
2073
2074bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2075 if (RegionOfInterest.isValid()) {
2076 SourceRange Range = getRawCursorExtent(C);
2077 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2078 return false;
2079 }
2080 return true;
2081}
2082
2083bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2084 while (!WL.empty()) {
2085 // Dequeue the worklist item.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002086 VisitorJob LI = WL.back();
2087 WL.pop_back();
2088
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002089 // Set the Parent field, then back to its old value once we're done.
2090 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2091
2092 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00002093 case VisitorJob::DeclVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002094 Decl *D = cast<DeclVisit>(&LI)->get();
Ted Kremenekf1107452010-11-12 18:26:56 +00002095 if (!D)
2096 continue;
2097
2098 // For now, perform default visitation for Decls.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002099 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst())))
Ted Kremenekf1107452010-11-12 18:26:56 +00002100 return true;
2101
2102 continue;
2103 }
Ted Kremenek60608ec2010-11-17 00:50:47 +00002104 case VisitorJob::ExplicitTemplateArgsVisitKind: {
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002105 const ASTTemplateArgumentListInfo *ArgList =
Ted Kremenek60608ec2010-11-17 00:50:47 +00002106 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2107 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2108 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2109 Arg != ArgEnd; ++Arg) {
2110 if (VisitTemplateArgumentLoc(*Arg))
2111 return true;
2112 }
2113 continue;
2114 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002115 case VisitorJob::TypeLocVisitKind: {
2116 // Perform default visitation for TypeLocs.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002117 if (Visit(cast<TypeLocVisit>(&LI)->get()))
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00002118 return true;
2119 continue;
2120 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002121 case VisitorJob::LabelRefVisitKind: {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002122 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Ted Kremeneke7455012011-02-23 04:54:51 +00002123 if (LabelStmt *stmt = LS->getStmt()) {
2124 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2125 TU))) {
2126 return true;
2127 }
2128 }
Ted Kremenekae1fd6f2010-11-17 00:50:45 +00002129 continue;
2130 }
Ted Kremenek47695c82011-08-18 22:25:21 +00002131
Douglas Gregorf3db29f2011-02-25 18:19:59 +00002132 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2133 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2134 if (VisitNestedNameSpecifierLoc(V->get()))
2135 return true;
2136 continue;
2137 }
2138
Ted Kremenekf64d8032010-11-18 00:02:32 +00002139 case VisitorJob::DeclarationNameInfoVisitKind: {
2140 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2141 ->get()))
2142 return true;
2143 continue;
2144 }
Ted Kremenekcdba6592010-11-18 00:42:18 +00002145 case VisitorJob::MemberRefVisitKind: {
2146 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2147 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2148 return true;
2149 continue;
2150 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002151 case VisitorJob::StmtVisitKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002152 Stmt *S = cast<StmtVisit>(&LI)->get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00002153 if (!S)
2154 continue;
2155
Ted Kremenekf1107452010-11-12 18:26:56 +00002156 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002157 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
Ted Kremenekcdba6592010-11-18 00:42:18 +00002158 if (!IsInRegionOfInterest(Cursor))
2159 continue;
2160 switch (Visitor(Cursor, Parent, ClientData)) {
2161 case CXChildVisit_Break: return true;
2162 case CXChildVisit_Continue: break;
2163 case CXChildVisit_Recurse:
2164 EnqueueWorkList(WL, S);
Ted Kremenek82f3c502010-11-15 22:23:26 +00002165 break;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002166 }
Ted Kremenek82f3c502010-11-15 22:23:26 +00002167 continue;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002168 }
2169 case VisitorJob::MemberExprPartsKind: {
2170 // Handle the other pieces in the MemberExpr besides the base.
Ted Kremenek82f3c502010-11-15 22:23:26 +00002171 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002172
2173 // Visit the nested-name-specifier
Douglas Gregor40d96a62011-02-28 21:54:11 +00002174 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2175 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002176 return true;
2177
2178 // Visit the declaration name.
2179 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2180 return true;
2181
2182 // Visit the explicitly-specified template arguments, if any.
2183 if (M->hasExplicitTemplateArgs()) {
2184 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2185 *ArgEnd = Arg + M->getNumTemplateArgs();
2186 Arg != ArgEnd; ++Arg) {
2187 if (VisitTemplateArgumentLoc(*Arg))
2188 return true;
2189 }
2190 }
2191 continue;
2192 }
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002193 case VisitorJob::DeclRefExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002194 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002195 // Visit nested-name-specifier, if present.
Douglas Gregor40d96a62011-02-28 21:54:11 +00002196 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2197 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002198 return true;
2199 // Visit declaration name.
2200 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2201 return true;
Ted Kremeneke4979cc2010-11-13 00:58:18 +00002202 continue;
2203 }
Ted Kremenek60458782010-11-12 21:34:16 +00002204 case VisitorJob::OverloadExprPartsKind: {
Ted Kremenek82f3c502010-11-15 22:23:26 +00002205 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Ted Kremenek60458782010-11-12 21:34:16 +00002206 // Visit the nested-name-specifier.
Douglas Gregor4c9be892011-02-28 20:01:57 +00002207 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2208 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Ted Kremenek60458782010-11-12 21:34:16 +00002209 return true;
2210 // Visit the declaration name.
2211 if (VisitDeclarationNameInfo(O->getNameInfo()))
2212 return true;
2213 // Visit the overloaded declaration reference.
2214 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2215 return true;
Ted Kremenek60458782010-11-12 21:34:16 +00002216 continue;
2217 }
Douglas Gregor94d96292011-01-19 20:34:17 +00002218 case VisitorJob::SizeOfPackExprPartsKind: {
2219 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2220 NamedDecl *Pack = E->getPack();
2221 if (isa<TemplateTypeParmDecl>(Pack)) {
2222 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2223 E->getPackLoc(), TU)))
2224 return true;
2225
2226 continue;
2227 }
2228
2229 if (isa<TemplateTemplateParmDecl>(Pack)) {
2230 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2231 E->getPackLoc(), TU)))
2232 return true;
2233
2234 continue;
2235 }
2236
2237 // Non-type template parameter packs and function parameter packs are
2238 // treated like DeclRefExpr cursors.
2239 continue;
2240 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002241 }
2242 }
2243 return false;
2244}
2245
Ted Kremenekcdba6592010-11-18 00:42:18 +00002246bool CursorVisitor::Visit(Stmt *S) {
Ted Kremenekd1ded662010-11-15 23:31:32 +00002247 VisitorWorkList *WL = 0;
2248 if (!WorkListFreeList.empty()) {
2249 WL = WorkListFreeList.back();
2250 WL->clear();
2251 WorkListFreeList.pop_back();
2252 }
2253 else {
2254 WL = new VisitorWorkList();
2255 WorkListCache.push_back(WL);
2256 }
2257 EnqueueWorkList(*WL, S);
2258 bool result = RunVisitorWorkList(*WL);
2259 WorkListFreeList.push_back(WL);
2260 return result;
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002261}
2262
Francois Pichet48a8d142011-07-25 22:00:44 +00002263namespace {
2264typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2265RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2266 const DeclarationNameInfo &NI,
2267 const SourceRange &QLoc,
Argyrios Kyrtzidisb0c3e092011-09-22 20:07:03 +00002268 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
Francois Pichet48a8d142011-07-25 22:00:44 +00002269 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2270 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2271 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2272
2273 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2274
2275 RefNamePieces Pieces;
2276
2277 if (WantQualifier && QLoc.isValid())
2278 Pieces.push_back(QLoc);
2279
2280 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2281 Pieces.push_back(NI.getLoc());
2282
2283 if (WantTemplateArgs && TemplateArgs)
2284 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2285 TemplateArgs->RAngleLoc));
2286
2287 if (Kind == DeclarationName::CXXOperatorName) {
2288 Pieces.push_back(SourceLocation::getFromRawEncoding(
2289 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2290 Pieces.push_back(SourceLocation::getFromRawEncoding(
2291 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2292 }
2293
2294 if (WantSinglePiece) {
2295 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2296 Pieces.clear();
2297 Pieces.push_back(R);
2298 }
2299
2300 return Pieces;
2301}
2302}
2303
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002304//===----------------------------------------------------------------------===//
2305// Misc. API hooks.
2306//===----------------------------------------------------------------------===//
2307
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002308static llvm::sys::Mutex EnableMultithreadingMutex;
2309static bool EnabledMultithreading;
2310
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002311extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002312CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2313 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002314 // Disable pretty stack trace functionality, which will otherwise be a very
2315 // poor citizen of the world and set up all sorts of signal handlers.
2316 llvm::DisablePrettyStackTrace = true;
2317
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002318 // We use crash recovery to make some of our APIs more reliable, implicitly
2319 // enable it.
2320 llvm::CrashRecoveryContext::Enable();
2321
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002322 // Enable support for multithreading in LLVM.
2323 {
2324 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2325 if (!EnabledMultithreading) {
2326 llvm::llvm_start_multithreaded();
2327 EnabledMultithreading = true;
2328 }
2329 }
2330
Douglas Gregora030b7c2010-01-22 20:35:53 +00002331 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002332 if (excludeDeclarationsFromPCH)
2333 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002334 if (displayDiagnostics)
2335 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002336 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002337}
2338
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002339void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002340 if (CIdx)
2341 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002342}
2343
Ted Kremenekd2427dd2011-03-18 23:05:39 +00002344void clang_toggleCrashRecovery(unsigned isEnabled) {
2345 if (isEnabled)
2346 llvm::CrashRecoveryContext::Enable();
2347 else
2348 llvm::CrashRecoveryContext::Disable();
2349}
2350
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002351CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002352 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002353 if (!CIdx)
2354 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002355
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002356 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002357 FileSystemOptions FileSystemOpts;
2358 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002359
David Blaikied6471f72011-09-25 23:23:43 +00002360 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002361 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002362 CXXIdx->getOnlyLocalDecls(),
2363 0, 0, true);
Ted Kremeneka60ed472010-11-16 08:15:36 +00002364 return MakeCXTranslationUnit(TU);
Steve Naroff600866c2009-08-27 19:51:58 +00002365}
2366
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002367unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002368 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregorb5af8432011-08-25 22:54:01 +00002369 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002370}
2371
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002372CXTranslationUnit
2373clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2374 const char *source_filename,
2375 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002376 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002377 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002378 struct CXUnsavedFile *unsaved_files) {
Douglas Gregordca8ee82011-05-06 16:33:08 +00002379 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord |
Chandler Carruthba7537f2011-07-14 09:02:10 +00002380 CXTranslationUnit_NestedMacroExpansions;
Douglas Gregor5a430212010-07-21 18:52:53 +00002381 return clang_parseTranslationUnit(CIdx, source_filename,
2382 command_line_args, num_command_line_args,
2383 unsaved_files, num_unsaved_files,
Douglas Gregordca8ee82011-05-06 16:33:08 +00002384 Options);
Douglas Gregor5a430212010-07-21 18:52:53 +00002385}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002386
2387struct ParseTranslationUnitInfo {
2388 CXIndex CIdx;
2389 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002390 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002391 int num_command_line_args;
2392 struct CXUnsavedFile *unsaved_files;
2393 unsigned num_unsaved_files;
2394 unsigned options;
2395 CXTranslationUnit result;
2396};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002397static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002398 ParseTranslationUnitInfo *PTUI =
2399 static_cast<ParseTranslationUnitInfo*>(UserData);
2400 CXIndex CIdx = PTUI->CIdx;
2401 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002402 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002403 int num_command_line_args = PTUI->num_command_line_args;
2404 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2405 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2406 unsigned options = PTUI->options;
2407 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002408
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002409 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002410 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002411
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002412 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2413
Douglas Gregor44c181a2010-07-23 00:33:23 +00002414 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor467dc882011-08-25 22:30:56 +00002415 // FIXME: Add a flag for modules.
2416 TranslationUnitKind TUKind
2417 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002418 bool CacheCodeCompetionResults
2419 = options & CXTranslationUnit_CacheCompletionResults;
2420
Douglas Gregor5352ac02010-01-28 00:27:43 +00002421 // Configure the diagnostics.
2422 DiagnosticOptions DiagOpts;
David Blaikied6471f72011-09-25 23:23:43 +00002423 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Ted Kremenek25a11e12011-03-22 01:15:24 +00002424 Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2425 command_line_args));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002426
Ted Kremenek25a11e12011-03-22 01:15:24 +00002427 // Recover resources if we crash before exiting this function.
David Blaikied6471f72011-09-25 23:23:43 +00002428 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2429 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00002430 DiagCleanup(Diags.getPtr());
2431
2432 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2433 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2434
2435 // Recover resources if we crash before exiting this function.
2436 llvm::CrashRecoveryContextCleanupRegistrar<
2437 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2438
Douglas Gregor4db64a42010-01-23 00:14:00 +00002439 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002440 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002442 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002443 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2444 Buffer));
Douglas Gregor4db64a42010-01-23 00:14:00 +00002445 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002446
Ted Kremenek25a11e12011-03-22 01:15:24 +00002447 llvm::OwningPtr<std::vector<const char *> >
2448 Args(new std::vector<const char*>());
2449
2450 // Recover resources if we crash before exiting this method.
2451 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2452 ArgsCleanup(Args.get());
2453
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002454 // Since the Clang C library is primarily used by batch tools dealing with
2455 // (often very broken) source code, where spell-checking can have a
2456 // significant negative impact on performance (particularly when
2457 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002458 // Only do this if we haven't found a spell-checking-related argument.
2459 bool FoundSpellCheckingArgument = false;
2460 for (int I = 0; I != num_command_line_args; ++I) {
2461 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2462 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2463 FoundSpellCheckingArgument = true;
2464 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002465 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002466 }
2467 if (!FoundSpellCheckingArgument)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002468 Args->push_back("-fno-spell-checking");
Douglas Gregorb10daed2010-10-11 16:52:23 +00002469
Ted Kremenek25a11e12011-03-22 01:15:24 +00002470 Args->insert(Args->end(), command_line_args,
2471 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002472
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002473 // The 'source_filename' argument is optional. If the caller does not
2474 // specify it then it is assumed that the source file is specified
2475 // in the actual argument list.
2476 // Put the source file after command_line_args otherwise if '-x' flag is
2477 // present it will be unused.
2478 if (source_filename)
Ted Kremenek25a11e12011-03-22 01:15:24 +00002479 Args->push_back(source_filename);
Argyrios Kyrtzidisc8429552011-03-20 18:17:52 +00002480
Douglas Gregor44c181a2010-07-23 00:33:23 +00002481 // Do we need the detailed preprocessing record?
Chandler Carruthba7537f2011-07-14 09:02:10 +00002482 bool NestedMacroExpansions = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00002483 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Ted Kremenek25a11e12011-03-22 01:15:24 +00002484 Args->push_back("-Xclang");
2485 Args->push_back("-detailed-preprocessing-record");
Chandler Carruthba7537f2011-07-14 09:02:10 +00002486 NestedMacroExpansions
2487 = (options & CXTranslationUnit_NestedMacroExpansions);
Douglas Gregor44c181a2010-07-23 00:33:23 +00002488 }
2489
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002490 unsigned NumErrors = Diags->getClient()->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002491 llvm::OwningPtr<ASTUnit> Unit(
Ted Kremenek4ee99262011-03-22 20:16:19 +00002492 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2493 /* vector::data() not portable */,
2494 Args->size() ? (&(*Args)[0] + Args->size()) :0,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002495 Diags,
2496 CXXIdx->getClangResourcesPath(),
2497 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002498 /*CaptureDiagnostics=*/true,
Ted Kremenek4ee99262011-03-22 20:16:19 +00002499 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
Ted Kremenek25a11e12011-03-22 01:15:24 +00002500 RemappedFiles->size(),
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00002501 /*RemappedFilesKeepOriginalName=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002502 PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00002503 TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002504 CacheCodeCompetionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00002505 NestedMacroExpansions));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002506
Argyrios Kyrtzidis026f6912010-11-18 21:47:04 +00002507 if (NumErrors != Diags->getClient()->getNumErrors()) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002508 // Make sure to check that 'Unit' is non-NULL.
2509 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2510 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2511 DEnd = Unit->stored_diag_end();
2512 D != DEnd; ++D) {
2513 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2514 CXString Msg = clang_formatDiagnostic(&Diag,
2515 clang_defaultDiagnosticDisplayOptions());
2516 fprintf(stderr, "%s\n", clang_getCString(Msg));
2517 clang_disposeString(Msg);
2518 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002519#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002520 // On Windows, force a flush, since there may be multiple copies of
2521 // stderr and stdout in the file system, all with different buffers
2522 // but writing to the same device.
2523 fflush(stderr);
2524#endif
2525 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002526 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002527
Ted Kremeneka60ed472010-11-16 08:15:36 +00002528 PTUI->result = MakeCXTranslationUnit(Unit.take());
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002529}
2530CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2531 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002532 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002533 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002534 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002535 unsigned num_unsaved_files,
2536 unsigned options) {
2537 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002538 num_command_line_args, unsaved_files,
2539 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002540 llvm::CrashRecoveryContext CRC;
2541
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002542 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002543 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2544 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2545 fprintf(stderr, " 'command_line_args' : [");
2546 for (int i = 0; i != num_command_line_args; ++i) {
2547 if (i)
2548 fprintf(stderr, ", ");
2549 fprintf(stderr, "'%s'", command_line_args[i]);
2550 }
2551 fprintf(stderr, "],\n");
2552 fprintf(stderr, " 'unsaved_files' : [");
2553 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2554 if (i)
2555 fprintf(stderr, ", ");
2556 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2557 unsaved_files[i].Length);
2558 }
2559 fprintf(stderr, "],\n");
2560 fprintf(stderr, " 'options' : %d,\n", options);
2561 fprintf(stderr, "}\n");
2562
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002563 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +00002564 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2565 PrintLibclangResourceUsage(PTUI.result);
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002566 }
Douglas Gregor6df78732011-05-05 20:27:22 +00002567
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002568 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002569}
2570
Douglas Gregor19998442010-08-13 15:35:05 +00002571unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2572 return CXSaveTranslationUnit_None;
2573}
2574
2575int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2576 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002577 if (!TU)
Douglas Gregor39c411f2011-07-06 16:43:36 +00002578 return CXSaveError_InvalidTU;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002579
Douglas Gregor39c411f2011-07-06 16:43:36 +00002580 CXSaveError result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
Douglas Gregor6df78732011-05-05 20:27:22 +00002581 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2582 PrintLibclangResourceUsage(TU);
2583 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002584}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002585
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002586void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002587 if (CTUnit) {
2588 // If the translation unit has been marked as unsafe to free, just discard
2589 // it.
Ted Kremeneka60ed472010-11-16 08:15:36 +00002590 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002591 return;
2592
Ted Kremeneka60ed472010-11-16 08:15:36 +00002593 delete static_cast<ASTUnit *>(CTUnit->TUData);
2594 disposeCXStringPool(CTUnit->StringPool);
2595 delete CTUnit;
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002596 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002597}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002598
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002599unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2600 return CXReparse_None;
2601}
2602
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002603struct ReparseTranslationUnitInfo {
2604 CXTranslationUnit TU;
2605 unsigned num_unsaved_files;
2606 struct CXUnsavedFile *unsaved_files;
2607 unsigned options;
2608 int result;
2609};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002610
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002611static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002612 ReparseTranslationUnitInfo *RTUI =
2613 static_cast<ReparseTranslationUnitInfo*>(UserData);
2614 CXTranslationUnit TU = RTUI->TU;
2615 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2616 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2617 unsigned options = RTUI->options;
2618 (void) options;
2619 RTUI->result = 1;
2620
Douglas Gregorabc563f2010-07-19 21:46:24 +00002621 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002622 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002623
Ted Kremeneka60ed472010-11-16 08:15:36 +00002624 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor593b0c12010-09-23 18:47:53 +00002625 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002626
Ted Kremenek25a11e12011-03-22 01:15:24 +00002627 llvm::OwningPtr<std::vector<ASTUnit::RemappedFile> >
2628 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2629
2630 // Recover resources if we crash before exiting this function.
2631 llvm::CrashRecoveryContextCleanupRegistrar<
2632 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2633
Douglas Gregorabc563f2010-07-19 21:46:24 +00002634 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002635 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002636 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002637 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Ted Kremenek25a11e12011-03-22 01:15:24 +00002638 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2639 Buffer));
Douglas Gregorabc563f2010-07-19 21:46:24 +00002640 }
2641
Ted Kremenek4ee99262011-03-22 20:16:19 +00002642 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2643 RemappedFiles->size()))
Douglas Gregor593b0c12010-09-23 18:47:53 +00002644 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002645}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002646
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002647int clang_reparseTranslationUnit(CXTranslationUnit TU,
2648 unsigned num_unsaved_files,
2649 struct CXUnsavedFile *unsaved_files,
2650 unsigned options) {
2651 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2652 options, 0 };
2653 llvm::CrashRecoveryContext CRC;
2654
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002655 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002656 fprintf(stderr, "libclang: crash detected during reparsing\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002657 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002658 return 1;
Douglas Gregor6df78732011-05-05 20:27:22 +00002659 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2660 PrintLibclangResourceUsage(TU);
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002661
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002662 return RTUI.result;
2663}
2664
Douglas Gregordf95a132010-08-09 20:45:32 +00002665
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002666CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002667 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002668 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002669
Ted Kremeneka60ed472010-11-16 08:15:36 +00002670 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002671 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002672}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002673
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002674CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002675 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002676 return Result;
2677}
2678
Ted Kremenekfb480492010-01-13 21:46:36 +00002679} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002680
Ted Kremenekfb480492010-01-13 21:46:36 +00002681//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002682// CXSourceLocation and CXSourceRange Operations.
2683//===----------------------------------------------------------------------===//
2684
Douglas Gregorb9790342010-01-22 21:44:22 +00002685extern "C" {
2686CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002687 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002688 return Result;
2689}
2690
2691unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002692 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2693 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2694 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002695}
2696
2697CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2698 CXFile file,
2699 unsigned line,
2700 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002701 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002702 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002703
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002704 bool Logging = ::getenv("LIBCLANG_LOGGING");
Ted Kremeneka60ed472010-11-16 08:15:36 +00002705 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002706 const FileEntry *File = static_cast<const FileEntry *>(file);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002707 SourceLocation SLoc = CXXUnit->getLocation(File, line, column);
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00002708 if (SLoc.isInvalid()) {
2709 if (Logging)
2710 llvm::errs() << "clang_getLocation(\"" << File->getName()
2711 << "\", " << line << ", " << column << ") = invalid\n";
2712 return clang_getNullLocation();
2713 }
2714
2715 if (Logging)
2716 llvm::errs() << "clang_getLocation(\"" << File->getName()
2717 << "\", " << line << ", " << column << ") = "
2718 << SLoc.getRawEncoding() << "\n";
David Chisnall83889a72010-10-15 17:07:39 +00002719
2720 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2721}
2722
2723CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2724 CXFile file,
2725 unsigned offset) {
2726 if (!tu || !file)
2727 return clang_getNullLocation();
2728
Ted Kremeneka60ed472010-11-16 08:15:36 +00002729 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002730 SourceLocation SLoc
2731 = CXXUnit->getLocation(static_cast<const FileEntry *>(file), offset);
David Chisnall83889a72010-10-15 17:07:39 +00002732 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002733
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002734 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002735}
2736
Douglas Gregor5352ac02010-01-28 00:27:43 +00002737CXSourceRange clang_getNullRange() {
2738 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2739 return Result;
2740}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002741
Douglas Gregor5352ac02010-01-28 00:27:43 +00002742CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2743 if (begin.ptr_data[0] != end.ptr_data[0] ||
2744 begin.ptr_data[1] != end.ptr_data[1])
2745 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002746
2747 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002748 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002749 return Result;
2750}
Douglas Gregorab4e83b2011-07-23 19:35:14 +00002751
2752unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2)
2753{
2754 return range1.ptr_data[0] == range2.ptr_data[0]
2755 && range1.ptr_data[1] == range2.ptr_data[1]
2756 && range1.begin_int_data == range2.begin_int_data
2757 && range1.end_int_data == range2.end_int_data;
2758}
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002759} // end: extern "C"
Douglas Gregorb9790342010-01-22 21:44:22 +00002760
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002761static void createNullLocation(CXFile *file, unsigned *line,
2762 unsigned *column, unsigned *offset) {
2763 if (file)
2764 *file = 0;
2765 if (line)
2766 *line = 0;
2767 if (column)
2768 *column = 0;
2769 if (offset)
2770 *offset = 0;
2771 return;
2772}
2773
2774extern "C" {
Chandler Carruth20174222011-08-31 16:53:37 +00002775void clang_getExpansionLocation(CXSourceLocation location,
2776 CXFile *file,
2777 unsigned *line,
2778 unsigned *column,
2779 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002780 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2781
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002782 if (!location.ptr_data[0] || Loc.isInvalid()) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002783 createNullLocation(file, line, column, offset);
Douglas Gregor46766dc2010-01-26 19:19:08 +00002784 return;
2785 }
2786
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002787 const SourceManager &SM =
2788 *static_cast<const SourceManager*>(location.ptr_data[0]);
Chandler Carruth20174222011-08-31 16:53:37 +00002789 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002790
Chandler Carruthcea731a2011-07-14 16:07:57 +00002791 // Check that the FileID is invalid on the expansion location.
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002792 // This can manifest in invalid code.
Chandler Carruth20174222011-08-31 16:53:37 +00002793 FileID fileID = SM.getFileID(ExpansionLoc);
Douglas Gregore23ac652011-04-20 00:21:03 +00002794 bool Invalid = false;
2795 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid);
2796 if (!sloc.isFile() || Invalid) {
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002797 createNullLocation(file, line, column, offset);
2798 return;
2799 }
2800
Douglas Gregor1db19de2010-01-19 21:36:55 +00002801 if (file)
Ted Kremenek9d5a1652011-03-23 02:16:44 +00002802 *file = (void *)SM.getFileEntryForSLocEntry(sloc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002803 if (line)
Chandler Carruth20174222011-08-31 16:53:37 +00002804 *line = SM.getExpansionLineNumber(ExpansionLoc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002805 if (column)
Chandler Carruth20174222011-08-31 16:53:37 +00002806 *column = SM.getExpansionColumnNumber(ExpansionLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002807 if (offset)
Chandler Carruth20174222011-08-31 16:53:37 +00002808 *offset = SM.getDecomposedLoc(ExpansionLoc).second;
2809}
2810
Argyrios Kyrtzidise6be34d2011-09-13 21:49:08 +00002811void clang_getPresumedLocation(CXSourceLocation location,
2812 CXString *filename,
2813 unsigned *line,
2814 unsigned *column) {
2815 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2816
2817 if (!location.ptr_data[0] || Loc.isInvalid()) {
2818 if (filename)
2819 *filename = createCXString("");
2820 if (line)
2821 *line = 0;
2822 if (column)
2823 *column = 0;
2824 }
2825 else {
2826 const SourceManager &SM =
2827 *static_cast<const SourceManager*>(location.ptr_data[0]);
2828 PresumedLoc PreLoc = SM.getPresumedLoc(Loc);
2829
2830 if (filename)
2831 *filename = createCXString(PreLoc.getFilename());
2832 if (line)
2833 *line = PreLoc.getLine();
2834 if (column)
2835 *column = PreLoc.getColumn();
2836 }
2837}
2838
Chandler Carruth20174222011-08-31 16:53:37 +00002839void clang_getInstantiationLocation(CXSourceLocation location,
2840 CXFile *file,
2841 unsigned *line,
2842 unsigned *column,
2843 unsigned *offset) {
2844 // Redirect to new API.
2845 clang_getExpansionLocation(location, file, line, column, offset);
Douglas Gregore69517c2010-01-26 03:07:15 +00002846}
2847
Douglas Gregora9b06d42010-11-09 06:24:54 +00002848void clang_getSpellingLocation(CXSourceLocation location,
2849 CXFile *file,
2850 unsigned *line,
2851 unsigned *column,
2852 unsigned *offset) {
2853 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2854
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002855 if (!location.ptr_data[0] || Loc.isInvalid())
2856 return createNullLocation(file, line, column, offset);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002857
2858 const SourceManager &SM =
2859 *static_cast<const SourceManager*>(location.ptr_data[0]);
2860 SourceLocation SpellLoc = Loc;
2861 if (SpellLoc.isMacroID()) {
2862 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2863 if (SimpleSpellingLoc.isFileID() &&
2864 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2865 SpellLoc = SimpleSpellingLoc;
2866 else
Chandler Carruth40278532011-07-25 16:49:02 +00002867 SpellLoc = SM.getExpansionLoc(SpellLoc);
Douglas Gregora9b06d42010-11-09 06:24:54 +00002868 }
2869
2870 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2871 FileID FID = LocInfo.first;
2872 unsigned FileOffset = LocInfo.second;
2873
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00002874 if (FID.isInvalid())
2875 return createNullLocation(file, line, column, offset);
2876
Douglas Gregora9b06d42010-11-09 06:24:54 +00002877 if (file)
2878 *file = (void *)SM.getFileEntryForID(FID);
2879 if (line)
2880 *line = SM.getLineNumber(FID, FileOffset);
2881 if (column)
2882 *column = SM.getColumnNumber(FID, FileOffset);
2883 if (offset)
2884 *offset = FileOffset;
2885}
2886
Douglas Gregor1db19de2010-01-19 21:36:55 +00002887CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002889 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002890 return Result;
2891}
2892
2893CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002894 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002895 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002896 return Result;
2897}
2898
Douglas Gregorb9790342010-01-22 21:44:22 +00002899} // end: extern "C"
2900
Douglas Gregor1db19de2010-01-19 21:36:55 +00002901//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002902// CXFile Operations.
2903//===----------------------------------------------------------------------===//
2904
2905extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002906CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002907 if (!SFile)
Ted Kremeneka60ed472010-11-16 08:15:36 +00002908 return createCXString((const char*)NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002909
Steve Naroff88145032009-10-27 14:35:18 +00002910 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002911 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002912}
2913
2914time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002915 if (!SFile)
2916 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002917
Steve Naroff88145032009-10-27 14:35:18 +00002918 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2919 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002920}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002921
Douglas Gregorb9790342010-01-22 21:44:22 +00002922CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2923 if (!tu)
2924 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002925
Ted Kremeneka60ed472010-11-16 08:15:36 +00002926 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002927
Douglas Gregorb9790342010-01-22 21:44:22 +00002928 FileManager &FMgr = CXXUnit->getFileManager();
Chris Lattner39b49bc2010-11-23 08:35:12 +00002929 return const_cast<FileEntry *>(FMgr.getFile(file_name));
Douglas Gregorb9790342010-01-22 21:44:22 +00002930}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002931
Douglas Gregordd3e5542011-05-04 00:14:37 +00002932unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2933 if (!tu || !file)
2934 return 0;
2935
2936 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2937 FileEntry *FEnt = static_cast<FileEntry *>(file);
2938 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2939 .isFileMultipleIncludeGuarded(FEnt);
2940}
2941
Ted Kremenekfb480492010-01-13 21:46:36 +00002942} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002943
Ted Kremenekfb480492010-01-13 21:46:36 +00002944//===----------------------------------------------------------------------===//
2945// CXCursor Operations.
2946//===----------------------------------------------------------------------===//
2947
Ted Kremenekfb480492010-01-13 21:46:36 +00002948static Decl *getDeclFromExpr(Stmt *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002949 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Douglas Gregordb1314e2010-10-01 21:11:22 +00002950 return getDeclFromExpr(CE->getSubExpr());
2951
Ted Kremenekfb480492010-01-13 21:46:36 +00002952 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2953 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002954 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2955 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002956 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2957 return ME->getMemberDecl();
2958 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2959 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002960 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
John McCall12f78a62010-12-02 01:19:52 +00002961 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0;
Douglas Gregordb1314e2010-10-01 21:11:22 +00002962
Ted Kremenekfb480492010-01-13 21:46:36 +00002963 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2964 return getDeclFromExpr(CE->getCallee());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002965 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Douglas Gregor93798e22010-11-05 21:11:19 +00002966 if (!CE->isElidable())
2967 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002968 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2969 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002970
Douglas Gregordb1314e2010-10-01 21:11:22 +00002971 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2972 return PE->getProtocol();
Douglas Gregorc7793c72011-01-15 01:15:58 +00002973 if (SubstNonTypeTemplateParmPackExpr *NTTP
2974 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2975 return NTTP->getParameterPack();
Douglas Gregor94d96292011-01-19 20:34:17 +00002976 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2977 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2978 isa<ParmVarDecl>(SizeOfPack->getPack()))
2979 return SizeOfPack->getPack();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002980
Ted Kremenekfb480492010-01-13 21:46:36 +00002981 return 0;
2982}
2983
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002984static SourceLocation getLocationFromExpr(Expr *E) {
Argyrios Kyrtzidisc2954612011-09-12 22:17:26 +00002985 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2986 return getLocationFromExpr(CE->getSubExpr());
2987
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002988 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2989 return /*FIXME:*/Msg->getLeftLoc();
2990 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2991 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002992 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2993 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002994 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2995 return Member->getMemberLoc();
2996 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2997 return Ivar->getLocation();
Douglas Gregor94d96292011-01-19 20:34:17 +00002998 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2999 return SizeOfPack->getPackLoc();
3000
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00003001 return E->getLocStart();
3002}
3003
Ted Kremenekfb480492010-01-13 21:46:36 +00003004extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003005
3006unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00003007 CXCursorVisitor visitor,
3008 CXClientData client_data) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003009 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
Douglas Gregor04a9eb32011-03-16 23:23:30 +00003010 false);
Douglas Gregorb1373d02010-01-20 20:59:29 +00003011 return CursorVis.VisitChildren(parent);
3012}
3013
David Chisnall3387c652010-11-03 14:12:26 +00003014#ifndef __has_feature
3015#define __has_feature(x) 0
3016#endif
3017#if __has_feature(blocks)
3018typedef enum CXChildVisitResult
3019 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3020
3021static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3022 CXClientData client_data) {
3023 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3024 return block(cursor, parent);
3025}
3026#else
3027// If we are compiled with a compiler that doesn't have native blocks support,
3028// define and call the block manually, so the
3029typedef struct _CXChildVisitResult
3030{
3031 void *isa;
3032 int flags;
3033 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003034 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3035 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00003036} *CXCursorVisitorBlock;
3037
3038static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3039 CXClientData client_data) {
3040 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3041 return block->invoke(block, cursor, parent);
3042}
3043#endif
3044
3045
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003046unsigned clang_visitChildrenWithBlock(CXCursor parent,
3047 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00003048 return clang_visitChildren(parent, visitWithBlock, block);
3049}
3050
Douglas Gregor78205d42010-01-20 21:45:58 +00003051static CXString getDeclSpelling(Decl *D) {
3052 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregore3c60a72010-11-17 00:13:31 +00003053 if (!ND) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003054 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003055 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3056 return createCXString(Property->getIdentifier()->getName());
3057
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003058 return createCXString("");
Douglas Gregore3c60a72010-11-17 00:13:31 +00003059 }
3060
Douglas Gregor78205d42010-01-20 21:45:58 +00003061 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003062 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003063
Douglas Gregor78205d42010-01-20 21:45:58 +00003064 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3065 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3066 // and returns different names. NamedDecl returns the class name and
3067 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003068 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003069
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003070 if (isa<UsingDirectiveDecl>(D))
3071 return createCXString("");
3072
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00003073 llvm::SmallString<1024> S;
3074 llvm::raw_svector_ostream os(S);
3075 ND->printName(os);
3076
3077 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00003078}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003079
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003080CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003081 if (clang_isTranslationUnit(C.kind))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003082 return clang_getTranslationUnitSpelling(
3083 static_cast<CXTranslationUnit>(C.data[2]));
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003084
Steve Narofff334b4e2009-09-02 18:26:48 +00003085 if (clang_isReference(C.kind)) {
3086 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00003087 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00003088 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003089 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003090 }
3091 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00003092 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003093 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003094 }
3095 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00003096 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00003097 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003098 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00003099 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00003100 case CXCursor_CXXBaseSpecifier: {
3101 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3102 return createCXString(B->getType().getAsString());
3103 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003104 case CXCursor_TypeRef: {
3105 TypeDecl *Type = getCursorTypeRef(C).first;
3106 assert(Type && "Missing type decl");
3107
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003108 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3109 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003110 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003111 case CXCursor_TemplateRef: {
3112 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00003113 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003114
3115 return createCXString(Template->getNameAsString());
3116 }
Douglas Gregor69319002010-08-31 23:48:11 +00003117
3118 case CXCursor_NamespaceRef: {
3119 NamedDecl *NS = getCursorNamespaceRef(C).first;
3120 assert(NS && "Missing namespace decl");
3121
3122 return createCXString(NS->getNameAsString());
3123 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003124
Douglas Gregora67e03f2010-09-09 21:42:20 +00003125 case CXCursor_MemberRef: {
3126 FieldDecl *Field = getCursorMemberRef(C).first;
3127 assert(Field && "Missing member decl");
3128
3129 return createCXString(Field->getNameAsString());
3130 }
3131
Douglas Gregor36897b02010-09-10 00:22:18 +00003132 case CXCursor_LabelRef: {
3133 LabelStmt *Label = getCursorLabelRef(C).first;
3134 assert(Label && "Missing label");
3135
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003136 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003137 }
3138
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003139 case CXCursor_OverloadedDeclRef: {
3140 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3141 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3142 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3143 return createCXString(ND->getNameAsString());
3144 return createCXString("");
3145 }
3146 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3147 return createCXString(E->getName().getAsString());
3148 OverloadedTemplateStorage *Ovl
3149 = Storage.get<OverloadedTemplateStorage*>();
3150 if (Ovl->size() == 0)
3151 return createCXString("");
3152 return createCXString((*Ovl->begin())->getNameAsString());
3153 }
3154
Daniel Dunbaracca7252009-11-30 20:42:49 +00003155 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003156 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00003157 }
3158 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003159
3160 if (clang_isExpression(C.kind)) {
3161 Decl *D = getDeclFromExpr(getCursorExpr(C));
3162 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00003163 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003164 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00003165 }
3166
Douglas Gregor36897b02010-09-10 00:22:18 +00003167 if (clang_isStatement(C.kind)) {
3168 Stmt *S = getCursorStmt(C);
3169 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003170 return createCXString(Label->getName());
Douglas Gregor36897b02010-09-10 00:22:18 +00003171
3172 return createCXString("");
3173 }
3174
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003175 if (C.kind == CXCursor_MacroExpansion)
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003176 return createCXString(getCursorMacroExpansion(C)->getName()
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003177 ->getNameStart());
3178
Douglas Gregor572feb22010-03-18 18:04:21 +00003179 if (C.kind == CXCursor_MacroDefinition)
3180 return createCXString(getCursorMacroDefinition(C)->getName()
3181 ->getNameStart());
3182
Douglas Gregorecdcb882010-10-20 22:00:55 +00003183 if (C.kind == CXCursor_InclusionDirective)
3184 return createCXString(getCursorInclusionDirective(C)->getFileName());
3185
Douglas Gregor60cbfac2010-01-25 16:56:17 +00003186 if (clang_isDeclaration(C.kind))
3187 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00003188
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003189 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00003190}
3191
Douglas Gregor358559d2010-10-02 22:49:11 +00003192CXString clang_getCursorDisplayName(CXCursor C) {
3193 if (!clang_isDeclaration(C.kind))
3194 return clang_getCursorSpelling(C);
3195
3196 Decl *D = getCursorDecl(C);
3197 if (!D)
3198 return createCXString("");
3199
3200 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
3201 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3202 D = FunTmpl->getTemplatedDecl();
3203
3204 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3205 llvm::SmallString<64> Str;
3206 llvm::raw_svector_ostream OS(Str);
3207 OS << Function->getNameAsString();
3208 if (Function->getPrimaryTemplate())
3209 OS << "<>";
3210 OS << "(";
3211 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3212 if (I)
3213 OS << ", ";
3214 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3215 }
3216
3217 if (Function->isVariadic()) {
3218 if (Function->getNumParams())
3219 OS << ", ";
3220 OS << "...";
3221 }
3222 OS << ")";
3223 return createCXString(OS.str());
3224 }
3225
3226 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3227 llvm::SmallString<64> Str;
3228 llvm::raw_svector_ostream OS(Str);
3229 OS << ClassTemplate->getNameAsString();
3230 OS << "<";
3231 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3232 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3233 if (I)
3234 OS << ", ";
3235
3236 NamedDecl *Param = Params->getParam(I);
3237 if (Param->getIdentifier()) {
3238 OS << Param->getIdentifier()->getName();
3239 continue;
3240 }
3241
3242 // There is no parameter name, which makes this tricky. Try to come up
3243 // with something useful that isn't too long.
3244 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3245 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3246 else if (NonTypeTemplateParmDecl *NTTP
3247 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3248 OS << NTTP->getType().getAsString(Policy);
3249 else
3250 OS << "template<...> class";
3251 }
3252
3253 OS << ">";
3254 return createCXString(OS.str());
3255 }
3256
3257 if (ClassTemplateSpecializationDecl *ClassSpec
3258 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3259 // If the type was explicitly written, use that.
3260 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3261 return createCXString(TSInfo->getType().getAsString(Policy));
3262
3263 llvm::SmallString<64> Str;
3264 llvm::raw_svector_ostream OS(Str);
3265 OS << ClassSpec->getNameAsString();
3266 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003267 ClassSpec->getTemplateArgs().data(),
3268 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00003269 Policy);
3270 return createCXString(OS.str());
3271 }
3272
3273 return clang_getCursorSpelling(C);
3274}
3275
Ted Kremeneke68fff62010-02-17 00:41:32 +00003276CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00003277 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003278 case CXCursor_FunctionDecl:
3279 return createCXString("FunctionDecl");
3280 case CXCursor_TypedefDecl:
3281 return createCXString("TypedefDecl");
3282 case CXCursor_EnumDecl:
3283 return createCXString("EnumDecl");
3284 case CXCursor_EnumConstantDecl:
3285 return createCXString("EnumConstantDecl");
3286 case CXCursor_StructDecl:
3287 return createCXString("StructDecl");
3288 case CXCursor_UnionDecl:
3289 return createCXString("UnionDecl");
3290 case CXCursor_ClassDecl:
3291 return createCXString("ClassDecl");
3292 case CXCursor_FieldDecl:
3293 return createCXString("FieldDecl");
3294 case CXCursor_VarDecl:
3295 return createCXString("VarDecl");
3296 case CXCursor_ParmDecl:
3297 return createCXString("ParmDecl");
3298 case CXCursor_ObjCInterfaceDecl:
3299 return createCXString("ObjCInterfaceDecl");
3300 case CXCursor_ObjCCategoryDecl:
3301 return createCXString("ObjCCategoryDecl");
3302 case CXCursor_ObjCProtocolDecl:
3303 return createCXString("ObjCProtocolDecl");
3304 case CXCursor_ObjCPropertyDecl:
3305 return createCXString("ObjCPropertyDecl");
3306 case CXCursor_ObjCIvarDecl:
3307 return createCXString("ObjCIvarDecl");
3308 case CXCursor_ObjCInstanceMethodDecl:
3309 return createCXString("ObjCInstanceMethodDecl");
3310 case CXCursor_ObjCClassMethodDecl:
3311 return createCXString("ObjCClassMethodDecl");
3312 case CXCursor_ObjCImplementationDecl:
3313 return createCXString("ObjCImplementationDecl");
3314 case CXCursor_ObjCCategoryImplDecl:
3315 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00003316 case CXCursor_CXXMethod:
3317 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003318 case CXCursor_UnexposedDecl:
3319 return createCXString("UnexposedDecl");
3320 case CXCursor_ObjCSuperClassRef:
3321 return createCXString("ObjCSuperClassRef");
3322 case CXCursor_ObjCProtocolRef:
3323 return createCXString("ObjCProtocolRef");
3324 case CXCursor_ObjCClassRef:
3325 return createCXString("ObjCClassRef");
3326 case CXCursor_TypeRef:
3327 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00003328 case CXCursor_TemplateRef:
3329 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00003330 case CXCursor_NamespaceRef:
3331 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00003332 case CXCursor_MemberRef:
3333 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00003334 case CXCursor_LabelRef:
3335 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003336 case CXCursor_OverloadedDeclRef:
3337 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003338 case CXCursor_UnexposedExpr:
3339 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00003340 case CXCursor_BlockExpr:
3341 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003342 case CXCursor_DeclRefExpr:
3343 return createCXString("DeclRefExpr");
3344 case CXCursor_MemberRefExpr:
3345 return createCXString("MemberRefExpr");
3346 case CXCursor_CallExpr:
3347 return createCXString("CallExpr");
3348 case CXCursor_ObjCMessageExpr:
3349 return createCXString("ObjCMessageExpr");
3350 case CXCursor_UnexposedStmt:
3351 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003352 case CXCursor_LabelStmt:
3353 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003354 case CXCursor_InvalidFile:
3355 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003356 case CXCursor_InvalidCode:
3357 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003358 case CXCursor_NoDeclFound:
3359 return createCXString("NoDeclFound");
3360 case CXCursor_NotImplemented:
3361 return createCXString("NotImplemented");
3362 case CXCursor_TranslationUnit:
3363 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003364 case CXCursor_UnexposedAttr:
3365 return createCXString("UnexposedAttr");
3366 case CXCursor_IBActionAttr:
3367 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003368 case CXCursor_IBOutletAttr:
3369 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003370 case CXCursor_IBOutletCollectionAttr:
3371 return createCXString("attribute(iboutletcollection)");
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003372 case CXCursor_CXXFinalAttr:
3373 return createCXString("attribute(final)");
3374 case CXCursor_CXXOverrideAttr:
3375 return createCXString("attribute(override)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003376 case CXCursor_PreprocessingDirective:
3377 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003378 case CXCursor_MacroDefinition:
3379 return createCXString("macro definition");
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003380 case CXCursor_MacroExpansion:
3381 return createCXString("macro expansion");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003382 case CXCursor_InclusionDirective:
3383 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003384 case CXCursor_Namespace:
3385 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003386 case CXCursor_LinkageSpec:
3387 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003388 case CXCursor_CXXBaseSpecifier:
3389 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003390 case CXCursor_Constructor:
3391 return createCXString("CXXConstructor");
3392 case CXCursor_Destructor:
3393 return createCXString("CXXDestructor");
3394 case CXCursor_ConversionFunction:
3395 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003396 case CXCursor_TemplateTypeParameter:
3397 return createCXString("TemplateTypeParameter");
3398 case CXCursor_NonTypeTemplateParameter:
3399 return createCXString("NonTypeTemplateParameter");
3400 case CXCursor_TemplateTemplateParameter:
3401 return createCXString("TemplateTemplateParameter");
3402 case CXCursor_FunctionTemplate:
3403 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003404 case CXCursor_ClassTemplate:
3405 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003406 case CXCursor_ClassTemplatePartialSpecialization:
3407 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003408 case CXCursor_NamespaceAlias:
3409 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003410 case CXCursor_UsingDirective:
3411 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003412 case CXCursor_UsingDeclaration:
3413 return createCXString("UsingDeclaration");
Richard Smith162e1c12011-04-15 14:24:37 +00003414 case CXCursor_TypeAliasDecl:
Douglas Gregor352697a2011-06-03 23:08:58 +00003415 return createCXString("TypeAliasDecl");
3416 case CXCursor_ObjCSynthesizeDecl:
3417 return createCXString("ObjCSynthesizeDecl");
3418 case CXCursor_ObjCDynamicDecl:
3419 return createCXString("ObjCDynamicDecl");
Steve Naroff89922f82009-08-31 00:59:03 +00003420 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003421
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003422 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneka60ed472010-11-16 08:15:36 +00003423 return createCXString((const char*) 0);
Steve Naroff600866c2009-08-27 19:51:58 +00003424}
Steve Naroff89922f82009-08-31 00:59:03 +00003425
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003426struct GetCursorData {
3427 SourceLocation TokenBeginLoc;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003428 bool PointsAtMacroArgExpansion;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003429 CXCursor &BestCursor;
3430
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003431 GetCursorData(SourceManager &SM,
3432 SourceLocation tokenBegin, CXCursor &outputCursor)
3433 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3434 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3435 }
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003436};
3437
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003438static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3439 CXCursor parent,
3440 CXClientData client_data) {
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003441 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3442 CXCursor *BestCursor = &Data->BestCursor;
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003443
3444 // If we point inside a macro argument we should provide info of what the
3445 // token is so use the actual cursor, don't replace it with a macro expansion
3446 // cursor.
3447 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3448 return CXChildVisit_Recurse;
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003449
3450 if (clang_isExpression(cursor.kind) &&
3451 clang_isDeclaration(BestCursor->kind)) {
3452 Decl *D = getCursorDecl(*BestCursor);
3453
3454 // Avoid having the cursor of an expression replace the declaration cursor
3455 // when the expression source range overlaps the declaration range.
3456 // This can happen for C++ constructor expressions whose range generally
3457 // include the variable declaration, e.g.:
3458 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3459 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3460 D->getLocation() == Data->TokenBeginLoc)
3461 return CXChildVisit_Break;
3462 }
3463
Douglas Gregor93798e22010-11-05 21:11:19 +00003464 // If our current best cursor is the construction of a temporary object,
3465 // don't replace that cursor with a type reference, because we want
3466 // clang_getCursor() to point at the constructor.
3467 if (clang_isExpression(BestCursor->kind) &&
3468 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3469 cursor.kind == CXCursor_TypeRef)
3470 return CXChildVisit_Recurse;
3471
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003472 *BestCursor = cursor;
3473 return CXChildVisit_Recurse;
3474}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003475
Douglas Gregorb9790342010-01-22 21:44:22 +00003476CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3477 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003478 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003479
Ted Kremeneka60ed472010-11-16 08:15:36 +00003480 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003481 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3482
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003483 // Translate the given source location to make it point at the beginning of
3484 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003485 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003486
3487 // Guard against an invalid SourceLocation, or we may assert in one
3488 // of the following calls.
3489 if (SLoc.isInvalid())
3490 return clang_getNullCursor();
3491
Douglas Gregor40749ee2010-11-03 00:35:38 +00003492 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003493 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3494 CXXUnit->getASTContext().getLangOptions());
3495
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003496 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3497 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003498 // FIXME: Would be great to have a "hint" cursor, then walk from that
3499 // hint cursor upward until we find a cursor whose source range encloses
3500 // the region of interest, rather than starting from the translation unit.
Argyrios Kyrtzidis4b43b302011-08-17 00:31:25 +00003501 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
Ted Kremeneka60ed472010-11-16 08:15:36 +00003502 CXCursor Parent = clang_getTranslationUnitCursor(TU);
Argyrios Kyrtzidis064c44b2011-06-27 19:42:23 +00003503 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00003504 /*VisitPreprocessorLast=*/true,
3505 SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003506 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003507 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003508
3509 if (Logging) {
3510 CXFile SearchFile;
3511 unsigned SearchLine, SearchColumn;
3512 CXFile ResultFile;
3513 unsigned ResultLine, ResultColumn;
Douglas Gregor66537982010-11-17 17:14:07 +00003514 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3515 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
Douglas Gregor40749ee2010-11-03 00:35:38 +00003516 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3517
Chandler Carruth20174222011-08-31 16:53:37 +00003518 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3519 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3520 &ResultColumn, 0);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003521 SearchFileName = clang_getFileName(SearchFile);
3522 ResultFileName = clang_getFileName(ResultFile);
3523 KindSpelling = clang_getCursorKindSpelling(Result.kind);
Douglas Gregor66537982010-11-17 17:14:07 +00003524 USR = clang_getCursorUSR(Result);
3525 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
Douglas Gregor40749ee2010-11-03 00:35:38 +00003526 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3527 clang_getCString(KindSpelling),
Douglas Gregor66537982010-11-17 17:14:07 +00003528 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3529 clang_getCString(USR), IsDef);
Douglas Gregor40749ee2010-11-03 00:35:38 +00003530 clang_disposeString(SearchFileName);
3531 clang_disposeString(ResultFileName);
3532 clang_disposeString(KindSpelling);
Douglas Gregor66537982010-11-17 17:14:07 +00003533 clang_disposeString(USR);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003534
3535 CXCursor Definition = clang_getCursorDefinition(Result);
3536 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3537 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3538 CXString DefinitionKindSpelling
3539 = clang_getCursorKindSpelling(Definition.kind);
3540 CXFile DefinitionFile;
3541 unsigned DefinitionLine, DefinitionColumn;
Chandler Carruth20174222011-08-31 16:53:37 +00003542 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3543 &DefinitionLine, &DefinitionColumn, 0);
Douglas Gregor0aefbd82010-12-10 01:45:00 +00003544 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3545 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3546 clang_getCString(DefinitionKindSpelling),
3547 clang_getCString(DefinitionFileName),
3548 DefinitionLine, DefinitionColumn);
3549 clang_disposeString(DefinitionFileName);
3550 clang_disposeString(DefinitionKindSpelling);
3551 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003552 }
3553
Ted Kremeneke68fff62010-02-17 00:41:32 +00003554 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003555}
3556
Ted Kremenek73885552009-11-17 19:28:59 +00003557CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003558 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003559}
3560
3561unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003562 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003563}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003564
Douglas Gregor9ce55842010-11-20 00:09:34 +00003565unsigned clang_hashCursor(CXCursor C) {
3566 unsigned Index = 0;
3567 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3568 Index = 1;
3569
3570 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3571 std::make_pair(C.kind, C.data[Index]));
3572}
3573
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003574unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003575 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3576}
3577
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003578unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003579 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3580}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003581
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003582unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003583 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3584}
3585
Douglas Gregor97b98722010-01-19 23:20:36 +00003586unsigned clang_isExpression(enum CXCursorKind K) {
3587 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3588}
3589
3590unsigned clang_isStatement(enum CXCursorKind K) {
3591 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3592}
3593
Douglas Gregor8be80e12011-07-06 03:00:34 +00003594unsigned clang_isAttribute(enum CXCursorKind K) {
3595 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3596}
3597
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003598unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3599 return K == CXCursor_TranslationUnit;
3600}
3601
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003602unsigned clang_isPreprocessing(enum CXCursorKind K) {
3603 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3604}
3605
Ted Kremenekad6eff62010-03-08 21:17:29 +00003606unsigned clang_isUnexposed(enum CXCursorKind K) {
3607 switch (K) {
3608 case CXCursor_UnexposedDecl:
3609 case CXCursor_UnexposedExpr:
3610 case CXCursor_UnexposedStmt:
3611 case CXCursor_UnexposedAttr:
3612 return true;
3613 default:
3614 return false;
3615 }
3616}
3617
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003618CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003619 return C.kind;
3620}
3621
Douglas Gregor98258af2010-01-18 22:46:11 +00003622CXSourceLocation clang_getCursorLocation(CXCursor C) {
3623 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003624 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003625 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003626 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3627 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003628 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003629 }
3630
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003631 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003632 std::pair<ObjCProtocolDecl *, SourceLocation> P
3633 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003634 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003635 }
3636
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003637 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003638 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3639 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003640 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003641 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003642
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003643 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003644 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003645 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003646 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003647
3648 case CXCursor_TemplateRef: {
3649 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3650 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3651 }
3652
Douglas Gregor69319002010-08-31 23:48:11 +00003653 case CXCursor_NamespaceRef: {
3654 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3655 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3656 }
3657
Douglas Gregora67e03f2010-09-09 21:42:20 +00003658 case CXCursor_MemberRef: {
3659 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3660 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3661 }
3662
Ted Kremenek3064ef92010-08-27 21:34:58 +00003663 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003664 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3665 if (!BaseSpec)
3666 return clang_getNullLocation();
3667
3668 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3669 return cxloc::translateSourceLocation(getCursorContext(C),
3670 TSInfo->getTypeLoc().getBeginLoc());
3671
3672 return cxloc::translateSourceLocation(getCursorContext(C),
3673 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003674 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003675
Douglas Gregor36897b02010-09-10 00:22:18 +00003676 case CXCursor_LabelRef: {
3677 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3678 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3679 }
3680
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003681 case CXCursor_OverloadedDeclRef:
3682 return cxloc::translateSourceLocation(getCursorContext(C),
3683 getCursorOverloadedDeclRef(C).second);
3684
Douglas Gregorf46034a2010-01-18 23:41:10 +00003685 default:
3686 // FIXME: Need a way to enumerate all non-reference cases.
3687 llvm_unreachable("Missed a reference kind");
3688 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003689 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003690
3691 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003692 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003693 getLocationFromExpr(getCursorExpr(C)));
3694
Douglas Gregor36897b02010-09-10 00:22:18 +00003695 if (clang_isStatement(C.kind))
3696 return cxloc::translateSourceLocation(getCursorContext(C),
3697 getCursorStmt(C)->getLocStart());
3698
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003699 if (C.kind == CXCursor_PreprocessingDirective) {
3700 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3701 return cxloc::translateSourceLocation(getCursorContext(C), L);
3702 }
Douglas Gregor48072312010-03-18 15:23:44 +00003703
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003704 if (C.kind == CXCursor_MacroExpansion) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003705 SourceLocation L
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003706 = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003707 return cxloc::translateSourceLocation(getCursorContext(C), L);
3708 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003709
3710 if (C.kind == CXCursor_MacroDefinition) {
3711 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3712 return cxloc::translateSourceLocation(getCursorContext(C), L);
3713 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003714
3715 if (C.kind == CXCursor_InclusionDirective) {
3716 SourceLocation L
3717 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3718 return cxloc::translateSourceLocation(getCursorContext(C), L);
3719 }
3720
Ted Kremenek9a700d22010-05-12 06:16:13 +00003721 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003722 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003723
Douglas Gregorf46034a2010-01-18 23:41:10 +00003724 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003725 SourceLocation Loc = D->getLocation();
3726 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3727 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003728 // FIXME: Multiple variables declared in a single declaration
3729 // currently lack the information needed to correctly determine their
3730 // ranges when accounting for the type-specifier. We use context
3731 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3732 // and if so, whether it is the first decl.
3733 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3734 if (!cxcursor::isFirstInDeclGroup(C))
3735 Loc = VD->getLocation();
3736 }
3737
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003738 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003739}
Douglas Gregora7bde202010-01-19 00:34:46 +00003740
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003741} // end extern "C"
3742
3743static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003744 if (clang_isReference(C.kind)) {
3745 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003746 case CXCursor_ObjCSuperClassRef:
3747 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003748
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003749 case CXCursor_ObjCProtocolRef:
3750 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003751
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003752 case CXCursor_ObjCClassRef:
3753 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003754
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003755 case CXCursor_TypeRef:
3756 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003757
3758 case CXCursor_TemplateRef:
3759 return getCursorTemplateRef(C).second;
3760
Douglas Gregor69319002010-08-31 23:48:11 +00003761 case CXCursor_NamespaceRef:
3762 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003763
3764 case CXCursor_MemberRef:
3765 return getCursorMemberRef(C).second;
3766
Ted Kremenek3064ef92010-08-27 21:34:58 +00003767 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003768 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003769
Douglas Gregor36897b02010-09-10 00:22:18 +00003770 case CXCursor_LabelRef:
3771 return getCursorLabelRef(C).second;
3772
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003773 case CXCursor_OverloadedDeclRef:
3774 return getCursorOverloadedDeclRef(C).second;
3775
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003776 default:
3777 // FIXME: Need a way to enumerate all non-reference cases.
3778 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003779 }
3780 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003781
3782 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003783 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003784
3785 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003786 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003787
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00003788 if (clang_isAttribute(C.kind))
3789 return getCursorAttr(C)->getRange();
3790
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003791 if (C.kind == CXCursor_PreprocessingDirective)
3792 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003793
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003794 if (C.kind == CXCursor_MacroExpansion) {
3795 ASTUnit *TU = getCursorASTUnit(C);
3796 SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
3797 return TU->mapRangeFromPreamble(Range);
3798 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003799
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003800 if (C.kind == CXCursor_MacroDefinition) {
3801 ASTUnit *TU = getCursorASTUnit(C);
3802 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3803 return TU->mapRangeFromPreamble(Range);
3804 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003805
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003806 if (C.kind == CXCursor_InclusionDirective) {
3807 ASTUnit *TU = getCursorASTUnit(C);
3808 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3809 return TU->mapRangeFromPreamble(Range);
3810 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003811
Ted Kremenek007a7c92010-11-01 23:26:51 +00003812 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3813 Decl *D = cxcursor::getCursorDecl(C);
3814 SourceRange R = D->getSourceRange();
3815 // FIXME: Multiple variables declared in a single declaration
3816 // currently lack the information needed to correctly determine their
3817 // ranges when accounting for the type-specifier. We use context
3818 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3819 // and if so, whether it is the first decl.
3820 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3821 if (!cxcursor::isFirstInDeclGroup(C))
3822 R.setBegin(VD->getLocation());
3823 }
3824 return R;
3825 }
Douglas Gregor66537982010-11-17 17:14:07 +00003826 return SourceRange();
3827}
3828
3829/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3830/// the decl-specifier-seq for declarations.
3831static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3832 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3833 Decl *D = cxcursor::getCursorDecl(C);
3834 SourceRange R = D->getSourceRange();
Douglas Gregor66537982010-11-17 17:14:07 +00003835
Douglas Gregor2494dd02011-03-01 01:34:45 +00003836 // Adjust the start of the location for declarations preceded by
3837 // declaration specifiers.
3838 SourceLocation StartLoc;
3839 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3840 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
3841 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3842 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
3843 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
3844 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
3845 }
3846
3847 if (StartLoc.isValid() && R.getBegin().isValid() &&
3848 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
3849 R.setBegin(StartLoc);
3850
3851 // FIXME: Multiple variables declared in a single declaration
3852 // currently lack the information needed to correctly determine their
3853 // ranges when accounting for the type-specifier. We use context
3854 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3855 // and if so, whether it is the first decl.
3856 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3857 if (!cxcursor::isFirstInDeclGroup(C))
3858 R.setBegin(VD->getLocation());
Douglas Gregor66537982010-11-17 17:14:07 +00003859 }
3860
3861 return R;
3862 }
3863
3864 return getRawCursorExtent(C);
3865}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003866
3867extern "C" {
3868
3869CXSourceRange clang_getCursorExtent(CXCursor C) {
3870 SourceRange R = getRawCursorExtent(C);
3871 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003872 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003873
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003874 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003875}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003876
3877CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003878 if (clang_isInvalid(C.kind))
3879 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003880
Ted Kremeneka60ed472010-11-16 08:15:36 +00003881 CXTranslationUnit tu = getCursorTU(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003882 if (clang_isDeclaration(C.kind)) {
3883 Decl *D = getCursorDecl(C);
3884 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003885 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003886 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003887 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003888 if (ObjCForwardProtocolDecl *Protocols
3889 = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003890 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003891 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
Douglas Gregore3c60a72010-11-17 00:13:31 +00003892 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3893 return MakeCXCursor(Property, tu);
3894
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003895 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003896 }
3897
Douglas Gregor97b98722010-01-19 23:20:36 +00003898 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003899 Expr *E = getCursorExpr(C);
3900 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003901 if (D)
Ted Kremeneka60ed472010-11-16 08:15:36 +00003902 return MakeCXCursor(D, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003903
3904 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Ted Kremeneka60ed472010-11-16 08:15:36 +00003905 return MakeCursorOverloadedDeclRef(Ovl, tu);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003906
Douglas Gregor97b98722010-01-19 23:20:36 +00003907 return clang_getNullCursor();
3908 }
3909
Douglas Gregor36897b02010-09-10 00:22:18 +00003910 if (clang_isStatement(C.kind)) {
3911 Stmt *S = getCursorStmt(C);
3912 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Ted Kremenek37c2e962011-03-15 23:47:49 +00003913 if (LabelDecl *label = Goto->getLabel())
3914 if (LabelStmt *labelS = label->getStmt())
3915 return MakeCXCursor(labelS, getCursorDecl(C), tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003916
3917 return clang_getNullCursor();
3918 }
3919
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003920 if (C.kind == CXCursor_MacroExpansion) {
Chandler Carruth9e5bb852011-07-14 08:20:46 +00003921 if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00003922 return MakeMacroDefinitionCursor(Def, tu);
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003923 }
3924
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003925 if (!clang_isReference(C.kind))
3926 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003927
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003928 switch (C.kind) {
3929 case CXCursor_ObjCSuperClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003930 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003931
3932 case CXCursor_ObjCProtocolRef: {
Ted Kremeneka60ed472010-11-16 08:15:36 +00003933 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003934
3935 case CXCursor_ObjCClassRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003936 return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003937
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003938 case CXCursor_TypeRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003939 return MakeCXCursor(getCursorTypeRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003940
3941 case CXCursor_TemplateRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003942 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
Douglas Gregor0b36e612010-08-31 20:37:03 +00003943
Douglas Gregor69319002010-08-31 23:48:11 +00003944 case CXCursor_NamespaceRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003945 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
Douglas Gregor69319002010-08-31 23:48:11 +00003946
Douglas Gregora67e03f2010-09-09 21:42:20 +00003947 case CXCursor_MemberRef:
Ted Kremeneka60ed472010-11-16 08:15:36 +00003948 return MakeCXCursor(getCursorMemberRef(C).first, tu );
Douglas Gregora67e03f2010-09-09 21:42:20 +00003949
Ted Kremenek3064ef92010-08-27 21:34:58 +00003950 case CXCursor_CXXBaseSpecifier: {
3951 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3952 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00003953 tu ));
Ted Kremenek3064ef92010-08-27 21:34:58 +00003954 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003955
Douglas Gregor36897b02010-09-10 00:22:18 +00003956 case CXCursor_LabelRef:
3957 // FIXME: We end up faking the "parent" declaration here because we
3958 // don't want to make CXCursor larger.
3959 return MakeCXCursor(getCursorLabelRef(C).first,
Ted Kremeneka60ed472010-11-16 08:15:36 +00003960 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3961 .getTranslationUnitDecl(),
3962 tu);
Douglas Gregor36897b02010-09-10 00:22:18 +00003963
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003964 case CXCursor_OverloadedDeclRef:
3965 return C;
3966
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003967 default:
3968 // We would prefer to enumerate all non-reference cursor kinds here.
3969 llvm_unreachable("Unhandled reference cursor kind");
3970 break;
3971 }
3972 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003973
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003974 return clang_getNullCursor();
3975}
3976
Douglas Gregorb6998662010-01-19 19:34:47 +00003977CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003978 if (clang_isInvalid(C.kind))
3979 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003980
Ted Kremeneka60ed472010-11-16 08:15:36 +00003981 CXTranslationUnit TU = getCursorTU(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003982
Douglas Gregorb6998662010-01-19 19:34:47 +00003983 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003984 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003985 C = clang_getCursorReferenced(C);
3986 WasReference = true;
3987 }
3988
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00003989 if (C.kind == CXCursor_MacroExpansion)
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003990 return clang_getCursorReferenced(C);
3991
Douglas Gregorb6998662010-01-19 19:34:47 +00003992 if (!clang_isDeclaration(C.kind))
3993 return clang_getNullCursor();
3994
3995 Decl *D = getCursorDecl(C);
3996 if (!D)
3997 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003998
Douglas Gregorb6998662010-01-19 19:34:47 +00003999 switch (D->getKind()) {
4000 // Declaration kinds that don't really separate the notions of
4001 // declaration and definition.
4002 case Decl::Namespace:
4003 case Decl::Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +00004004 case Decl::TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +00004005 case Decl::TypeAliasTemplate:
Douglas Gregorb6998662010-01-19 19:34:47 +00004006 case Decl::TemplateTypeParm:
4007 case Decl::EnumConstant:
4008 case Decl::Field:
Benjamin Kramerd9811462010-11-21 14:11:41 +00004009 case Decl::IndirectField:
Douglas Gregorb6998662010-01-19 19:34:47 +00004010 case Decl::ObjCIvar:
4011 case Decl::ObjCAtDefsField:
4012 case Decl::ImplicitParam:
4013 case Decl::ParmVar:
4014 case Decl::NonTypeTemplateParm:
4015 case Decl::TemplateTemplateParm:
4016 case Decl::ObjCCategoryImpl:
4017 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00004018 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00004019 case Decl::LinkageSpec:
4020 case Decl::ObjCPropertyImpl:
4021 case Decl::FileScopeAsm:
4022 case Decl::StaticAssert:
4023 case Decl::Block:
Chris Lattnerad8dcf42011-02-17 07:39:24 +00004024 case Decl::Label: // FIXME: Is this right??
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004025 case Decl::ClassScopeFunctionSpecialization:
Douglas Gregorb6998662010-01-19 19:34:47 +00004026 return C;
4027
4028 // Declaration kinds that don't make any sense here, but are
4029 // nonetheless harmless.
4030 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00004031 break;
4032
4033 // Declaration kinds for which the definition is not resolvable.
4034 case Decl::UnresolvedUsingTypename:
4035 case Decl::UnresolvedUsingValue:
4036 break;
4037
4038 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00004039 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004040 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004041
4042 case Decl::NamespaceAlias:
Ted Kremeneka60ed472010-11-16 08:15:36 +00004043 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004044
4045 case Decl::Enum:
4046 case Decl::Record:
4047 case Decl::CXXRecord:
4048 case Decl::ClassTemplateSpecialization:
4049 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00004050 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004051 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004052 return clang_getNullCursor();
4053
4054 case Decl::Function:
4055 case Decl::CXXMethod:
4056 case Decl::CXXConstructor:
4057 case Decl::CXXDestructor:
4058 case Decl::CXXConversion: {
4059 const FunctionDecl *Def = 0;
4060 if (cast<FunctionDecl>(D)->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004061 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004062 return clang_getNullCursor();
4063 }
4064
4065 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00004066 // Ask the variable if it has a definition.
4067 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004068 return MakeCXCursor(Def, TU);
Sebastian Redl31310a22010-02-01 20:16:42 +00004069 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00004070 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004071
Douglas Gregorb6998662010-01-19 19:34:47 +00004072 case Decl::FunctionTemplate: {
4073 const FunctionDecl *Def = 0;
4074 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004075 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004076 return clang_getNullCursor();
4077 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004078
Douglas Gregorb6998662010-01-19 19:34:47 +00004079 case Decl::ClassTemplate: {
4080 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00004081 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00004082 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004083 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004084 return clang_getNullCursor();
4085 }
4086
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004087 case Decl::Using:
4088 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004089 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004090
4091 case Decl::UsingShadow:
4092 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004093 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004094 TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004095
4096 case Decl::ObjCMethod: {
4097 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4098 if (Method->isThisDeclarationADefinition())
4099 return C;
4100
4101 // Dig out the method definition in the associated
4102 // @implementation, if we have it.
4103 // FIXME: The ASTs should make finding the definition easier.
4104 if (ObjCInterfaceDecl *Class
4105 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4106 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4107 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4108 Method->isInstanceMethod()))
4109 if (Def->isThisDeclarationADefinition())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004110 return MakeCXCursor(Def, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004111
4112 return clang_getNullCursor();
4113 }
4114
4115 case Decl::ObjCCategory:
4116 if (ObjCCategoryImplDecl *Impl
4117 = cast<ObjCCategoryDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004118 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004119 return clang_getNullCursor();
4120
4121 case Decl::ObjCProtocol:
4122 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
4123 return C;
4124 return clang_getNullCursor();
4125
4126 case Decl::ObjCInterface:
4127 // There are two notions of a "definition" for an Objective-C
4128 // class: the interface and its implementation. When we resolved a
4129 // reference to an Objective-C class, produce the @interface as
4130 // the definition; when we were provided with the interface,
4131 // produce the @implementation as the definition.
4132 if (WasReference) {
4133 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
4134 return C;
4135 } else if (ObjCImplementationDecl *Impl
4136 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004137 return MakeCXCursor(Impl, TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004138 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004139
Douglas Gregorb6998662010-01-19 19:34:47 +00004140 case Decl::ObjCProperty:
4141 // FIXME: We don't really know where to find the
4142 // ObjCPropertyImplDecls that implement this property.
4143 return clang_getNullCursor();
4144
4145 case Decl::ObjCCompatibleAlias:
4146 if (ObjCInterfaceDecl *Class
4147 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4148 if (!Class->isForwardDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004149 return MakeCXCursor(Class, TU);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004150
Douglas Gregorb6998662010-01-19 19:34:47 +00004151 return clang_getNullCursor();
4152
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004153 case Decl::ObjCForwardProtocol:
4154 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004155 D->getLocation(), TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004156
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004157 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004158 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004159 TU);
Douglas Gregorb6998662010-01-19 19:34:47 +00004160
4161 case Decl::Friend:
4162 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004163 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004164 return clang_getNullCursor();
4165
4166 case Decl::FriendTemplate:
4167 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004168 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
Douglas Gregorb6998662010-01-19 19:34:47 +00004169 return clang_getNullCursor();
4170 }
4171
4172 return clang_getNullCursor();
4173}
4174
4175unsigned clang_isCursorDefinition(CXCursor C) {
4176 if (!clang_isDeclaration(C.kind))
4177 return 0;
4178
4179 return clang_getCursorDefinition(C) == C;
4180}
4181
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004182CXCursor clang_getCanonicalCursor(CXCursor C) {
4183 if (!clang_isDeclaration(C.kind))
4184 return C;
4185
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004186 if (Decl *D = getCursorDecl(C)) {
Argyrios Kyrtzidisdebb00f2011-07-15 22:37:58 +00004187 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4188 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4189 return MakeCXCursor(CatD, getCursorTU(C));
4190
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004191 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4192 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4193 return MakeCXCursor(IFD, getCursorTU(C));
4194
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004195 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
Argyrios Kyrtzidise2f854d2011-07-15 22:27:18 +00004196 }
Douglas Gregor1a9d0502010-11-19 23:44:15 +00004197
4198 return C;
4199}
4200
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004201unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004202 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004203 return 0;
4204
4205 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4206 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4207 return E->getNumDecls();
4208
4209 if (OverloadedTemplateStorage *S
4210 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4211 return S->size();
4212
4213 Decl *D = Storage.get<Decl*>();
4214 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00004215 return Using->shadow_size();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004216 if (isa<ObjCClassDecl>(D))
4217 return 1;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004218 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
4219 return Protocols->protocol_size();
4220
4221 return 0;
4222}
4223
4224CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00004225 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004226 return clang_getNullCursor();
4227
4228 if (index >= clang_getNumOverloadedDecls(cursor))
4229 return clang_getNullCursor();
4230
Ted Kremeneka60ed472010-11-16 08:15:36 +00004231 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004232 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4233 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004234 return MakeCXCursor(E->decls_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004235
4236 if (OverloadedTemplateStorage *S
4237 = Storage.dyn_cast<OverloadedTemplateStorage*>())
Ted Kremeneka60ed472010-11-16 08:15:36 +00004238 return MakeCXCursor(S->begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004239
4240 Decl *D = Storage.get<Decl*>();
4241 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4242 // FIXME: This is, unfortunately, linear time.
4243 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4244 std::advance(Pos, index);
Ted Kremeneka60ed472010-11-16 08:15:36 +00004245 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004246 }
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004247 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00004248 return MakeCXCursor(Classes->getForwardInterfaceDecl(), TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004249 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
Ted Kremeneka60ed472010-11-16 08:15:36 +00004250 return MakeCXCursor(Protocols->protocol_begin()[index], TU);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00004251
4252 return clang_getNullCursor();
4253}
4254
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00004255void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00004256 const char **startBuf,
4257 const char **endBuf,
4258 unsigned *startLine,
4259 unsigned *startColumn,
4260 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00004261 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00004262 assert(getCursorDecl(C) && "CXCursor has null decl");
4263 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00004264 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4265 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004266
Steve Naroff4ade6d62009-09-23 17:52:52 +00004267 SourceManager &SM = FD->getASTContext().getSourceManager();
4268 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4269 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4270 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4271 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4272 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4273 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4274}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004275
Douglas Gregor430d7a12011-07-25 17:48:11 +00004276
4277CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4278 unsigned PieceIndex) {
4279 RefNamePieces Pieces;
4280
4281 switch (C.kind) {
4282 case CXCursor_MemberRefExpr:
4283 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4284 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4285 E->getQualifierLoc().getSourceRange());
4286 break;
4287
4288 case CXCursor_DeclRefExpr:
4289 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4290 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4291 E->getQualifierLoc().getSourceRange(),
4292 E->getExplicitTemplateArgsOpt());
4293 break;
4294
4295 case CXCursor_CallExpr:
4296 if (CXXOperatorCallExpr *OCE =
4297 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4298 Expr *Callee = OCE->getCallee();
4299 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4300 Callee = ICE->getSubExpr();
4301
4302 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4303 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4304 DRE->getQualifierLoc().getSourceRange());
4305 }
4306 break;
4307
4308 default:
4309 break;
4310 }
4311
4312 if (Pieces.empty()) {
4313 if (PieceIndex == 0)
4314 return clang_getCursorExtent(C);
4315 } else if (PieceIndex < Pieces.size()) {
4316 SourceRange R = Pieces[PieceIndex];
4317 if (R.isValid())
4318 return cxloc::translateSourceRange(getCursorContext(C), R);
4319 }
4320
4321 return clang_getNullRange();
4322}
4323
Douglas Gregor0a812cf2010-02-18 23:07:20 +00004324void clang_enableStackTraces(void) {
4325 llvm::sys::PrintStackTraceOnErrorSignal();
4326}
4327
Daniel Dunbar995aaf92010-11-04 01:26:29 +00004328void clang_executeOnThread(void (*fn)(void*), void *user_data,
4329 unsigned stack_size) {
4330 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4331}
4332
Ted Kremenekfb480492010-01-13 21:46:36 +00004333} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00004334
Ted Kremenekfb480492010-01-13 21:46:36 +00004335//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004336// Token-based Operations.
4337//===----------------------------------------------------------------------===//
4338
4339/* CXToken layout:
4340 * int_data[0]: a CXTokenKind
4341 * int_data[1]: starting token location
4342 * int_data[2]: token length
4343 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004344 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004345 * otherwise unused.
4346 */
4347extern "C" {
4348
4349CXTokenKind clang_getTokenKind(CXToken CXTok) {
4350 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4351}
4352
4353CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4354 switch (clang_getTokenKind(CXTok)) {
4355 case CXToken_Identifier:
4356 case CXToken_Keyword:
4357 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004358 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4359 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004360
4361 case CXToken_Literal: {
4362 // We have stashed the starting pointer in the ptr_data field. Use it.
4363 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004364 return createCXString(StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004365 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004366
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004367 case CXToken_Punctuation:
4368 case CXToken_Comment:
4369 break;
4370 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004371
4372 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004373 // deconstructing the source location.
Ted Kremeneka60ed472010-11-16 08:15:36 +00004374 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004375 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004376 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004377
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004378 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4379 std::pair<FileID, unsigned> LocInfo
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004380 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00004381 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004382 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004383 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4384 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00004385 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004386
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004387 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004388}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004389
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004390CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004391 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004392 if (!CXXUnit)
4393 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004394
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004395 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4396 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4397}
4398
4399CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004400 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor5352ac02010-01-28 00:27:43 +00004401 if (!CXXUnit)
4402 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004403
4404 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004405 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4406}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004407
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004408static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4409 SmallVectorImpl<CXToken> &CXTokens) {
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004410 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4411 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004412 = SourceMgr.getDecomposedLoc(Range.getBegin());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004413 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004414 = SourceMgr.getDecomposedLoc(Range.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004415
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004416 // Cannot tokenize across files.
4417 if (BeginLocInfo.first != EndLocInfo.first)
4418 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004419
4420 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004421 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004422 StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00004423 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00004424 if (Invalid)
4425 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00004426
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004427 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4428 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004429 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004430 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004431
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004432 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00004433 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004434 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00004435 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004436 do {
4437 // Lex the next token
4438 Lex.LexFromRawLexer(Tok);
4439 if (Tok.is(tok::eof))
4440 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004441
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004442 // Initialize the CXToken.
4443 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004444
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004445 // - Common fields
4446 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4447 CXTok.int_data[2] = Tok.getLength();
4448 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004449
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004450 // - Kind-specific fields
4451 if (Tok.isLiteral()) {
4452 CXTok.int_data[0] = CXToken_Literal;
4453 CXTok.ptr_data = (void *)Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004454 } else if (Tok.is(tok::raw_identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00004455 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004456 IdentifierInfo *II
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004457 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004458
David Chisnall096428b2010-10-13 21:44:48 +00004459 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004460 CXTok.int_data[0] = CXToken_Keyword;
4461 }
4462 else {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00004463 CXTok.int_data[0] = Tok.is(tok::identifier)
4464 ? CXToken_Identifier
4465 : CXToken_Keyword;
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00004466 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004467 CXTok.ptr_data = II;
4468 } else if (Tok.is(tok::comment)) {
4469 CXTok.int_data[0] = CXToken_Comment;
4470 CXTok.ptr_data = 0;
4471 } else {
4472 CXTok.int_data[0] = CXToken_Punctuation;
4473 CXTok.ptr_data = 0;
4474 }
4475 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00004476 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004477 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004478}
4479
4480void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4481 CXToken **Tokens, unsigned *NumTokens) {
4482 if (Tokens)
4483 *Tokens = 0;
4484 if (NumTokens)
4485 *NumTokens = 0;
4486
4487 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4488 if (!CXXUnit || !Tokens || !NumTokens)
4489 return;
4490
4491 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4492
4493 SourceRange R = cxloc::translateCXSourceRange(Range);
4494 if (R.isInvalid())
4495 return;
4496
4497 SmallVector<CXToken, 32> CXTokens;
4498 getTokens(CXXUnit, R, CXTokens);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004499
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004500 if (CXTokens.empty())
4501 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004502
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004503 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4504 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4505 *NumTokens = CXTokens.size();
4506}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004507
Ted Kremenek6db61092010-05-05 00:55:15 +00004508void clang_disposeTokens(CXTranslationUnit TU,
4509 CXToken *Tokens, unsigned NumTokens) {
4510 free(Tokens);
4511}
4512
4513} // end: extern "C"
4514
4515//===----------------------------------------------------------------------===//
4516// Token annotation APIs.
4517//===----------------------------------------------------------------------===//
4518
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004519typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004520static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4521 CXCursor parent,
4522 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00004523namespace {
4524class AnnotateTokensWorker {
4525 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004526 CXToken *Tokens;
4527 CXCursor *Cursors;
4528 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004529 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00004530 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004531 CursorVisitor AnnotateVis;
4532 SourceManager &SrcMgr;
Douglas Gregorf5251602011-03-08 17:10:18 +00004533 bool HasContextSensitiveKeywords;
4534
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004535 bool MoreTokens() const { return TokIdx < NumTokens; }
4536 unsigned NextToken() const { return TokIdx; }
4537 void AdvanceToken() { ++TokIdx; }
4538 SourceLocation GetTokenLoc(unsigned tokI) {
4539 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4540 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004541 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004542 return Tokens[tokI].int_data[3] != 0;
4543 }
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004544 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004545 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4546 }
4547
4548 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004549 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4550 SourceRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004551
Ted Kremenek6db61092010-05-05 00:55:15 +00004552public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00004553 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004554 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Ted Kremeneka60ed472010-11-16 08:15:36 +00004555 CXTranslationUnit tu, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00004556 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00004557 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremeneka60ed472010-11-16 08:15:36 +00004558 AnnotateVis(tu,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00004559 AnnotateTokensVisitor, this, true, RegionOfInterest),
Douglas Gregorf5251602011-03-08 17:10:18 +00004560 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4561 HasContextSensitiveKeywords(false) { }
Ted Kremenek11949cb2010-05-05 00:55:17 +00004562
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004563 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004564 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004565 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004566 void AnnotateTokens() {
Ted Kremeneka60ed472010-11-16 08:15:36 +00004567 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
Ted Kremenekab979612010-11-11 08:05:23 +00004568 }
Douglas Gregorf5251602011-03-08 17:10:18 +00004569
4570 /// \brief Determine whether the annotator saw any cursors that have
4571 /// context-sensitive keywords.
4572 bool hasContextSensitiveKeywords() const {
4573 return HasContextSensitiveKeywords;
4574 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004575};
4576}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004577
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004578void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4579 // Walk the AST within the region of interest, annotating tokens
4580 // along the way.
4581 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004582
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004583 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4584 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004585 if (Pos != Annotated.end() &&
4586 (clang_isInvalid(Cursors[I].kind) ||
4587 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004588 Cursors[I] = Pos->second;
4589 }
4590
4591 // Finish up annotating any tokens left.
4592 if (!MoreTokens())
4593 return;
4594
4595 const CXCursor &C = clang_getNullCursor();
4596 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4597 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4598 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004599 }
4600}
4601
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004602/// \brief It annotates and advances tokens with a cursor until the comparison
4603//// between the cursor location and the source range is the same as
4604/// \arg compResult.
4605///
4606/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4607/// Pass RangeOverlap to annotate tokens inside a range.
4608void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4609 RangeComparisonResult compResult,
4610 SourceRange range) {
4611 while (MoreTokens()) {
4612 const unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004613 if (isFunctionMacroToken(I))
4614 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004615
4616 SourceLocation TokLoc = GetTokenLoc(I);
4617 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4618 Cursors[I] = updateC;
4619 AdvanceToken();
4620 continue;
4621 }
4622 break;
4623 }
4624}
4625
4626/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004627void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4628 CXCursor updateC,
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004629 RangeComparisonResult compResult,
4630 SourceRange range) {
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004631 assert(MoreTokens());
4632 assert(isFunctionMacroToken(NextToken()) &&
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004633 "Should be called only for macro arg tokens");
4634
4635 // This works differently than annotateAndAdvanceTokens; because expanded
4636 // macro arguments can have arbitrary translation-unit source order, we do not
4637 // advance the token index one by one until a token fails the range test.
4638 // We only advance once past all of the macro arg tokens if all of them
4639 // pass the range test. If one of them fails we keep the token index pointing
4640 // at the start of the macro arg tokens so that the failing token will be
4641 // annotated by a subsequent annotation try.
4642
4643 bool atLeastOneCompFail = false;
4644
4645 unsigned I = NextToken();
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004646 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4647 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004648 if (TokLoc.isFileID())
4649 continue; // not macro arg token, it's parens or comma.
4650 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4651 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4652 Cursors[I] = updateC;
4653 } else
4654 atLeastOneCompFail = true;
4655 }
4656
4657 if (!atLeastOneCompFail)
4658 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4659}
4660
Ted Kremenek6db61092010-05-05 00:55:15 +00004661enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004662AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004663 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004664 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004665 if (cursorRange.isInvalid())
4666 return CXChildVisit_Recurse;
Douglas Gregorf5251602011-03-08 17:10:18 +00004667
4668 if (!HasContextSensitiveKeywords) {
4669 // Objective-C properties can have context-sensitive keywords.
4670 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4671 if (ObjCPropertyDecl *Property
4672 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4673 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4674 }
4675 // Objective-C methods can have context-sensitive keywords.
4676 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4677 cursor.kind == CXCursor_ObjCClassMethodDecl) {
4678 if (ObjCMethodDecl *Method
4679 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4680 if (Method->getObjCDeclQualifier())
4681 HasContextSensitiveKeywords = true;
4682 else {
4683 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4684 PEnd = Method->param_end();
4685 P != PEnd; ++P) {
4686 if ((*P)->getObjCDeclQualifier()) {
4687 HasContextSensitiveKeywords = true;
4688 break;
4689 }
4690 }
4691 }
4692 }
4693 }
4694 // C++ methods can have context-sensitive keywords.
4695 else if (cursor.kind == CXCursor_CXXMethod) {
4696 if (CXXMethodDecl *Method
4697 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4698 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4699 HasContextSensitiveKeywords = true;
4700 }
4701 }
4702 // C++ classes can have context-sensitive keywords.
4703 else if (cursor.kind == CXCursor_StructDecl ||
4704 cursor.kind == CXCursor_ClassDecl ||
4705 cursor.kind == CXCursor_ClassTemplate ||
4706 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4707 if (Decl *D = getCursorDecl(cursor))
4708 if (D->hasAttr<FinalAttr>())
4709 HasContextSensitiveKeywords = true;
4710 }
4711 }
4712
Douglas Gregor4419b672010-10-21 06:10:04 +00004713 if (clang_isPreprocessing(cursor.kind)) {
Chandler Carruthcea731a2011-07-14 16:07:57 +00004714 // For macro expansions, just note where the beginning of the macro
4715 // expansion occurs.
Chandler Carruth9b2a0ac2011-07-14 08:41:15 +00004716 if (cursor.kind == CXCursor_MacroExpansion) {
Douglas Gregor4419b672010-10-21 06:10:04 +00004717 Annotated[Loc.int_data] = cursor;
4718 return CXChildVisit_Recurse;
4719 }
4720
Douglas Gregor4419b672010-10-21 06:10:04 +00004721 // Items in the preprocessing record are kept separate from items in
4722 // declarations, so we keep a separate token index.
4723 unsigned SavedTokIdx = TokIdx;
4724 TokIdx = PreprocessingTokIdx;
4725
4726 // Skip tokens up until we catch up to the beginning of the preprocessing
4727 // entry.
4728 while (MoreTokens()) {
4729 const unsigned I = NextToken();
4730 SourceLocation TokLoc = GetTokenLoc(I);
4731 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4732 case RangeBefore:
4733 AdvanceToken();
4734 continue;
4735 case RangeAfter:
4736 case RangeOverlap:
4737 break;
4738 }
4739 break;
4740 }
4741
4742 // Look at all of the tokens within this range.
4743 while (MoreTokens()) {
4744 const unsigned I = NextToken();
4745 SourceLocation TokLoc = GetTokenLoc(I);
4746 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4747 case RangeBefore:
David Blaikieb219cfc2011-09-23 05:06:16 +00004748 llvm_unreachable("Infeasible");
Douglas Gregor4419b672010-10-21 06:10:04 +00004749 case RangeAfter:
4750 break;
4751 case RangeOverlap:
4752 Cursors[I] = cursor;
4753 AdvanceToken();
4754 continue;
4755 }
4756 break;
4757 }
4758
4759 // Save the preprocessing token index; restore the non-preprocessing
4760 // token index.
4761 PreprocessingTokIdx = TokIdx;
4762 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004763 return CXChildVisit_Recurse;
4764 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004765
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004766 if (cursorRange.isInvalid())
4767 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004768
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004769 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4770
Ted Kremeneka333c662010-05-12 05:29:33 +00004771 // Adjust the annotated range based specific declarations.
4772 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4773 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004774 Decl *D = cxcursor::getCursorDecl(cursor);
Douglas Gregor2494dd02011-03-01 01:34:45 +00004775
4776 SourceLocation StartLoc;
Ted Kremenek23173d72010-05-18 21:09:07 +00004777 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00004778 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4779 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
4780 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4781 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4782 StartLoc = TI->getTypeLoc().getSourceRange().getBegin();
Ted Kremeneka333c662010-05-12 05:29:33 +00004783 }
Douglas Gregor2494dd02011-03-01 01:34:45 +00004784
4785 if (StartLoc.isValid() && L.isValid() &&
4786 SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
4787 cursorRange.setBegin(StartLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004788 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004789
Ted Kremenek3f404602010-08-14 01:14:06 +00004790 // If the location of the cursor occurs within a macro instantiation, record
4791 // the spelling location of the cursor in our annotation map. We can then
4792 // paper over the token labelings during a post-processing step to try and
4793 // get cursor mappings for tokens that are the *arguments* of a macro
4794 // instantiation.
4795 if (L.isMacroID()) {
4796 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4797 // Only invalidate the old annotation if it isn't part of a preprocessing
4798 // directive. Here we assume that the default construction of CXCursor
4799 // results in CXCursor.kind being an initialized value (i.e., 0). If
4800 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004801
Ted Kremenek3f404602010-08-14 01:14:06 +00004802 CXCursor &oldC = Annotated[rawEncoding];
4803 if (!clang_isPreprocessing(oldC.kind))
4804 oldC = cursor;
4805 }
4806
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004807 const enum CXCursorKind K = clang_getCursorKind(parent);
4808 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004809 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4810 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004811
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004812 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004813
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004814 // Avoid having the cursor of an expression "overwrite" the annotation of the
4815 // variable declaration that it belongs to.
4816 // This can happen for C++ constructor expressions whose range generally
4817 // include the variable declaration, e.g.:
4818 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
4819 if (clang_isExpression(cursorK)) {
4820 Expr *E = getCursorExpr(cursor);
Argyrios Kyrtzidis8ccac3d2011-06-29 22:20:07 +00004821 if (Decl *D = getCursorParentDecl(cursor)) {
Argyrios Kyrtzidis5517b892011-06-27 19:42:20 +00004822 const unsigned I = NextToken();
4823 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
4824 E->getLocStart() == D->getLocation() &&
4825 E->getLocStart() == GetTokenLoc(I)) {
4826 Cursors[I] = updateC;
4827 AdvanceToken();
4828 }
4829 }
4830 }
4831
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004832 // Visit children to get their cursor information.
4833 const unsigned BeforeChildren = NextToken();
4834 VisitChildren(cursor);
4835 const unsigned AfterChildren = NextToken();
4836
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004837 // Scan the tokens that are at the end of the cursor, but are not captured
4838 // but the child cursors.
4839 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
Ted Kremenek6db61092010-05-05 00:55:15 +00004840
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004841 // Scan the tokens that are at the beginning of the cursor, but are not
4842 // capture by the child cursors.
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004843 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4844 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4845 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004846
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004847 Cursors[I] = cursor;
4848 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004849
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004850 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004851}
4852
Ted Kremenek6db61092010-05-05 00:55:15 +00004853static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4854 CXCursor parent,
4855 CXClientData client_data) {
4856 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4857}
4858
Ted Kremenek6628a612011-03-18 22:51:30 +00004859namespace {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004860
4861/// \brief Uses the macro expansions in the preprocessing record to find
4862/// and mark tokens that are macro arguments. This info is used by the
4863/// AnnotateTokensWorker.
4864class MarkMacroArgTokensVisitor {
4865 SourceManager &SM;
4866 CXToken *Tokens;
4867 unsigned NumTokens;
4868 unsigned CurIdx;
4869
4870public:
4871 MarkMacroArgTokensVisitor(SourceManager &SM,
4872 CXToken *tokens, unsigned numTokens)
4873 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
4874
4875 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
4876 if (cursor.kind != CXCursor_MacroExpansion)
4877 return CXChildVisit_Continue;
4878
4879 SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
4880 if (macroRange.getBegin() == macroRange.getEnd())
4881 return CXChildVisit_Continue; // it's not a function macro.
4882
4883 for (; CurIdx < NumTokens; ++CurIdx) {
4884 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
4885 macroRange.getBegin()))
4886 break;
4887 }
4888
4889 if (CurIdx == NumTokens)
4890 return CXChildVisit_Break;
4891
4892 for (; CurIdx < NumTokens; ++CurIdx) {
4893 SourceLocation tokLoc = getTokenLoc(CurIdx);
4894 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
4895 break;
4896
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004897 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004898 }
4899
4900 if (CurIdx == NumTokens)
4901 return CXChildVisit_Break;
4902
4903 return CXChildVisit_Continue;
4904 }
4905
4906private:
4907 SourceLocation getTokenLoc(unsigned tokI) {
4908 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4909 }
4910
Argyrios Kyrtzidis5f616b72011-08-30 19:43:19 +00004911 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00004912 // The third field is reserved and currently not used. Use it here
4913 // to mark macro arg expanded tokens with their expanded locations.
4914 Tokens[tokI].int_data[3] = loc.getRawEncoding();
4915 }
4916};
4917
4918} // end anonymous namespace
4919
4920static CXChildVisitResult
4921MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
4922 CXClientData client_data) {
4923 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
4924 parent);
4925}
4926
4927namespace {
Ted Kremenek6628a612011-03-18 22:51:30 +00004928 struct clang_annotateTokens_Data {
4929 CXTranslationUnit TU;
4930 ASTUnit *CXXUnit;
4931 CXToken *Tokens;
4932 unsigned NumTokens;
4933 CXCursor *Cursors;
4934 };
4935}
4936
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00004937static void annotatePreprocessorTokens(CXTranslationUnit TU,
4938 SourceRange RegionOfInterest,
4939 AnnotateTokensData &Annotated) {
4940 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4941
4942 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4943 std::pair<FileID, unsigned> BeginLocInfo
4944 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4945 std::pair<FileID, unsigned> EndLocInfo
4946 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4947
4948 if (BeginLocInfo.first != EndLocInfo.first)
4949 return;
4950
4951 StringRef Buffer;
4952 bool Invalid = false;
4953 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4954 if (Buffer.empty() || Invalid)
4955 return;
4956
4957 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4958 CXXUnit->getASTContext().getLangOptions(),
4959 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4960 Buffer.end());
4961 Lex.SetCommentRetentionState(true);
4962
4963 // Lex tokens in raw mode until we hit the end of the range, to avoid
4964 // entering #includes or expanding macros.
4965 while (true) {
4966 Token Tok;
4967 Lex.LexFromRawLexer(Tok);
4968
4969 reprocess:
4970 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4971 // We have found a preprocessing directive. Gobble it up so that we
4972 // don't see it while preprocessing these tokens later, but keep track
4973 // of all of the token locations inside this preprocessing directive so
4974 // that we can annotate them appropriately.
4975 //
4976 // FIXME: Some simple tests here could identify macro definitions and
4977 // #undefs, to provide specific cursor kinds for those.
4978 SmallVector<SourceLocation, 32> Locations;
4979 do {
4980 Locations.push_back(Tok.getLocation());
4981 Lex.LexFromRawLexer(Tok);
4982 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4983
4984 using namespace cxcursor;
4985 CXCursor Cursor
4986 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4987 Locations.back()),
4988 TU);
4989 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4990 Annotated[Locations[I].getRawEncoding()] = Cursor;
4991 }
4992
4993 if (Tok.isAtStartOfLine())
4994 goto reprocess;
4995
4996 continue;
4997 }
4998
4999 if (Tok.is(tok::eof))
5000 break;
5001 }
5002}
5003
Ted Kremenekab979612010-11-11 08:05:23 +00005004// This gets run a separate thread to avoid stack blowout.
Ted Kremenek6628a612011-03-18 22:51:30 +00005005static void clang_annotateTokensImpl(void *UserData) {
5006 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5007 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5008 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5009 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5010 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5011
5012 // Determine the region of interest, which contains all of the tokens.
5013 SourceRange RegionOfInterest;
5014 RegionOfInterest.setBegin(
5015 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5016 RegionOfInterest.setEnd(
5017 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5018 Tokens[NumTokens-1])));
5019
5020 // A mapping from the source locations found when re-lexing or traversing the
5021 // region of interest to the corresponding cursors.
5022 AnnotateTokensData Annotated;
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005023
Ted Kremenek6628a612011-03-18 22:51:30 +00005024 // Relex the tokens within the source range to look for preprocessing
5025 // directives.
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00005026 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
Ted Kremenek6628a612011-03-18 22:51:30 +00005027
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005028 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5029 // Search and mark tokens that are macro argument expansions.
5030 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5031 Tokens, NumTokens);
5032 CursorVisitor MacroArgMarker(TU,
5033 MarkMacroArgTokensVisitorDelegate, &Visitor,
Douglas Gregor08e0bc12011-09-10 00:09:20 +00005034 true, RegionOfInterest);
Argyrios Kyrtzidisa6763792011-08-18 18:03:34 +00005035 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5036 }
5037
Ted Kremenek6628a612011-03-18 22:51:30 +00005038 // Annotate all of the source locations in the region of interest that map to
5039 // a specific cursor.
5040 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5041 TU, RegionOfInterest);
5042
5043 // FIXME: We use a ridiculous stack size here because the data-recursion
5044 // algorithm uses a large stack frame than the non-data recursive version,
5045 // and AnnotationTokensWorker currently transforms the data-recursion
5046 // algorithm back into a traditional recursion by explicitly calling
5047 // VisitChildren(). We will need to remove this explicit recursive call.
5048 W.AnnotateTokens();
5049
5050 // If we ran into any entities that involve context-sensitive keywords,
5051 // take another pass through the tokens to mark them as such.
5052 if (W.hasContextSensitiveKeywords()) {
5053 for (unsigned I = 0; I != NumTokens; ++I) {
5054 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5055 continue;
5056
5057 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5058 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5059 if (ObjCPropertyDecl *Property
5060 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5061 if (Property->getPropertyAttributesAsWritten() != 0 &&
5062 llvm::StringSwitch<bool>(II->getName())
5063 .Case("readonly", true)
5064 .Case("assign", true)
John McCallf85e1932011-06-15 23:02:42 +00005065 .Case("unsafe_unretained", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005066 .Case("readwrite", true)
5067 .Case("retain", true)
5068 .Case("copy", true)
5069 .Case("nonatomic", true)
5070 .Case("atomic", true)
5071 .Case("getter", true)
5072 .Case("setter", true)
John McCallf85e1932011-06-15 23:02:42 +00005073 .Case("strong", true)
5074 .Case("weak", true)
Ted Kremenek6628a612011-03-18 22:51:30 +00005075 .Default(false))
5076 Tokens[I].int_data[0] = CXToken_Keyword;
5077 }
5078 continue;
5079 }
5080
5081 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5082 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5083 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5084 if (llvm::StringSwitch<bool>(II->getName())
5085 .Case("in", true)
5086 .Case("out", true)
5087 .Case("inout", true)
5088 .Case("oneway", true)
5089 .Case("bycopy", true)
5090 .Case("byref", true)
5091 .Default(false))
5092 Tokens[I].int_data[0] = CXToken_Keyword;
5093 continue;
5094 }
Argyrios Kyrtzidis6639e922011-09-13 17:39:31 +00005095
5096 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5097 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5098 Tokens[I].int_data[0] = CXToken_Keyword;
Ted Kremenek6628a612011-03-18 22:51:30 +00005099 continue;
5100 }
5101 }
5102 }
Ted Kremenekab979612010-11-11 08:05:23 +00005103}
5104
Ted Kremenek6db61092010-05-05 00:55:15 +00005105extern "C" {
5106
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005107void clang_annotateTokens(CXTranslationUnit TU,
5108 CXToken *Tokens, unsigned NumTokens,
5109 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005110
5111 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005112 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005113
Douglas Gregor4419b672010-10-21 06:10:04 +00005114 // Any token we don't specifically annotate will have a NULL cursor.
5115 CXCursor C = clang_getNullCursor();
5116 for (unsigned I = 0; I != NumTokens; ++I)
5117 Cursors[I] = C;
5118
Ted Kremeneka60ed472010-11-16 08:15:36 +00005119 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor4419b672010-10-21 06:10:04 +00005120 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00005121 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00005122
Douglas Gregorbdf60622010-03-05 21:16:25 +00005123 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek6628a612011-03-18 22:51:30 +00005124
5125 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
Ted Kremenekab979612010-11-11 08:05:23 +00005126 llvm::CrashRecoveryContext CRC;
Ted Kremenek6628a612011-03-18 22:51:30 +00005127 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005128 GetSafetyThreadStackSize() * 2)) {
Ted Kremenekab979612010-11-11 08:05:23 +00005129 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5130 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005131}
Ted Kremenek6628a612011-03-18 22:51:30 +00005132
Douglas Gregorfc8ea232010-01-26 17:06:03 +00005133} // end: extern "C"
5134
5135//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00005136// Operations for querying linkage of a cursor.
5137//===----------------------------------------------------------------------===//
5138
5139extern "C" {
5140CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00005141 if (!clang_isDeclaration(cursor.kind))
5142 return CXLinkage_Invalid;
5143
Ted Kremenek16b42592010-03-03 06:36:57 +00005144 Decl *D = cxcursor::getCursorDecl(cursor);
5145 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5146 switch (ND->getLinkage()) {
5147 case NoLinkage: return CXLinkage_NoLinkage;
5148 case InternalLinkage: return CXLinkage_Internal;
5149 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5150 case ExternalLinkage: return CXLinkage_External;
5151 };
5152
5153 return CXLinkage_Invalid;
5154}
5155} // end: extern "C"
5156
5157//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005158// Operations for querying language of a cursor.
5159//===----------------------------------------------------------------------===//
5160
5161static CXLanguageKind getDeclLanguage(const Decl *D) {
5162 switch (D->getKind()) {
5163 default:
5164 break;
5165 case Decl::ImplicitParam:
5166 case Decl::ObjCAtDefsField:
5167 case Decl::ObjCCategory:
5168 case Decl::ObjCCategoryImpl:
5169 case Decl::ObjCClass:
5170 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005171 case Decl::ObjCForwardProtocol:
5172 case Decl::ObjCImplementation:
5173 case Decl::ObjCInterface:
5174 case Decl::ObjCIvar:
5175 case Decl::ObjCMethod:
5176 case Decl::ObjCProperty:
5177 case Decl::ObjCPropertyImpl:
5178 case Decl::ObjCProtocol:
5179 return CXLanguage_ObjC;
5180 case Decl::CXXConstructor:
5181 case Decl::CXXConversion:
5182 case Decl::CXXDestructor:
5183 case Decl::CXXMethod:
5184 case Decl::CXXRecord:
5185 case Decl::ClassTemplate:
5186 case Decl::ClassTemplatePartialSpecialization:
5187 case Decl::ClassTemplateSpecialization:
5188 case Decl::Friend:
5189 case Decl::FriendTemplate:
5190 case Decl::FunctionTemplate:
5191 case Decl::LinkageSpec:
5192 case Decl::Namespace:
5193 case Decl::NamespaceAlias:
5194 case Decl::NonTypeTemplateParm:
5195 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005196 case Decl::TemplateTemplateParm:
5197 case Decl::TemplateTypeParm:
5198 case Decl::UnresolvedUsingTypename:
5199 case Decl::UnresolvedUsingValue:
5200 case Decl::Using:
5201 case Decl::UsingDirective:
5202 case Decl::UsingShadow:
5203 return CXLanguage_CPlusPlus;
5204 }
5205
5206 return CXLanguage_C;
5207}
5208
5209extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00005210
5211enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5212 if (clang_isDeclaration(cursor.kind))
5213 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005214 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Douglas Gregor58ddb602010-08-23 23:00:57 +00005215 return CXAvailability_Available;
5216
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005217 switch (D->getAvailability()) {
5218 case AR_Available:
5219 case AR_NotYetIntroduced:
5220 return CXAvailability_Available;
5221
5222 case AR_Deprecated:
Douglas Gregor58ddb602010-08-23 23:00:57 +00005223 return CXAvailability_Deprecated;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005224
5225 case AR_Unavailable:
5226 return CXAvailability_NotAvailable;
5227 }
Douglas Gregor58ddb602010-08-23 23:00:57 +00005228 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00005229
Douglas Gregor58ddb602010-08-23 23:00:57 +00005230 return CXAvailability_Available;
5231}
5232
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005233CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5234 if (clang_isDeclaration(cursor.kind))
5235 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5236
5237 return CXLanguage_Invalid;
5238}
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005239
5240 /// \brief If the given cursor is the "templated" declaration
5241 /// descibing a class or function template, return the class or
5242 /// function template.
5243static Decl *maybeGetTemplateCursor(Decl *D) {
5244 if (!D)
5245 return 0;
5246
5247 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5248 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5249 return FunTmpl;
5250
5251 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5252 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5253 return ClassTmpl;
5254
5255 return D;
5256}
5257
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005258CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5259 if (clang_isDeclaration(cursor.kind)) {
5260 if (Decl *D = getCursorDecl(cursor)) {
5261 DeclContext *DC = D->getDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005262 if (!DC)
5263 return clang_getNullCursor();
5264
5265 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5266 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005267 }
5268 }
5269
5270 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5271 if (Decl *D = getCursorDecl(cursor))
Ted Kremeneka60ed472010-11-16 08:15:36 +00005272 return MakeCXCursor(D, getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005273 }
5274
5275 return clang_getNullCursor();
5276}
5277
5278CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5279 if (clang_isDeclaration(cursor.kind)) {
5280 if (Decl *D = getCursorDecl(cursor)) {
5281 DeclContext *DC = D->getLexicalDeclContext();
Douglas Gregor3910cfd2010-12-21 07:55:45 +00005282 if (!DC)
5283 return clang_getNullCursor();
5284
5285 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5286 getCursorTU(cursor));
Douglas Gregor2be5bc92010-09-22 21:22:29 +00005287 }
5288 }
5289
5290 // FIXME: Note that we can't easily compute the lexical context of a
5291 // statement or expression, so we return nothing.
5292 return clang_getNullCursor();
5293}
5294
Douglas Gregor9f592342010-10-01 20:25:15 +00005295static void CollectOverriddenMethods(DeclContext *Ctx,
5296 ObjCMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005297 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
Douglas Gregor9f592342010-10-01 20:25:15 +00005298 if (!Ctx)
5299 return;
5300
5301 // If we have a class or category implementation, jump straight to the
5302 // interface.
5303 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
5304 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
5305
5306 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
5307 if (!Container)
5308 return;
5309
5310 // Check whether we have a matching method at this level.
5311 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
5312 Method->isInstanceMethod()))
5313 if (Method != Overridden) {
5314 // We found an override at this level; there is no need to look
5315 // into other protocols or categories.
5316 Methods.push_back(Overridden);
5317 return;
5318 }
5319
5320 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5321 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
5322 PEnd = Protocol->protocol_end();
5323 P != PEnd; ++P)
5324 CollectOverriddenMethods(*P, Method, Methods);
5325 }
5326
5327 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5328 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
5329 PEnd = Category->protocol_end();
5330 P != PEnd; ++P)
5331 CollectOverriddenMethods(*P, Method, Methods);
5332 }
5333
5334 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
5335 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
5336 PEnd = Interface->protocol_end();
5337 P != PEnd; ++P)
5338 CollectOverriddenMethods(*P, Method, Methods);
5339
5340 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
5341 Category; Category = Category->getNextClassCategory())
5342 CollectOverriddenMethods(Category, Method, Methods);
5343
5344 // We only look into the superclass if we haven't found anything yet.
5345 if (Methods.empty())
5346 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
5347 return CollectOverriddenMethods(Super, Method, Methods);
5348 }
5349}
5350
5351void clang_getOverriddenCursors(CXCursor cursor,
5352 CXCursor **overridden,
5353 unsigned *num_overridden) {
5354 if (overridden)
5355 *overridden = 0;
5356 if (num_overridden)
5357 *num_overridden = 0;
5358 if (!overridden || !num_overridden)
5359 return;
5360
5361 if (!clang_isDeclaration(cursor.kind))
5362 return;
5363
5364 Decl *D = getCursorDecl(cursor);
5365 if (!D)
5366 return;
5367
5368 // Handle C++ member functions.
Ted Kremeneka60ed472010-11-16 08:15:36 +00005369 CXTranslationUnit TU = getCursorTU(cursor);
Douglas Gregor9f592342010-10-01 20:25:15 +00005370 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
5371 *num_overridden = CXXMethod->size_overridden_methods();
5372 if (!*num_overridden)
5373 return;
5374
5375 *overridden = new CXCursor [*num_overridden];
5376 unsigned I = 0;
5377 for (CXXMethodDecl::method_iterator
5378 M = CXXMethod->begin_overridden_methods(),
5379 MEnd = CXXMethod->end_overridden_methods();
5380 M != MEnd; (void)++M, ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005381 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005382 return;
5383 }
5384
5385 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
5386 if (!Method)
5387 return;
5388
5389 // Handle Objective-C methods.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005390 SmallVector<ObjCMethodDecl *, 4> Methods;
Douglas Gregor9f592342010-10-01 20:25:15 +00005391 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
5392
5393 if (Methods.empty())
5394 return;
5395
5396 *num_overridden = Methods.size();
5397 *overridden = new CXCursor [Methods.size()];
5398 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005399 (*overridden)[I] = MakeCXCursor(Methods[I], TU);
Douglas Gregor9f592342010-10-01 20:25:15 +00005400}
5401
5402void clang_disposeOverriddenCursors(CXCursor *overridden) {
5403 delete [] overridden;
5404}
5405
Douglas Gregorecdcb882010-10-20 22:00:55 +00005406CXFile clang_getIncludedFile(CXCursor cursor) {
5407 if (cursor.kind != CXCursor_InclusionDirective)
5408 return 0;
5409
5410 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5411 return (void *)ID->getFile();
5412}
5413
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005414} // end: extern "C"
5415
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005416
5417//===----------------------------------------------------------------------===//
5418// C++ AST instrospection.
5419//===----------------------------------------------------------------------===//
5420
5421extern "C" {
5422unsigned clang_CXXMethod_isStatic(CXCursor C) {
5423 if (!clang_isDeclaration(C.kind))
5424 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00005425
5426 CXXMethodDecl *Method = 0;
5427 Decl *D = cxcursor::getCursorDecl(C);
5428 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5429 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5430 else
5431 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5432 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00005433}
Ted Kremenekb12903e2010-05-18 22:32:15 +00005434
Douglas Gregor211924b2011-05-12 15:17:24 +00005435unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5436 if (!clang_isDeclaration(C.kind))
5437 return 0;
5438
5439 CXXMethodDecl *Method = 0;
5440 Decl *D = cxcursor::getCursorDecl(C);
5441 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5442 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5443 else
5444 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5445 return (Method && Method->isVirtual()) ? 1 : 0;
5446}
Ted Kremenek9ada39a2010-05-17 20:06:56 +00005447} // end: extern "C"
5448
Ted Kremenek45e1dae2010-04-12 21:22:16 +00005449//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00005450// Attribute introspection.
5451//===----------------------------------------------------------------------===//
5452
5453extern "C" {
5454CXType clang_getIBOutletCollectionType(CXCursor C) {
5455 if (C.kind != CXCursor_IBOutletCollectionAttr)
Ted Kremeneka60ed472010-11-16 08:15:36 +00005456 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005457
5458 IBOutletCollectionAttr *A =
5459 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5460
Argyrios Kyrtzidis18aa2ff2011-09-13 18:49:52 +00005461 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
Ted Kremenek95f33552010-08-26 01:42:22 +00005462}
5463} // end: extern "C"
5464
5465//===----------------------------------------------------------------------===//
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005466// Inspecting memory usage.
5467//===----------------------------------------------------------------------===//
5468
Ted Kremenekf7870022011-04-20 16:41:07 +00005469typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005470
Ted Kremenekf7870022011-04-20 16:41:07 +00005471static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5472 enum CXTUResourceUsageKind k,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005473 unsigned long amount) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005474 CXTUResourceUsageEntry entry = { k, amount };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005475 entries.push_back(entry);
5476}
5477
5478extern "C" {
5479
Ted Kremenekf7870022011-04-20 16:41:07 +00005480const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005481 const char *str = "";
5482 switch (kind) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005483 case CXTUResourceUsage_AST:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005484 str = "ASTContext: expressions, declarations, and types";
5485 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005486 case CXTUResourceUsage_Identifiers:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005487 str = "ASTContext: identifiers";
5488 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005489 case CXTUResourceUsage_Selectors:
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005490 str = "ASTContext: selectors";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005491 break;
Ted Kremenekf7870022011-04-20 16:41:07 +00005492 case CXTUResourceUsage_GlobalCompletionResults:
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005493 str = "Code completion: cached global results";
Ted Kremeneke294ab72011-04-19 04:36:17 +00005494 break;
Ted Kremenek457aaf02011-04-28 04:10:31 +00005495 case CXTUResourceUsage_SourceManagerContentCache:
5496 str = "SourceManager: content cache allocator";
5497 break;
Ted Kremenekba29bd22011-04-28 04:53:38 +00005498 case CXTUResourceUsage_AST_SideTables:
5499 str = "ASTContext: side tables";
5500 break;
Ted Kremenekf61b8312011-04-28 20:36:42 +00005501 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5502 str = "SourceManager: malloc'ed memory buffers";
5503 break;
5504 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5505 str = "SourceManager: mmap'ed memory buffers";
5506 break;
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005507 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5508 str = "ExternalASTSource: malloc'ed memory buffers";
5509 break;
5510 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5511 str = "ExternalASTSource: mmap'ed memory buffers";
5512 break;
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005513 case CXTUResourceUsage_Preprocessor:
5514 str = "Preprocessor: malloc'ed memory";
5515 break;
5516 case CXTUResourceUsage_PreprocessingRecord:
5517 str = "Preprocessor: PreprocessingRecord";
5518 break;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005519 case CXTUResourceUsage_SourceManager_DataStructures:
5520 str = "SourceManager: data structures and tables";
5521 break;
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005522 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5523 str = "Preprocessor: header search tables";
5524 break;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005525 }
5526 return str;
5527}
5528
Ted Kremenekf7870022011-04-20 16:41:07 +00005529CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005530 if (!TU) {
Ted Kremenekf7870022011-04-20 16:41:07 +00005531 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005532 return usage;
5533 }
5534
5535 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5536 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5537 ASTContext &astContext = astUnit->getASTContext();
5538
5539 // How much memory is used by AST nodes and types?
Ted Kremenekf7870022011-04-20 16:41:07 +00005540 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
Ted Kremenekba29bd22011-04-28 04:53:38 +00005541 (unsigned long) astContext.getASTAllocatedMemory());
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005542
5543 // How much memory is used by identifiers?
Ted Kremenekf7870022011-04-20 16:41:07 +00005544 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005545 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5546
5547 // How much memory is used for selectors?
Ted Kremenekf7870022011-04-20 16:41:07 +00005548 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005549 (unsigned long) astContext.Selectors.getTotalMemory());
5550
Ted Kremenekba29bd22011-04-28 04:53:38 +00005551 // How much memory is used by ASTContext's side tables?
5552 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5553 (unsigned long) astContext.getSideTableAllocatedMemory());
5554
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005555 // How much memory is used for caching global code completion results?
5556 unsigned long completionBytes = 0;
5557 if (GlobalCodeCompletionAllocator *completionAllocator =
5558 astUnit->getCachedCompletionAllocator().getPtr()) {
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005559 completionBytes = completionAllocator->getTotalMemory();
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00005560 }
Ted Kremenek457aaf02011-04-28 04:10:31 +00005561 createCXTUResourceUsageEntry(*entries,
5562 CXTUResourceUsage_GlobalCompletionResults,
5563 completionBytes);
5564
5565 // How much memory is being used by SourceManager's content cache?
5566 createCXTUResourceUsageEntry(*entries,
5567 CXTUResourceUsage_SourceManagerContentCache,
5568 (unsigned long) astContext.getSourceManager().getContentCacheSize());
Ted Kremenekf61b8312011-04-28 20:36:42 +00005569
5570 // How much memory is being used by the MemoryBuffer's in SourceManager?
5571 const SourceManager::MemoryBufferSizes &srcBufs =
5572 astUnit->getSourceManager().getMemoryBufferSizes();
5573
5574 createCXTUResourceUsageEntry(*entries,
5575 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5576 (unsigned long) srcBufs.malloc_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005577 createCXTUResourceUsageEntry(*entries,
Ted Kremenekf61b8312011-04-28 20:36:42 +00005578 CXTUResourceUsage_SourceManager_Membuffer_MMap,
5579 (unsigned long) srcBufs.mmap_bytes);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00005580 createCXTUResourceUsageEntry(*entries,
5581 CXTUResourceUsage_SourceManager_DataStructures,
5582 (unsigned long) astContext.getSourceManager()
5583 .getDataStructureSizes());
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005584
5585 // How much memory is being used by the ExternalASTSource?
5586 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5587 const ExternalASTSource::MemoryBufferSizes &sizes =
5588 esrc->getMemoryBufferSizes();
5589
5590 createCXTUResourceUsageEntry(*entries,
5591 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5592 (unsigned long) sizes.malloc_bytes);
5593 createCXTUResourceUsageEntry(*entries,
5594 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5595 (unsigned long) sizes.mmap_bytes);
5596 }
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005597
5598 // How much memory is being used by the Preprocessor?
5599 Preprocessor &pp = astUnit->getPreprocessor();
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005600 createCXTUResourceUsageEntry(*entries,
5601 CXTUResourceUsage_Preprocessor,
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +00005602 pp.getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005603
5604 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5605 createCXTUResourceUsageEntry(*entries,
5606 CXTUResourceUsage_PreprocessingRecord,
5607 pRec->getTotalMemory());
5608 }
5609
Ted Kremenekd1194fb2011-07-26 23:46:11 +00005610 createCXTUResourceUsageEntry(*entries,
5611 CXTUResourceUsage_Preprocessor_HeaderSearch,
5612 pp.getHeaderSearchInfo().getTotalMemory());
Ted Kremenek5e1db6a2011-05-04 01:38:46 +00005613
Ted Kremenekf7870022011-04-20 16:41:07 +00005614 CXTUResourceUsage usage = { (void*) entries.get(),
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005615 (unsigned) entries->size(),
5616 entries->size() ? &(*entries)[0] : 0 };
5617 entries.take();
5618 return usage;
5619}
5620
Ted Kremenekf7870022011-04-20 16:41:07 +00005621void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005622 if (usage.data)
5623 delete (MemUsageEntries*) usage.data;
5624}
5625
5626} // end extern "C"
5627
Douglas Gregor6df78732011-05-05 20:27:22 +00005628void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5629 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5630 for (unsigned I = 0; I != Usage.numEntries; ++I)
5631 fprintf(stderr, " %s: %lu\n",
5632 clang_getTUResourceUsageName(Usage.entries[I].kind),
5633 Usage.entries[I].amount);
5634
5635 clang_disposeCXTUResourceUsage(Usage);
5636}
5637
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005638//===----------------------------------------------------------------------===//
Ted Kremenek04bb7162010-01-22 22:44:15 +00005639// Misc. utility functions.
5640//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00005641
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00005642/// Default to using an 8 MB stack size on "safety" threads.
5643static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005644
5645namespace clang {
5646
5647bool RunSafely(llvm::CrashRecoveryContext &CRC,
Ted Kremenek6c53fdd2010-11-14 17:47:35 +00005648 void (*Fn)(void*), void *UserData,
5649 unsigned Size) {
5650 if (!Size)
5651 Size = GetSafetyThreadStackSize();
5652 if (Size)
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00005653 return CRC.RunSafelyOnThread(Fn, UserData, Size);
5654 return CRC.RunSafely(Fn, UserData);
5655}
5656
5657unsigned GetSafetyThreadStackSize() {
5658 return SafetyStackThreadSize;
5659}
5660
5661void SetSafetyThreadStackSize(unsigned Value) {
5662 SafetyStackThreadSize = Value;
5663}
5664
5665}
5666
Ted Kremenek04bb7162010-01-22 22:44:15 +00005667extern "C" {
5668
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00005669CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00005670 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00005671}
5672
5673} // end: extern "C"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00005674